This commit is contained in:
nik
2025-10-03 22:27:28 +03:00
parent 829fad0e17
commit 871cf7e792
16520 changed files with 2967597 additions and 3 deletions

44
node_modules/pkg-types/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,44 @@
MIT License
Copyright (c) Pooya Parsa <pooya@pi0.io> - Daniel Roe <daniel@roe.dev>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--------------------------------------------------------------------------------
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.

266
node_modules/pkg-types/README.md generated vendored Normal file
View File

@@ -0,0 +1,266 @@
# pkg-types
<!-- automd:badges color=yellow codecov -->
[![npm version](https://img.shields.io/npm/v/pkg-types?color=yellow)](https://npmjs.com/package/pkg-types)
[![npm downloads](https://img.shields.io/npm/dm/pkg-types?color=yellow)](https://npm.chart.dev/pkg-types)
[![codecov](https://img.shields.io/codecov/c/gh/unjs/pkg-types?color=yellow)](https://codecov.io/gh/unjs/pkg-types)
<!-- /automd -->
Node.js utilities and TypeScript definitions for `package.json`, `tsconfig.json`, and other configuration files.
## Install
<!-- automd:pm-i -->
```sh
# ✨ Auto-detect
npx nypm install pkg-types
# npm
npm install pkg-types
# yarn
yarn add pkg-types
# pnpm
pnpm install pkg-types
# bun
bun install pkg-types
# deno
deno install pkg-types
```
<!-- /automd -->
## Usage
### Package Configuration
#### `readPackage`
Reads any package file format (package.json, package.json5, or package.yaml) with automatic format detection.
```js
import { readPackage } from "pkg-types";
const localPackage = await readPackage();
// or
const package = await readPackage("/fully/resolved/path/to/folder");
```
#### `writePackage`
Writes package data with format detection based on file extension.
```js
import { writePackage } from "pkg-types";
await writePackage("path/to/package.json", pkg);
await writePackage("path/to/package.json5", pkg);
await writePackage("path/to/package.yaml", pkg);
```
#### `findPackage`
Finds the nearest package file (package.json, package.json5, or package.yaml).
```js
import { findPackage } from "pkg-types";
const filename = await findPackage();
// or
const filename = await findPackage("/fully/resolved/path/to/folder");
```
#### `readPackageJSON`
```js
import { readPackageJSON } from "pkg-types";
const localPackageJson = await readPackageJSON();
// or
const packageJson = await readPackageJSON("/fully/resolved/path/to/folder");
```
#### `writePackageJSON`
```js
import { writePackageJSON } from "pkg-types";
await writePackageJSON("path/to/package.json", pkg);
```
#### `resolvePackageJSON`
```js
import { resolvePackageJSON } from "pkg-types";
const filename = await resolvePackageJSON();
// or
const packageJson = await resolvePackageJSON("/fully/resolved/path/to/folder");
```
### TypeScript Configuration
#### `readTSConfig`
```js
import { readTSConfig } from "pkg-types";
const tsconfig = await readTSConfig();
// or
const tsconfig2 = await readTSConfig("/fully/resolved/path/to/folder");
```
#### `writeTSConfig`
```js
import { writeTSConfig } from "pkg-types";
await writeTSConfig("path/to/tsconfig.json", tsconfig);
```
#### `resolveTSConfig`
```js
import { resolveTSConfig } from "pkg-types";
const filename = await resolveTSConfig();
// or
const tsconfig = await resolveTSConfig("/fully/resolved/path/to/folder");
```
### File Resolution
#### `resolveFile`
```js
import { resolveFile } from "pkg-types";
const filename = await resolveFile("README.md", {
startingFrom: id,
rootPattern: /^node_modules$/,
matcher: (filename) => filename.endsWith(".md"),
});
```
#### `resolveLockFile`
Find path to the lock file (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`, `npm-shrinkwrap.json`, `bun.lockb`, `bun.lock`, `deno.lock`) or throws an error.
```js
import { resolveLockFile } from "pkg-types";
const lockfile = await resolveLockFile(".");
```
#### `findWorkspaceDir`
Try to detect workspace dir by in order:
1. Farthest workspace file (`pnpm-workspace.yaml`, `lerna.json`, `turbo.json`, `rush.json`, `deno.json`, `deno.jsonc`)
2. Closest `.git/config` file
3. Farthest lockfile
4. Farthest `package.json` file
If fails, throws an error.
```js
import { findWorkspaceDir } from "pkg-types";
const workspaceDir = await findWorkspaceDir(".");
```
### Git Configuration
#### `resolveGitConfig`
Finds closest `.git/config` file.
```js
import { resolveGitConfig } from "pkg-types";
const gitConfig = await resolveGitConfig(".")
```
#### `readGitConfig`
Finds and reads closest `.git/config` file into a JS object.
```js
import { readGitConfig } from "pkg-types";
const gitConfigObj = await readGitConfig(".")
```
#### `writeGitConfig`
Stringifies git config object into INI text format and writes it to a file.
```js
import { writeGitConfig } from "pkg-types";
await writeGitConfig(".git/config", gitConfigObj)
```
#### `parseGitConfig`
Parses a git config file in INI text format into a JavaScript object.
```js
import { parseGitConfig } from "pkg-types";
const gitConfigObj = parseGitConfig(gitConfigINI)
```
#### `stringifyGitConfig`
Stringifies a git config object into a git config file INI text format.
```js
import { stringifyGitConfig } from "pkg-types";
const gitConfigINI = stringifyGitConfig(gitConfigObj)
```
## Types
**Note:** In order to make types working, you need to install `typescript` as a devDependency.
You can directly use typed interfaces:
```ts
import type { TSConfig, PackageJSON, GitConfig } from "pkg-types";
```
You can also use define utils for type support for using in plain `.js` files and auto-complete in IDE.
```js
import type { definePackageJSON } from 'pkg-types'
const pkg = definePackageJSON({})
```
```js
import type { defineTSConfig } from 'pkg-types'
const pkg = defineTSConfig({})
```
```js
import type { defineGitConfig } from 'pkg-types'
const gitConfig = defineGitConfig({})
```
## Alternatives
- [dominikg/tsconfck](https://github.com/dominikg/tsconfck)
## License
<!-- automd:contributors license=MIT author="pi0,danielroe" -->
Published under the [MIT](https://github.com/unjs/pkg-types/blob/main/LICENSE) license.
Made by [@pi0](https://github.com/pi0), [@danielroe](https://github.com/danielroe) and [community](https://github.com/unjs/pkg-types/graphs/contributors) 💛
<br><br>
<a href="https://github.com/unjs/pkg-types/graphs/contributors">
<img src="https://contrib.rocks/image?repo=unjs/pkg-types" />
</a>
<!-- /automd -->

538
node_modules/pkg-types/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,538 @@
import { ResolveOptions as ResolveOptions$1 } from 'exsolve';
import { CompilerOptions, TypeAcquisition } from 'typescript';
/**
* Represents the options for resolving paths with additional file finding capabilities.
*/
type ResolveOptions = Omit<FindFileOptions, "startingFrom"> & ResolveOptions$1 & {
/** @deprecated: use `from` */
url?: string;
/** @deprecated: use `from` */
parent?: string;
};
/**
* Options for reading files with optional caching.
*/
type ReadOptions = {
/**
* Specifies whether the read results should be cached.
* Can be a boolean or a map to hold the cached data.
*/
cache?: boolean | Map<string, Record<string, any>>;
};
interface FindFileOptions {
/**
* The starting directory for the search.
* @default . (same as `process.cwd()`)
*/
startingFrom?: string;
/**
* A pattern to match a path segment above which you don't want to ascend
* @default /^node_modules$/
*/
rootPattern?: RegExp;
/**
* If true, search starts from root level descending into subdirectories
*/
reverse?: boolean;
/**
* A matcher that can evaluate whether the given path is a valid file (for example,
* by testing whether the file path exists.
*
* @default fs.statSync(path).isFile()
*/
test?: (filePath: string) => boolean | undefined | Promise<boolean | undefined>;
}
/**
* Asynchronously finds a file by name, starting from the specified directory and traversing up (or down if reverse).
* @param filename - The name of the file to find.
* @param _options - Options to customise the search behaviour.
* @returns a promise that resolves to the path of the file found.
* @throws Will throw an error if the file cannot be found.
*/
declare function findFile(filename: string | string[], _options?: FindFileOptions): Promise<string>;
/**
* Asynchronously finds the next file with the given name, starting in the given directory and moving up.
* Alias for findFile without reversing the search.
* @param filename - The name of the file to find.
* @param options - Options to customise the search behaviour.
* @returns A promise that resolves to the path of the next file found.
*/
declare function findNearestFile(filename: string | string[], options?: FindFileOptions): Promise<string>;
/**
* Asynchronously finds the furthest file with the given name, starting from the root directory and moving downwards.
* This is essentially the reverse of `findNearestFile'.
* @param filename - The name of the file to find.
* @param options - Options to customise the search behaviour, with reverse set to true.
* @returns A promise that resolves to the path of the farthest file found.
*/
declare function findFarthestFile(filename: string | string[], options?: FindFileOptions): Promise<string>;
type StripEnums<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends boolean ? T[K] : T[K] extends string ? T[K] : T[K] extends object ? T[K] : T[K] extends Array<any> ? T[K] : T[K] extends undefined ? undefined : any;
};
interface TSConfig {
compilerOptions?: StripEnums<CompilerOptions>;
exclude?: string[];
compileOnSave?: boolean;
extends?: string | string[];
files?: string[];
include?: string[];
typeAcquisition?: TypeAcquisition;
references?: {
path: string;
}[];
}
/**
* Defines a TSConfig structure.
* @param tsconfig - The contents of `tsconfig.json` as an object. See {@link TSConfig}.
* @returns the same `tsconfig.json` object.
*/
declare function defineTSConfig(tsconfig: TSConfig): TSConfig;
/**
* Asynchronously reads a `tsconfig.json` file.
* @param id - The path to the `tsconfig.json` file, defaults to the current working directory.
* @param options - The options for resolving and reading the file. See {@link ResolveOptions}.
* @returns a promise resolving to the parsed `tsconfig.json` object.
*/
declare function readTSConfig(id?: string, options?: ResolveOptions & ReadOptions): Promise<TSConfig>;
/**
* Asynchronously writes data to a `tsconfig.json` file.
* @param path - The path to the file where the `tsconfig.json` is written.
* @param tsconfig - The `tsconfig.json` object to write. See {@link TSConfig}.
*/
declare function writeTSConfig(path: string, tsconfig: TSConfig): Promise<void>;
/**
* Resolves the path to the nearest `tsconfig.json` file from a given directory.
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest `tsconfig.json` file.
*/
declare function resolveTSConfig(id?: string, options?: ResolveOptions): Promise<string>;
interface PackageJson {
/**
* The name is what your thing is called.
* Some rules:
* - The name must be less than or equal to 214 characters. This includes the scope for scoped packages.
* - The name cant start with a dot or an underscore.
* - New packages must not have uppercase letters in the name.
* - The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name cant contain any non-URL-safe characters.
*/
name?: string;
/**
* Version must be parseable by `node-semver`, which is bundled with npm as a dependency. (`npm install semver` to use it yourself.)
*/
version?: string;
/**
* Put a description in it. Its a string. This helps people discover your package, as its listed in `npm search`.
*/
description?: string;
/**
* Put keywords in it. Its an array of strings. This helps people discover your package as its listed in `npm search`.
*/
keywords?: string[];
/**
* The url to the project homepage.
*/
homepage?: string;
/**
* The url to your projects issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.
*/
bugs?: string | {
url?: string;
email?: string;
};
/**
* You should specify a license for your package so that people know how they are permitted to use it, and any restrictions youre placing on it.
*/
license?: string;
/**
* Specify the place where your code lives. This is helpful for people who want to contribute. If the git repo is on GitHub, then the `npm docs` command will be able to find you.
* For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same shortcut syntax you use for npm install:
*/
repository?: string | {
type: string;
url: string;
/**
* If the `package.json` for your package is not in the root directory (for example if it is part of a monorepo), you can specify the directory in which it lives:
*/
directory?: string;
};
/**
* The `scripts` field is a dictionary containing script commands that are run at various times in the lifecycle of your package.
*/
scripts?: PackageJsonScripts;
/**
* If you set `"private": true` in your package.json, then npm will refuse to publish it.
*/
private?: boolean;
/**
* The “author” is one person.
*/
author?: PackageJsonPerson;
/**
* “contributors” is an array of people.
*/
contributors?: PackageJsonPerson[];
/**
* An object containing a URL that provides up-to-date information
* about ways to help fund development of your package,
* a string URL, or an array of objects and string URLs
*/
funding?: PackageJsonFunding | PackageJsonFunding[];
/**
* The optional `files` field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. File patterns follow a similar syntax to `.gitignore`, but reversed: including a file, directory, or glob pattern (`*`, `**\/*`, and such) will make it so that file is included in the tarball when its packed. Omitting the field will make it default to `["*"]`, which means it will include all files.
*/
files?: string[];
/**
* The main field is a module ID that is the primary entry point to your program. That is, if your package is named `foo`, and a user installs it, and then does `require("foo")`, then your main modules exports object will be returned.
* This should be a module ID relative to the root of your package folder.
* For most modules, it makes the most sense to have a main script and often not much else.
*/
main?: string;
/**
* If your module is meant to be used client-side the browser field should be used instead of the main field. This is helpful to hint users that it might rely on primitives that arent available in Node.js modules. (e.g. window)
*/
browser?: string | Record<string, string | false>;
/**
* The `unpkg` field is used to specify the URL to a UMD module for your package. This is used by default in the unpkg.com CDN service.
*/
unpkg?: string;
/**
* A map of command name to local file name. On install, npm will symlink that file into `prefix/bin` for global installs, or `./node_modules/.bin/` for local installs.
*/
bin?: string | Record<string, string>;
/**
* Specify either a single file or an array of filenames to put in place for the `man` program to find.
*/
man?: string | string[];
/**
* Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.
*/
dependencies?: Record<string, string>;
/**
* If someone is planning on downloading and using your module in their program, then they probably dont want or need to download and build the external test or documentation framework that you use.
* In this case, its best to map these additional items in a `devDependencies` object.
*/
devDependencies?: Record<string, string>;
/**
* If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the `optionalDependencies` object. This is a map of package name to version or url, just like the `dependencies` object. The difference is that build failures do not cause installation to fail.
*/
optionalDependencies?: Record<string, string>;
/**
* In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a `require` of this host. This is usually referred to as a plugin. Notably, your module may be exposing a specific interface, expected and specified by the host documentation.
*/
peerDependencies?: Record<string, string>;
/**
* TypeScript typings, typically ending by `.d.ts`.
*/
types?: string;
/**
* This field is synonymous with `types`.
*/
typings?: string;
/**
* Non-Standard Node.js alternate entry-point to main.
* An initial implementation for supporting CJS packages (from main), and use module for ESM modules.
*/
module?: string;
/**
* Make main entry-point be loaded as an ESM module, support "export" syntax instead of "require"
*
* Docs:
* - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_package_json_type_field
*
* @default 'commonjs'
* @since Node.js v14
*/
type?: "module" | "commonjs";
/**
* Alternate and extensible alternative to "main" entry point.
*
* When using `{type: "module"}`, any ESM module file MUST end with `.mjs` extension.
*
* Docs:
* - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_exports_sugar
*
* @since Node.js v12.7
*/
exports?: PackageJsonExports;
/**
* Docs:
* - https://nodejs.org/api/packages.html#imports
*/
imports?: Record<string, string | Record<string, string>>;
/**
* The field is used to define a set of sub-packages (or workspaces) within a monorepo.
*
* This field is an array of glob patterns or an object with specific configurations for managing
* multiple packages in a single repository.
*/
workspaces?: string[] | {
/**
* Workspace package paths. Glob patterns are supported.
*/
packages?: string[];
/**
* Packages to block from hoisting to the workspace root.
* Uses glob patterns to match module paths in the dependency tree.
*
* Docs:
* - https://classic.yarnpkg.com/blog/2018/02/15/nohoist/
*/
nohoist?: string[];
};
/**
* The field is used to specify different TypeScript declaration files for
* different versions of TypeScript, allowing for version-specific type definitions.
*/
typesVersions?: Record<string, Record<string, string[]>>;
/**
* You can specify which operating systems your module will run on:
* ```json
* {
* "os": ["darwin", "linux"]
* }
* ```
* You can also block instead of allowing operating systems, just prepend the blocked os with a '!':
* ```json
* {
* "os": ["!win32"]
* }
* ```
* The host operating system is determined by `process.platform`
* It is allowed to both block and allow an item, although there isn't any good reason to do this.
*/
os?: string[];
/**
* If your code only runs on certain cpu architectures, you can specify which ones.
* ```json
* {
* "cpu": ["x64", "ia32"]
* }
* ```
* Like the `os` option, you can also block architectures:
* ```json
* {
* "cpu": ["!arm", "!mips"]
* }
* ```
* The host architecture is determined by `process.arch`
*/
cpu?: string[];
/**
* This is a set of config values that will be used at publish-time.
*/
publishConfig?: {
/**
* The registry that will be used if the package is published.
*/
registry?: string;
/**
* The tag that will be used if the package is published.
*/
tag?: string;
/**
* The access level that will be used if the package is published.
*/
access?: "public" | "restricted";
/**
* **pnpm-only**
*
* By default, for portability reasons, no files except those listed in
* the bin field will be marked as executable in the resulting package
* archive. The executableFiles field lets you declare additional fields
* that must have the executable flag (+x) set even if
* they aren't directly accessible through the bin field.
*/
executableFiles?: string[];
/**
* **pnpm-only**
*
* You also can use the field `publishConfig.directory` to customize
* the published subdirectory relative to the current `package.json`.
*
* It is expected to have a modified version of the current package in
* the specified directory (usually using third party build tools).
*/
directory?: string;
/**
* **pnpm-only**
*
* When set to `true`, the project will be symlinked from the
* `publishConfig.directory` location during local development.
* @default true
*/
linkDirectory?: boolean;
} & Pick<PackageJson, "bin" | "main" | "exports" | "types" | "typings" | "module" | "browser" | "unpkg" | "typesVersions" | "os" | "cpu">;
/**
* See: https://nodejs.org/api/packages.html#packagemanager
* This field defines which package manager is expected to be used when working on the current project.
* Should be of the format: `<name>@<version>[#hash]`
*/
packageManager?: string;
[key: string]: any;
}
/**
* See: https://docs.npmjs.com/cli/v11/using-npm/scripts#pre--post-scripts
*/
type PackageJsonScriptWithPreAndPost<S extends string> = S | `${"pre" | "post"}${S}`;
/**
* See: https://docs.npmjs.com/cli/v11/using-npm/scripts#life-cycle-operation-order
*/
type PackageJsonNpmLifeCycleScripts = "dependencies" | "prepublishOnly" | PackageJsonScriptWithPreAndPost<"install" | "pack" | "prepare" | "publish" | "restart" | "start" | "stop" | "test" | "version">;
/**
* See: https://pnpm.io/scripts#lifecycle-scripts
*/
type PackageJsonPnpmLifeCycleScripts = "pnpm:devPreinstall";
type PackageJsonCommonScripts = "build" | "coverage" | "deploy" | "dev" | "format" | "lint" | "preview" | "release" | "typecheck" | "watch";
type PackageJsonScriptName = PackageJsonCommonScripts | PackageJsonNpmLifeCycleScripts | PackageJsonPnpmLifeCycleScripts | (string & {});
type PackageJsonScripts = {
[P in PackageJsonScriptName]?: string;
};
/**
* A “person” is an object with a “name” field and optionally “url” and “email”. Or you can shorten that all into a single string, and npm will parse it for you.
*/
type PackageJsonPerson = string | {
name: string;
email?: string;
url?: string;
};
type PackageJsonFunding = string | {
url: string;
type?: string;
};
type PackageJsonExportKey = "." | "import" | "require" | "types" | "node" | "browser" | "default" | (string & {});
type PackageJsonExportsObject = {
[P in PackageJsonExportKey]?: string | PackageJsonExportsObject | Array<string | PackageJsonExportsObject>;
};
type PackageJsonExports = string | PackageJsonExportsObject | Array<string | PackageJsonExportsObject>;
/**
* Defines a PackageJson structure.
* @param pkg - The `package.json` content as an object. See {@link PackageJson}.
* @returns the same `package.json` object.
*/
declare function definePackageJSON(pkg: PackageJson): PackageJson;
/**
* Finds the nearest package file (package.json, package.json5, or package.yaml).
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest package file.
*/
declare function findPackage(id?: string, options?: ResolveOptions): Promise<string>;
/**
* Reads any package file format (package.json, package.json5, or package.yaml).
* @param id - The path identifier for the package file, defaults to the current working directory.
* @param options - The options for resolving and reading the file. See {@link ResolveOptions}.
* @returns a promise resolving to the parsed `package.json` object.
*/
declare function readPackage(id?: string, options?: ResolveOptions & ReadOptions): Promise<PackageJson>;
/**
* Writes data to a package file with format detection based on file extension.
* @param path - The path to the file where the package data is written.
* @param pkg - The package object to write. See {@link PackageJson}.
*/
declare function writePackage(path: string, pkg: PackageJson): Promise<void>;
/**
* Asynchronously reads a `package.json` file.
* @param id - The path identifier for the package.json, defaults to the current working directory.
* @param options - The options for resolving and reading the file. See {@link ResolveOptions}.
* @returns a promise resolving to the parsed `package.json` object.
*/
declare function readPackageJSON(id?: string, options?: ResolveOptions & ReadOptions): Promise<PackageJson>;
/**
* Asynchronously writes data to a `package.json` file.
* @param path - The path to the file where the `package.json` is written.
* @param pkg - The `package.json` object to write. See {@link PackageJson}.
*/
declare function writePackageJSON(path: string, pkg: PackageJson): Promise<void>;
/**
* Resolves the path to the nearest `package.json` file from a given directory.
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest `package.json` file.
*/
declare function resolvePackageJSON(id?: string, options?: ResolveOptions): Promise<string>;
/**
* Resolves the path to the nearest lockfile from a given directory.
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest lockfile.
*/
declare function resolveLockfile(id?: string, options?: ResolveOptions): Promise<string>;
type WorkspaceTestName = "workspaceFile" | "gitConfig" | "lockFile" | "packageJson";
/**
* Detects the workspace directory based on common project markers .
* Throws an error if the workspace root cannot be detected.
*
* @param id - The base path to search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns a promise resolving to the path of the detected workspace directory.
*/
declare function findWorkspaceDir(id?: string, options?: ResolveOptions & Partial<Record<WorkspaceTestName, boolean | "closest" | "furthest">> & {
tests?: WorkspaceTestName[];
}): Promise<string>;
declare function updatePackage(id: string, callback: (pkg: PackageJson) => PackageJson | void | Promise<PackageJson | void>, options?: ResolveOptions & ReadOptions): Promise<void>;
declare function sortPackage(pkg: PackageJson): PackageJson;
declare function normalizePackage(pkg: PackageJson): PackageJson;
interface GitRemote {
[key: string]: unknown;
name?: string;
url?: string;
fetch?: string;
}
interface GitBranch {
[key: string]: unknown;
remote?: string;
merge?: string;
description?: string;
rebase?: boolean;
}
interface GitCoreConfig {
[key: string]: unknown;
}
interface GitConfigUser {
[key: string]: unknown;
name?: string;
email?: string;
}
interface GitConfig {
[key: string]: unknown;
core?: GitCoreConfig;
user?: GitConfigUser;
remote?: Record<string, GitRemote>;
branch?: Record<string, GitBranch>;
}
/**
* Defines a git config object.
*/
declare function defineGitConfig(config: GitConfig): GitConfig;
/**
* Finds closest `.git/config` file.
*/
declare function resolveGitConfig(dir: string, opts?: ResolveOptions): Promise<string>;
/**
* Finds and reads closest `.git/config` file into a JS object.
*/
declare function readGitConfig(dir: string, opts?: ResolveOptions): Promise<GitConfig>;
/**
* Stringifies git config object into INI text format and writes it to a file.
*/
declare function writeGitConfig(path: string, config: GitConfig): Promise<void>;
/**
* Parses a git config file in INI text format into a JavaScript object.
*/
declare function parseGitConfig(ini: string): GitConfig;
/**
* Stringifies a git config object into a git config file INI text format.
*/
declare function stringifyGitConfig(config: GitConfig): string;
export { defineGitConfig, definePackageJSON, defineTSConfig, findFarthestFile, findFile, findNearestFile, findPackage, findWorkspaceDir, normalizePackage, parseGitConfig, readGitConfig, readPackage, readPackageJSON, readTSConfig, resolveGitConfig, resolveLockfile, resolvePackageJSON, resolveTSConfig, sortPackage, stringifyGitConfig, updatePackage, writeGitConfig, writePackage, writePackageJSON, writeTSConfig };
export type { FindFileOptions, GitBranch, GitConfig, GitConfigUser, GitCoreConfig, GitRemote, PackageJson, PackageJsonExports, PackageJsonPerson, ReadOptions, ResolveOptions, TSConfig };

371
node_modules/pkg-types/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,371 @@
import { statSync, promises } from 'node:fs';
import { resolve, join, normalize, isAbsolute, dirname } from 'pathe';
import { parseJSONC, stringifyJSONC, parseJSON, stringifyJSON, parseJSON5, parseYAML, stringifyJSON5, stringifyYAML } from 'confbox';
import { resolveModulePath } from 'exsolve';
import { fileURLToPath } from 'node:url';
import { readFile, writeFile } from 'node:fs/promises';
import { parseINI, stringifyINI } from 'confbox/ini';
const defaultFindOptions = {
startingFrom: ".",
rootPattern: /^node_modules$/,
reverse: false,
test: (filePath) => {
try {
if (statSync(filePath).isFile()) {
return true;
}
} catch {
}
}
};
async function findFile(filename, _options = {}) {
const filenames = Array.isArray(filename) ? filename : [filename];
const options = { ...defaultFindOptions, ..._options };
const basePath = resolve(options.startingFrom);
const leadingSlash = basePath[0] === "/";
const segments = basePath.split("/").filter(Boolean);
if (filenames.includes(segments.at(-1)) && await options.test(basePath)) {
return basePath;
}
if (leadingSlash) {
segments[0] = "/" + segments[0];
}
let root = segments.findIndex((r) => r.match(options.rootPattern));
if (root === -1) {
root = 0;
}
if (options.reverse) {
for (let index = root + 1; index <= segments.length; index++) {
for (const filename2 of filenames) {
const filePath = join(...segments.slice(0, index), filename2);
if (await options.test(filePath)) {
return filePath;
}
}
}
} else {
for (let index = segments.length; index > root; index--) {
for (const filename2 of filenames) {
const filePath = join(...segments.slice(0, index), filename2);
if (await options.test(filePath)) {
return filePath;
}
}
}
}
throw new Error(
`Cannot find matching ${filename} in ${options.startingFrom} or parent directories`
);
}
function findNearestFile(filename, options = {}) {
return findFile(filename, options);
}
function findFarthestFile(filename, options = {}) {
return findFile(filename, { ...options, reverse: true });
}
function _resolvePath(id, opts = {}) {
if (id instanceof URL || id.startsWith("file://")) {
return normalize(fileURLToPath(id));
}
if (isAbsolute(id)) {
return normalize(id);
}
return resolveModulePath(id, {
...opts,
from: opts.from || opts.parent || opts.url
});
}
const FileCache$1 = /* @__PURE__ */ new Map();
function defineTSConfig(tsconfig) {
return tsconfig;
}
async function readTSConfig(id, options = {}) {
const resolvedPath = await resolveTSConfig(id, options);
const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache$1;
if (options.cache && cache.has(resolvedPath)) {
return cache.get(resolvedPath);
}
const text = await promises.readFile(resolvedPath, "utf8");
const parsed = parseJSONC(text);
cache.set(resolvedPath, parsed);
return parsed;
}
async function writeTSConfig(path, tsconfig) {
await promises.writeFile(path, stringifyJSONC(tsconfig));
}
async function resolveTSConfig(id = process.cwd(), options = {}) {
return findNearestFile("tsconfig.json", {
...options,
startingFrom: _resolvePath(id, options)
});
}
const lockFiles = [
"yarn.lock",
"package-lock.json",
"pnpm-lock.yaml",
"npm-shrinkwrap.json",
"bun.lockb",
"bun.lock",
"deno.lock"
];
const packageFiles = ["package.json", "package.json5", "package.yaml"];
const workspaceFiles = [
"pnpm-workspace.yaml",
"lerna.json",
"turbo.json",
"rush.json",
"deno.json",
"deno.jsonc"
];
const FileCache = /* @__PURE__ */ new Map();
function definePackageJSON(pkg) {
return pkg;
}
async function findPackage(id = process.cwd(), options = {}) {
return findNearestFile(packageFiles, {
...options,
startingFrom: _resolvePath(id, options)
});
}
async function readPackage(id, options = {}) {
const resolvedPath = await findPackage(id, options);
const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache;
if (options.cache && cache.has(resolvedPath)) {
return cache.get(resolvedPath);
}
const blob = await promises.readFile(resolvedPath, "utf8");
let parsed;
if (resolvedPath.endsWith(".json5")) {
parsed = parseJSON5(blob);
} else if (resolvedPath.endsWith(".yaml")) {
parsed = parseYAML(blob);
} else {
try {
parsed = parseJSON(blob);
} catch {
parsed = parseJSONC(blob);
}
}
cache.set(resolvedPath, parsed);
return parsed;
}
async function writePackage(path, pkg) {
let content;
if (path.endsWith(".json5")) {
content = stringifyJSON5(pkg);
} else if (path.endsWith(".yaml")) {
content = stringifyYAML(pkg);
} else {
content = stringifyJSON(pkg);
}
await promises.writeFile(path, content);
}
async function readPackageJSON(id, options = {}) {
const resolvedPath = await resolvePackageJSON(id, options);
const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : FileCache;
if (options.cache && cache.has(resolvedPath)) {
return cache.get(resolvedPath);
}
const blob = await promises.readFile(resolvedPath, "utf8");
let parsed;
try {
parsed = parseJSON(blob);
} catch {
parsed = parseJSONC(blob);
}
cache.set(resolvedPath, parsed);
return parsed;
}
async function writePackageJSON(path, pkg) {
await promises.writeFile(path, stringifyJSON(pkg));
}
async function resolvePackageJSON(id = process.cwd(), options = {}) {
return findNearestFile("package.json", {
...options,
startingFrom: _resolvePath(id, options)
});
}
async function resolveLockfile(id = process.cwd(), options = {}) {
return findNearestFile(lockFiles, {
...options,
startingFrom: _resolvePath(id, options)
});
}
const workspaceTests = {
workspaceFile: (opts) => findFile(workspaceFiles, opts).then((r) => dirname(r)),
gitConfig: (opts) => findFile(".git/config", opts).then((r) => resolve(r, "../..")),
lockFile: (opts) => findFile(lockFiles, opts).then((r) => dirname(r)),
packageJson: (opts) => findFile(packageFiles, opts).then((r) => dirname(r))
};
async function findWorkspaceDir(id = process.cwd(), options = {}) {
const startingFrom = _resolvePath(id, options);
const tests = options.tests || ["workspaceFile", "gitConfig", "lockFile", "packageJson"];
for (const testName of tests) {
const test = workspaceTests[testName];
if (options[testName] === false || !test) {
continue;
}
const direction = options[testName] || (testName === "gitConfig" ? "closest" : "furthest");
const detected = await test({
...options,
startingFrom,
reverse: direction === "furthest"
}).catch(() => {
});
if (detected) {
return detected;
}
}
throw new Error(`Cannot detect workspace root from ${id}`);
}
async function updatePackage(id, callback, options = {}) {
const resolvedPath = await findPackage(id, options);
const pkg = await readPackage(id, options);
const proxy = new Proxy(pkg, {
get(target, prop) {
if (typeof prop === "string" && objectKeys.has(prop) && !Object.hasOwn(target, prop)) {
target[prop] = {};
}
return Reflect.get(target, prop);
}
});
const updated = await callback(proxy) || pkg;
await writePackage(resolvedPath, updated);
}
function sortPackage(pkg) {
const sorted = {};
const originalKeys = Object.keys(pkg);
const knownKeysPresent = defaultFieldOrder.filter(
(key) => Object.hasOwn(pkg, key)
);
for (const key of originalKeys) {
const currentIndex = knownKeysPresent.indexOf(key);
if (currentIndex === -1) {
sorted[key] = pkg[key];
continue;
}
for (let i = 0; i <= currentIndex; i++) {
const knownKey = knownKeysPresent[i];
if (!Object.hasOwn(sorted, knownKey)) {
sorted[knownKey] = pkg[knownKey];
}
}
}
for (const key of [...dependencyKeys, "scripts"]) {
const value = sorted[key];
if (isObject(value)) {
sorted[key] = sortObject(value);
}
}
return sorted;
}
function normalizePackage(pkg) {
const normalized = sortPackage(pkg);
for (const key of dependencyKeys) {
if (!Object.hasOwn(normalized, key)) {
continue;
}
const value = normalized[key];
if (!isObject(value)) {
delete normalized[key];
}
}
return normalized;
}
function isObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function sortObject(obj) {
return Object.fromEntries(
Object.entries(obj).sort(([a], [b]) => a.localeCompare(b))
);
}
const dependencyKeys = [
"dependencies",
"devDependencies",
"optionalDependencies",
"peerDependencies"
];
const objectKeys = /* @__PURE__ */ new Set([
"typesVersions",
"scripts",
"resolutions",
"overrides",
"dependencies",
"devDependencies",
"dependenciesMeta",
"peerDependencies",
"peerDependenciesMeta",
"optionalDependencies",
"engines",
"publishConfig"
]);
const defaultFieldOrder = [
"$schema",
"name",
"version",
"private",
"description",
"keywords",
"homepage",
"bugs",
"repository",
"funding",
"license",
"author",
"sideEffects",
"type",
"imports",
"exports",
"main",
"module",
"browser",
"types",
"typesVersions",
"typings",
"bin",
"man",
"files",
"workspaces",
"scripts",
"resolutions",
"overrides",
"dependencies",
"devDependencies",
"dependenciesMeta",
"peerDependencies",
"peerDependenciesMeta",
"optionalDependencies",
"bundledDependencies",
"bundleDependencies",
"packageManager",
"engines",
"publishConfig"
];
function defineGitConfig(config) {
return config;
}
async function resolveGitConfig(dir, opts) {
return findNearestFile(".git/config", { ...opts, startingFrom: dir });
}
async function readGitConfig(dir, opts) {
const path = await resolveGitConfig(dir, opts);
const ini = await readFile(path, "utf8");
return parseGitConfig(ini);
}
async function writeGitConfig(path, config) {
await writeFile(path, stringifyGitConfig(config));
}
function parseGitConfig(ini) {
return parseINI(ini.replaceAll(/^\[(\w+) "(.+)"\]$/gm, "[$1.$2]"));
}
function stringifyGitConfig(config) {
return stringifyINI(config).replaceAll(/^\[(\w+)\.(\w+)\]$/gm, '[$1 "$2"]');
}
export { defineGitConfig, definePackageJSON, defineTSConfig, findFarthestFile, findFile, findNearestFile, findPackage, findWorkspaceDir, normalizePackage, parseGitConfig, readGitConfig, readPackage, readPackageJSON, readTSConfig, resolveGitConfig, resolveLockfile, resolvePackageJSON, resolveTSConfig, sortPackage, stringifyGitConfig, updatePackage, writeGitConfig, writePackage, writePackageJSON, writeTSConfig };

45
node_modules/pkg-types/package.json generated vendored Normal file
View File

@@ -0,0 +1,45 @@
{
"name": "pkg-types",
"version": "2.3.0",
"description": "Node.js utilities and TypeScript definitions for `package.json` and `tsconfig.json`",
"repository": "unjs/pkg-types",
"license": "MIT",
"sideEffects": false,
"exports": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"types": "./dist/index.d.mts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"dev": "vitest --typecheck",
"lint": "eslint && prettier -c src test",
"lint:fix": "automd && eslint --fix . && prettier -w src test",
"prepack": "pnpm build",
"release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
"test": "vitest run --typecheck --coverage"
},
"dependencies": {
"confbox": "^0.2.2",
"exsolve": "^1.0.7",
"pathe": "^2.0.3"
},
"devDependencies": {
"@types/node": "^24.3.0",
"@vitest/coverage-v8": "^3.2.4",
"automd": "^0.4.0",
"changelogen": "^0.6.2",
"eslint": "^9.33.0",
"eslint-config-unjs": "^0.5.0",
"expect-type": "^1.2.2",
"jiti": "^2.5.1",
"prettier": "^3.6.2",
"typescript": "^5.9.2",
"unbuild": "^3.6.1",
"vitest": "^3.2.4"
},
"packageManager": "pnpm@10.14.0"
}