前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
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.
+55
View File
@@ -0,0 +1,55 @@
# local-pkg
[![NPM version](https://img.shields.io/npm/v/local-pkg?color=a1b858&label=)](https://www.npmjs.com/package/local-pkg)
Get information on local packages. Works on both CJS and ESM.
## Install
```bash
npm i local-pkg
```
## Usage
```ts
import {
getPackageInfo,
importModule,
isPackageExists,
resolveModule,
} from 'local-pkg'
isPackageExists('local-pkg') // true
isPackageExists('foo') // false
await getPackageInfo('local-pkg')
/* {
* name: "local-pkg",
* version: "0.1.0",
* rootPath: "/path/to/node_modules/local-pkg",
* packageJson: {
* ...
* }
* }
*/
// similar to `require.resolve` but works also in ESM
resolveModule('local-pkg')
// '/path/to/node_modules/local-pkg/dist/index.cjs'
// similar to `await import()` but works also in CJS
const { importModule } = await importModule('local-pkg')
```
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu)
+190
View File
@@ -0,0 +1,190 @@
'use strict';
const fs = require('node:fs');
const node_module = require('node:module');
const path = require('node:path');
const process = require('node:process');
const fsPromises = require('node:fs/promises');
const node_url = require('node:url');
const mlly = require('mlly');
const macro = require('quansync/macro');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
const path__default = /*#__PURE__*/_interopDefaultCompat(path);
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
const fsPromises__default = /*#__PURE__*/_interopDefaultCompat(fsPromises);
const toPath = urlOrPath => urlOrPath instanceof URL ? node_url.fileURLToPath(urlOrPath) : urlOrPath;
async function findUp$1(name, {
cwd = process__default.cwd(),
type = 'file',
stopAt,
} = {}) {
let directory = path__default.resolve(toPath(cwd) ?? '');
const {root} = path__default.parse(directory);
stopAt = path__default.resolve(directory, toPath(stopAt ?? root));
const isAbsoluteName = path__default.isAbsolute(name);
while (directory) {
const filePath = isAbsoluteName ? name : path__default.join(directory, name);
try {
const stats = await fsPromises__default.stat(filePath); // eslint-disable-line no-await-in-loop
if ((type === 'file' && stats.isFile()) || (type === 'directory' && stats.isDirectory())) {
return filePath;
}
} catch {}
if (directory === stopAt || directory === root) {
break;
}
directory = path__default.dirname(directory);
}
}
function findUpSync(name, {
cwd = process__default.cwd(),
type = 'file',
stopAt,
} = {}) {
let directory = path__default.resolve(toPath(cwd) ?? '');
const {root} = path__default.parse(directory);
stopAt = path__default.resolve(directory, toPath(stopAt) ?? root);
const isAbsoluteName = path__default.isAbsolute(name);
while (directory) {
const filePath = isAbsoluteName ? name : path__default.join(directory, name);
try {
const stats = fs__default.statSync(filePath, {throwIfNoEntry: false});
if ((type === 'file' && stats?.isFile()) || (type === 'directory' && stats?.isDirectory())) {
return filePath;
}
} catch {}
if (directory === stopAt || directory === root) {
break;
}
directory = path__default.dirname(directory);
}
}
function _resolve(path$1, options = {}) {
if (options.platform === "auto" || !options.platform)
options.platform = process__default.platform === "win32" ? "win32" : "posix";
if (process__default.versions.pnp) {
const paths = options.paths || [];
if (paths.length === 0)
paths.push(process__default.cwd());
const targetRequire = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
try {
return targetRequire.resolve(path$1, { paths });
} catch {
}
}
const modulePath = mlly.resolvePathSync(path$1, {
url: options.paths
});
if (options.platform === "win32")
return path.win32.normalize(modulePath);
return modulePath;
}
function resolveModule(name, options = {}) {
try {
return _resolve(name, options);
} catch {
return void 0;
}
}
async function importModule(path) {
const i = await import(path);
if (i)
return mlly.interopDefault(i);
return i;
}
function isPackageExists(name, options = {}) {
return !!resolvePackage(name, options);
}
function getPackageJsonPath(name, options = {}) {
const entry = resolvePackage(name, options);
if (!entry)
return;
return searchPackageJSON(entry);
}
const readFile = macro.quansync({
async: (id) => fs__default.promises.readFile(id, "utf8"),
sync: (id) => fs__default.readFileSync(id, "utf8")
});
const getPackageInfo = macro.quansync(function* (name, options = {}) {
const packageJsonPath = getPackageJsonPath(name, options);
if (!packageJsonPath)
return;
const packageJson = JSON.parse(yield readFile(packageJsonPath));
return {
name,
version: packageJson.version,
rootPath: path.dirname(packageJsonPath),
packageJsonPath,
packageJson
};
});
const getPackageInfoSync = getPackageInfo.sync;
function resolvePackage(name, options = {}) {
try {
return _resolve(`${name}/package.json`, options);
} catch {
}
try {
return _resolve(name, options);
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
console.error(e);
return false;
}
}
function searchPackageJSON(dir) {
let packageJsonPath;
while (true) {
if (!dir)
return;
const newDir = path.dirname(dir);
if (newDir === dir)
return;
dir = newDir;
packageJsonPath = path.join(dir, "package.json");
if (fs__default.existsSync(packageJsonPath))
break;
}
return packageJsonPath;
}
const findUp = macro.quansync({
sync: findUpSync,
async: findUp$1
});
const loadPackageJSON = macro.quansync(function* (cwd = process__default.cwd()) {
const path = yield findUp("package.json", { cwd });
if (!path || !fs__default.existsSync(path))
return null;
return JSON.parse(yield readFile(path));
});
const loadPackageJSONSync = loadPackageJSON.sync;
const isPackageListed = macro.quansync(function* (name, cwd) {
const pkg = (yield loadPackageJSON(cwd)) || {};
return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
});
const isPackageListedSync = isPackageListed.sync;
exports.getPackageInfo = getPackageInfo;
exports.getPackageInfoSync = getPackageInfoSync;
exports.importModule = importModule;
exports.isPackageExists = isPackageExists;
exports.isPackageListed = isPackageListed;
exports.isPackageListedSync = isPackageListedSync;
exports.loadPackageJSON = loadPackageJSON;
exports.loadPackageJSONSync = loadPackageJSONSync;
exports.resolveModule = resolveModule;
+42
View File
@@ -0,0 +1,42 @@
import * as quansync_types from 'quansync/types';
import { PackageJson } from 'pkg-types';
interface PackageInfo {
name: string;
rootPath: string;
packageJsonPath: string;
version: string;
packageJson: PackageJson;
}
interface PackageResolvingOptions {
paths?: string[];
/**
* @default 'auto'
* Resolve path as posix or win32
*/
platform?: 'posix' | 'win32' | 'auto';
}
declare function resolveModule(name: string, options?: PackageResolvingOptions): string | undefined;
declare function importModule<T = any>(path: string): Promise<T>;
declare function isPackageExists(name: string, options?: PackageResolvingOptions): boolean;
declare const getPackageInfo: quansync_types.QuansyncFn<{
name: string;
version: string | undefined;
rootPath: string;
packageJsonPath: string;
packageJson: PackageJson;
} | undefined, [name: string, options?: PackageResolvingOptions | undefined]>;
declare const getPackageInfoSync: (name: string, options?: PackageResolvingOptions | undefined) => {
name: string;
version: string | undefined;
rootPath: string;
packageJsonPath: string;
packageJson: PackageJson;
} | undefined;
declare const loadPackageJSON: quansync_types.QuansyncFn<PackageJson | null, [cwd?: Args[0] | undefined]>;
declare const loadPackageJSONSync: (cwd?: Args[0] | undefined) => PackageJson | null;
declare const isPackageListed: quansync_types.QuansyncFn<boolean, [name: string, cwd?: string | undefined]>;
declare const isPackageListedSync: (name: string, cwd?: string | undefined) => boolean;
export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, isPackageListedSync, loadPackageJSON, loadPackageJSONSync, resolveModule };
export type { PackageInfo, PackageResolvingOptions };
+42
View File
@@ -0,0 +1,42 @@
import * as quansync_types from 'quansync/types';
import { PackageJson } from 'pkg-types';
interface PackageInfo {
name: string;
rootPath: string;
packageJsonPath: string;
version: string;
packageJson: PackageJson;
}
interface PackageResolvingOptions {
paths?: string[];
/**
* @default 'auto'
* Resolve path as posix or win32
*/
platform?: 'posix' | 'win32' | 'auto';
}
declare function resolveModule(name: string, options?: PackageResolvingOptions): string | undefined;
declare function importModule<T = any>(path: string): Promise<T>;
declare function isPackageExists(name: string, options?: PackageResolvingOptions): boolean;
declare const getPackageInfo: quansync_types.QuansyncFn<{
name: string;
version: string | undefined;
rootPath: string;
packageJsonPath: string;
packageJson: PackageJson;
} | undefined, [name: string, options?: PackageResolvingOptions | undefined]>;
declare const getPackageInfoSync: (name: string, options?: PackageResolvingOptions | undefined) => {
name: string;
version: string | undefined;
rootPath: string;
packageJsonPath: string;
packageJson: PackageJson;
} | undefined;
declare const loadPackageJSON: quansync_types.QuansyncFn<PackageJson | null, [cwd?: Args[0] | undefined]>;
declare const loadPackageJSONSync: (cwd?: Args[0] | undefined) => PackageJson | null;
declare const isPackageListed: quansync_types.QuansyncFn<boolean, [name: string, cwd?: string | undefined]>;
declare const isPackageListedSync: (name: string, cwd?: string | undefined) => boolean;
export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, isPackageListedSync, loadPackageJSON, loadPackageJSONSync, resolveModule };
export type { PackageInfo, PackageResolvingOptions };
+42
View File
@@ -0,0 +1,42 @@
import * as quansync_types from 'quansync/types';
import { PackageJson } from 'pkg-types';
interface PackageInfo {
name: string;
rootPath: string;
packageJsonPath: string;
version: string;
packageJson: PackageJson;
}
interface PackageResolvingOptions {
paths?: string[];
/**
* @default 'auto'
* Resolve path as posix or win32
*/
platform?: 'posix' | 'win32' | 'auto';
}
declare function resolveModule(name: string, options?: PackageResolvingOptions): string | undefined;
declare function importModule<T = any>(path: string): Promise<T>;
declare function isPackageExists(name: string, options?: PackageResolvingOptions): boolean;
declare const getPackageInfo: quansync_types.QuansyncFn<{
name: string;
version: string | undefined;
rootPath: string;
packageJsonPath: string;
packageJson: PackageJson;
} | undefined, [name: string, options?: PackageResolvingOptions | undefined]>;
declare const getPackageInfoSync: (name: string, options?: PackageResolvingOptions | undefined) => {
name: string;
version: string | undefined;
rootPath: string;
packageJsonPath: string;
packageJson: PackageJson;
} | undefined;
declare const loadPackageJSON: quansync_types.QuansyncFn<PackageJson | null, [cwd?: Args[0] | undefined]>;
declare const loadPackageJSONSync: (cwd?: Args[0] | undefined) => PackageJson | null;
declare const isPackageListed: quansync_types.QuansyncFn<boolean, [name: string, cwd?: string | undefined]>;
declare const isPackageListedSync: (name: string, cwd?: string | undefined) => boolean;
export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, isPackageListedSync, loadPackageJSON, loadPackageJSONSync, resolveModule };
export type { PackageInfo, PackageResolvingOptions };
+172
View File
@@ -0,0 +1,172 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import path, { dirname, join, win32 } from 'node:path';
import process from 'node:process';
import fsPromises from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { resolvePathSync, interopDefault } from 'mlly';
import { quansync } from 'quansync/macro';
const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
async function findUp$1(name, {
cwd = process.cwd(),
type = 'file',
stopAt,
} = {}) {
let directory = path.resolve(toPath(cwd) ?? '');
const {root} = path.parse(directory);
stopAt = path.resolve(directory, toPath(stopAt ?? root));
const isAbsoluteName = path.isAbsolute(name);
while (directory) {
const filePath = isAbsoluteName ? name : path.join(directory, name);
try {
const stats = await fsPromises.stat(filePath); // eslint-disable-line no-await-in-loop
if ((type === 'file' && stats.isFile()) || (type === 'directory' && stats.isDirectory())) {
return filePath;
}
} catch {}
if (directory === stopAt || directory === root) {
break;
}
directory = path.dirname(directory);
}
}
function findUpSync(name, {
cwd = process.cwd(),
type = 'file',
stopAt,
} = {}) {
let directory = path.resolve(toPath(cwd) ?? '');
const {root} = path.parse(directory);
stopAt = path.resolve(directory, toPath(stopAt) ?? root);
const isAbsoluteName = path.isAbsolute(name);
while (directory) {
const filePath = isAbsoluteName ? name : path.join(directory, name);
try {
const stats = fs.statSync(filePath, {throwIfNoEntry: false});
if ((type === 'file' && stats?.isFile()) || (type === 'directory' && stats?.isDirectory())) {
return filePath;
}
} catch {}
if (directory === stopAt || directory === root) {
break;
}
directory = path.dirname(directory);
}
}
function _resolve(path, options = {}) {
if (options.platform === "auto" || !options.platform)
options.platform = process.platform === "win32" ? "win32" : "posix";
if (process.versions.pnp) {
const paths = options.paths || [];
if (paths.length === 0)
paths.push(process.cwd());
const targetRequire = createRequire(import.meta.url);
try {
return targetRequire.resolve(path, { paths });
} catch {
}
}
const modulePath = resolvePathSync(path, {
url: options.paths
});
if (options.platform === "win32")
return win32.normalize(modulePath);
return modulePath;
}
function resolveModule(name, options = {}) {
try {
return _resolve(name, options);
} catch {
return void 0;
}
}
async function importModule(path) {
const i = await import(path);
if (i)
return interopDefault(i);
return i;
}
function isPackageExists(name, options = {}) {
return !!resolvePackage(name, options);
}
function getPackageJsonPath(name, options = {}) {
const entry = resolvePackage(name, options);
if (!entry)
return;
return searchPackageJSON(entry);
}
const readFile = quansync({
async: (id) => fs.promises.readFile(id, "utf8"),
sync: (id) => fs.readFileSync(id, "utf8")
});
const getPackageInfo = quansync(function* (name, options = {}) {
const packageJsonPath = getPackageJsonPath(name, options);
if (!packageJsonPath)
return;
const packageJson = JSON.parse(yield readFile(packageJsonPath));
return {
name,
version: packageJson.version,
rootPath: dirname(packageJsonPath),
packageJsonPath,
packageJson
};
});
const getPackageInfoSync = getPackageInfo.sync;
function resolvePackage(name, options = {}) {
try {
return _resolve(`${name}/package.json`, options);
} catch {
}
try {
return _resolve(name, options);
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND" && e.code !== "ERR_MODULE_NOT_FOUND")
console.error(e);
return false;
}
}
function searchPackageJSON(dir) {
let packageJsonPath;
while (true) {
if (!dir)
return;
const newDir = dirname(dir);
if (newDir === dir)
return;
dir = newDir;
packageJsonPath = join(dir, "package.json");
if (fs.existsSync(packageJsonPath))
break;
}
return packageJsonPath;
}
const findUp = quansync({
sync: findUpSync,
async: findUp$1
});
const loadPackageJSON = quansync(function* (cwd = process.cwd()) {
const path = yield findUp("package.json", { cwd });
if (!path || !fs.existsSync(path))
return null;
return JSON.parse(yield readFile(path));
});
const loadPackageJSONSync = loadPackageJSON.sync;
const isPackageListed = quansync(function* (name, cwd) {
const pkg = (yield loadPackageJSON(cwd)) || {};
return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
});
const isPackageListedSync = isPackageListed.sync;
export { getPackageInfo, getPackageInfoSync, importModule, isPackageExists, isPackageListed, isPackageListedSync, loadPackageJSON, loadPackageJSONSync, resolveModule };
+27
View File
@@ -0,0 +1,27 @@
MIT License
Copyright (c) Pooya Parsa <pooya@pi0.io>
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.
## Third-Party Licenses
This software includes bundled third-party dependencies. The licenses and
copyright notices for these dependencies are available in
`dist/THIRD-PARTY-LICENSES.md` within the distributed package.
+191
View File
@@ -0,0 +1,191 @@
# confbox
<!-- automd:badges color=yellow bundlephobia packagephobia -->
[![npm version](https://img.shields.io/npm/v/confbox?color=yellow)](https://npmjs.com/package/confbox)
[![npm downloads](https://img.shields.io/npm/dm/confbox?color=yellow)](https://npm.chart.dev/confbox)
[![bundle size](https://img.shields.io/bundlephobia/minzip/confbox?color=yellow)](https://bundlephobia.com/package/confbox)
[![install size](https://badgen.net/packagephobia/install/confbox?color=yellow)](https://packagephobia.com/result?p=confbox)
<!-- /automd -->
Parsing and serialization utils for [YAML](https://yaml.org/) ([js-yaml](https://github.com/nodeca/js-yaml)), [TOML](https://toml.io/) ([smol-toml](https://github.com/squirrelchat/smol-toml)), [JSONC](https://github.com/microsoft/node-jsonc-parser) ([jsonc-parser](https://github.com/microsoft/node-jsonc-parser)), [JSON5](https://json5.org/) ([json5](https://github.com/json5/json5)), [INI](https://en.wikipedia.org/wiki/INI_file) ([ini](https://www.npmjs.com/package/ini)) and [JSON](https://www.json.org/json-en.html).
✨ Zero dependency and tree-shakable
✨ Types exported out of the box
✨ Preserves code style (indentation and whitespace)
> [!TIP]
> Use [unjs/c12](https://github.com/unjs/c12) for a full featured configuration loader!
## Usage
Install package:
<!-- automd:pm-i no-version -->
```sh
# ✨ Auto-detect
npx nypm install confbox
# npm
npm install confbox
# yarn
yarn add confbox
# pnpm
pnpm add confbox
# bun
bun install confbox
# deno
deno install npm:confbox
```
<!-- /automd -->
Import:
<!-- automd:jsimport cdn src="./src/index.ts" -->
**ESM** (Node.js, Bun, Deno)
```js
import {
parseJSON5,
stringifyJSON5,
parseJSONC,
stringifyJSONC,
parseYAML,
stringifyYAML,
parseJSON,
stringifyJSON,
parseTOML,
stringifyTOML,
parseINI,
stringifyINI,
} from "confbox";
```
**CDN** (Deno and Browsers)
```js
import {
parseJSON5,
stringifyJSON5,
parseJSONC,
stringifyJSONC,
parseYAML,
stringifyYAML,
parseJSON,
stringifyJSON,
parseTOML,
stringifyTOML,
parseINI,
stringifyINI,
} from "https://esm.sh/confbox";
```
<!-- /automd -->
<!-- automd:jsdocs src="./src/index" -->
### `parseINI(text, options?)`
Converts an [INI](https://www.ini.org/ini-en.html) string into an object.
**Note:** Style and indentation are not preserved currently.
### `parseJSON(text, options?)`
Converts a [JSON](https://www.json.org/json-en.html) string into an object.
Indentation status is auto-detected and preserved when stringifying back using `stringifyJSON`
### `parseJSON5(text, options?)`
Converts a [JSON5](https://json5.org/) string into an object.
### `parseJSONC(text, options?)`
Converts a [JSONC](https://github.com/microsoft/node-jsonc-parser) string into an object.
### `parseTOML(text)`
Converts a [TOML](https://toml.io/) string into an object.
### `parseYAML(text, options?)`
Converts a [YAML](https://yaml.org/) string into an object.
### `stringifyINI(value, options?)`
Converts a JavaScript value to an [INI](https://www.ini.org/ini-en.html) string.
**Note:** Style and indentation are not preserved currently.
### `stringifyJSON(value, options?)`
Converts a JavaScript value to a [JSON](https://www.json.org/json-en.html) string.
Indentation status is auto detected and preserved when using value from parseJSON.
### `stringifyJSON5(value, options?)`
Converts a JavaScript value to a [JSON5](https://json5.org/) string.
### `stringifyJSONC(value, options?)`
Converts a JavaScript value to a [JSONC](https://github.com/microsoft/node-jsonc-parser) string.
### `stringifyTOML(value)`
Converts a JavaScript value to a [TOML](https://toml.io/) string.
### `stringifyYAML(value, options?)`
Converts a JavaScript value to a [YAML](https://yaml.org/) string.
<!-- /automd -->
<!-- automd:fetch url="gh:unjs/.github/main/snippets/readme-contrib-node-pnpm.md" -->
## Contribution
<details>
<summary>Local development</summary>
- Clone this repository
- Install the latest LTS version of [Node.js](https://nodejs.org/en/)
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
- Install dependencies using `pnpm install`
- Run tests using `pnpm dev` or `pnpm test`
</details>
<!-- /automd -->
## License
<!-- automd:contributors license=MIT author=pi0 -->
Published under the [MIT](https://github.com/unjs/confbox/blob/main/LICENSE) license.
Made by [@pi0](https://github.com/pi0) and [community](https://github.com/unjs/confbox/graphs/contributors) 💛
<br><br>
<a href="https://github.com/unjs/confbox/graphs/contributors">
<img src="https://contrib.rocks/image?repo=unjs/confbox" />
</a>
<!-- /automd -->
<!-- automd:with-automd -->
---
_🤖 auto updated with [automd](https://automd.unjs.io)_
<!-- /automd -->
@@ -0,0 +1,24 @@
export interface FormatOptions {
/**
* A String or Number object that's used to insert white space into the output JSON string for readability purposes.
*
* When provided, identation won't be auto detected anymore.
*
* When passed at parse time, it is remembered and used when stringifying the value back.
*/
indent?: string | number;
/**
* Set to `false` to skip indentation preservation.
*/
preserveIndentation?: boolean;
/**
* Set to `false` to skip whitespace preservation.
*/
preserveWhitespace?: boolean;
/**
* The number of characters to sample from the start of the text.
*
* Default: 1024
*/
sampleSize?: number;
}
@@ -0,0 +1,2 @@
import{detectIndent as e}from"./libs/detect-indent.mjs";const t=Symbol.for(`__confbox_fmt__`),n=/^(\s+)/,r=/^[ \t]+(?=\r?$)/gm;function i(e){return e.charCodeAt(0)===65279?e.slice(1):e}function a(e,t){let i=(n.exec(e)?.[0]||``).lastIndexOf(`
`)+1;return e.slice(i,i+t).replace(r,``)}function o(e,t={}){let r=t.indent===void 0&&t.preserveIndentation!==!1?a(i(e),t?.sampleSize||1024):void 0,o=t.preserveWhitespace===!1?void 0:{start:n.exec(e)?.[0]||``,end:e.slice(e.trimEnd().length)};return{indent:t.indent,sample:r,whiteSpace:o}}function s(e,n,r){n&&typeof n==`object`&&Object.defineProperty(n,t,{enumerable:!1,configurable:!0,writable:!0,value:o(e,r)})}function c(n,r){if(!n||typeof n!=`object`||!(t in n))return{indent:r?.indent??2,whitespace:{start:``,end:``}};let i=n[t];return{indent:r?.indent??i.indent??(i.sample?e(i.sample).indent:2),whitespace:i.whiteSpace||{start:``,end:``}}}export{c as getFormat,s as storeFormat,i as stripBOM};
@@ -0,0 +1 @@
const e=/^(?:( )+|\t+)/,t=`space`;function n(e,n,r){return e&&n===t&&r===1}function r(r,a){let o=/* @__PURE__ */ new Map,s=0,c,l;for(let u of r.split(/\n/g)){if(!u)continue;let r=u.match(e);if(r===null)s=0,c=``;else{let e=r[0].length,u=r[1]?t:`tab`;if(n(a,u,e))continue;u!==c&&(s=0),c=u;let d=1,f=0,p=e-s;if(s=e,p===0)d=0,f=1;else{let e=Math.abs(p);if(n(a,u,e))continue;l=i(u,e)}let m=o.get(l);o.set(l,m===void 0?[1,0]:[m[0]+d,m[1]+f])}}return o}function i(e,n){return(e===t?`s`:`t`)+String(n)}function a(e){return{type:e[0]===`s`?t:`tab`,amount:Number(e.slice(1))}}function o(e){let t,n=0,r=0;for(let[i,[a,o]]of e)(a>n||a===n&&o>r)&&(n=a,r=o,t=i);return t}function s(e,n){return(e===t?` `:` `).repeat(n)}function c(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);let t=r(e,!0);t.size===0&&(t=r(e,!1));let n=o(t),i,c=0,l=``;return n!==void 0&&({type:i,amount:c}=a(n),l=s(i,c)),{amount:c,type:i,indent:l}}export{c as detectIndent};
@@ -0,0 +1,3 @@
import{__commonJSMin as e}from"../rolldown-runtime.mjs";var t=/* @__PURE__ */ e(((e,t)=>{let{hasOwnProperty:n}=Object.prototype,r=(e,t={})=>{typeof t==`string`&&(t={section:t}),t.align=t.align===!0,t.newline=t.newline===!0,t.sort=t.sort===!0,t.whitespace=t.whitespace===!0||t.align===!0,t.platform=t.platform||typeof process<`u`&&process.platform,t.bracketedArray=t.bracketedArray!==!1;let n=t.platform===`win32`?`\r
`:`
`,a=t.whitespace?` = `:`=`,o=[],c=t.sort?Object.keys(e).sort():Object.keys(e),l=0;t.align&&(l=s(c.filter(t=>e[t]===null||Array.isArray(e[t])||typeof e[t]!=`object`).map(t=>Array.isArray(e[t])?`${t}[]`:t).concat([``]).reduce((e,t)=>s(e).length>=s(t).length?e:t)).length);let u=``,d=t.bracketedArray?`[]`:``;for(let t of c){let r=e[t];if(r&&Array.isArray(r))for(let e of r)u+=s(`${t}${d}`).padEnd(l,` `)+a+s(e)+n;else r&&typeof r==`object`?o.push(t):u+=s(t).padEnd(l,` `)+a+s(r)+n}t.section&&u.length&&(u=`[`+s(t.section)+`]`+(t.newline?n+n:n)+u);for(let a of o){let o=i(a,`.`).join(`\\.`),s=(t.section?t.section+`.`:``)+o,c=r(e[a],{...t,section:s});u.length&&c.length&&(u+=n),u+=c}return u};function i(e,t){var n=0,r=0,i=0,a=[];do if(i=e.indexOf(t,n),i!==-1){if(n=i+t.length,i>0&&e[i-1]===`\\`)continue;a.push(e.slice(r,i)),r=i+t.length}while(i!==-1);return a.push(e.slice(r)),a}let a=(e,t={})=>{t.bracketedArray=t.bracketedArray!==!1;let r=Object.create(null),a=r,o=null,s=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,l=e.split(/[\r\n]+/g),u={};for(let e of l){if(!e||e.match(/^\s*[;#]/)||e.match(/^\s*$/))continue;let i=e.match(s);if(!i)continue;if(i[1]!==void 0){if(o=c(i[1]),o===`__proto__`){a=Object.create(null);continue}a=r[o]=r[o]||Object.create(null);continue}let l=c(i[2]),d;t.bracketedArray?d=l.length>2&&l.slice(-2)===`[]`:(u[l]=(u?.[l]||0)+1,d=u[l]>1);let f=d&&l.endsWith(`[]`)?l.slice(0,-2):l;if(f===`__proto__`)continue;let p=!i[3]||c(i[4]),m=p===`true`||p===`false`||p===`null`?JSON.parse(p):p;d&&(n.call(a,f)?Array.isArray(a[f])||(a[f]=[a[f]]):a[f]=[]),Array.isArray(a[f])?a[f].push(m):a[f]=m}let d=[];for(let e of Object.keys(r)){if(!n.call(r,e)||typeof r[e]!=`object`||Array.isArray(r[e]))continue;let t=i(e,`.`);a=r;let o=t.pop(),s=o.replace(/\\\./g,`.`);for(let e of t)e!==`__proto__`&&(n.call(a,e)&&typeof a[e]==`object`||(a[e]=Object.create(null)),a=a[e]);(a!==r||s!==o)&&(a[s]=r[e],d.push(e))}for(let e of d)delete r[e];return r},o=e=>e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`),s=e=>typeof e!=`string`||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&o(e)||e!==e.trim()?JSON.stringify(e):e.split(`;`).join(`\\;`).split(`#`).join(`\\#`),c=e=>{if(e=(e||``).trim(),o(e)){e.charAt(0)===`'`&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let t=!1,n=``;for(let r=0,i=e.length;r<i;r++){let i=e.charAt(r);if(t)`\\;#`.indexOf(i)===-1?n+=`\\`+i:n+=i,t=!1;else if(`;#`.indexOf(i)!==-1)break;else i===`\\`?t=!0:n+=i}return t&&(n+=`\\`),n.trim()}return e};t.exports={parse:a,decode:a,stringify:r,encode:r,safe:s,unsafe:c}}));export{t as require_ini};
@@ -0,0 +1,33 @@
interface SnippetMark {
name?: string | null;
buffer: string;
position: number;
line: number;
column: number;
snippet?: string | null;
}
/**
* A YAML error. Unlike an ordinary `Error`, it adds a source snippet showing
* the location of the problem to the error message, when available.
*
* @category Main
*/
declare class YAMLException extends Error {
reason: string;
mark?: SnippetMark;
/**
* Optional `mark` contains source snippet data. Usually, use
* {@link YAMLException.throwAt} instead of passing it directly.
*/
constructor(reason: string, mark?: SnippetMark);
/**
* Returns the formatted error, omitting the source snippet in compact mode.
*/
toString(compact?: boolean): string;
/**
* Builds a YAMLException with a source snippet and throws it. `source` is
* the raw input text; `position` is an offset into it.
*/
static throwAt(source: string, position: number, message: string, filename?: string): never;
}
export { YAMLException };
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
const e=Symbol(`singleComment`),t=Symbol(`multiComment`),n=()=>``,r=(e,t,n)=>e.slice(t,n).replace(/[^ \t\r\n]/g,` `),i=(e,t)=>{let n=t-1,r=0;for(;e[n]===`\\`;)--n,r+=1;return!!(r%2)};function a(a,{whitespace:o=!0,trailingCommas:s=!1}={}){if(typeof a!=`string`)throw TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof a}\``);let c=o?r:n,l=!1,u=!1,d=0,f=``,p=``,m=-1;for(let n=0;n<a.length;n++){let r=a[n],o=a[n+1];if(u||r!==`"`||i(a,n)||(l=!l),!l){if(!u&&r+o===`//`)f+=a.slice(d,n),d=n,u=e,n++;else if(u===e&&r+o===`\r
`){n++,u=!1,f+=c(a,d,n),d=n;continue}else if(u===e&&r===`
`)u=!1,f+=c(a,d,n),d=n;else if(!u&&r+o===`/*`){f+=a.slice(d,n),d=n,u=t,n++;continue}else if(u===t&&r+o===`*/`){n++,u=!1,f+=c(a,d,n+1),d=n+1;continue}else s&&!u&&(m===-1?r===`,`&&(p+=f+a.slice(d,n),f=``,d=n,m=n):r===`}`||r===`]`?(f+=a.slice(d,n),p+=c(f,0,1)+f.slice(1),f=``,d=n,m=-1):r!==` `&&r!==` `&&r!==`\r`&&r!==`
`&&(f+=a.slice(d,n),d=n,m=-1))}}let h=u===e?c(a,d):a.slice(d);return p+f+h}export{a as stripJsonComments};
@@ -0,0 +1 @@
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));export{o as __commonJSMin,c as __toESM};
@@ -0,0 +1,7 @@
import { JSON5ParseOptions, JSON5StringifyOptions, parseJSON5, stringifyJSON5 } from "./json5.mjs";
import { JSONCParseOptions, parseJSONC, stringifyJSONC } from "./jsonc.mjs";
import { YAMLParseOptions, YAMLStringifyOptions, parseYAML, stringifyYAML } from "./yaml.mjs";
import { JSONParseOptions, JSONStringifyOptions, parseJSON, stringifyJSON } from "./json.mjs";
import { parseTOML, stringifyTOML } from "./toml.mjs";
import { INIParseOptions, INIStringifyOptions, parseINI, stringifyINI } from "./ini.mjs";
export { type INIParseOptions, type INIStringifyOptions, type JSON5ParseOptions, type JSON5StringifyOptions, type JSONCParseOptions, type JSONParseOptions, type JSONStringifyOptions, type YAMLParseOptions, type YAMLStringifyOptions, parseINI, parseJSON, parseJSON5, parseJSONC, parseTOML, parseYAML, stringifyINI, stringifyJSON, stringifyJSON5, stringifyJSONC, stringifyTOML, stringifyYAML };
@@ -0,0 +1 @@
import{parseJSON5 as e,stringifyJSON5 as t}from"./json5.mjs";import{parseJSON as n,stringifyJSON as r}from"./json.mjs";import{parseJSONC as i,stringifyJSONC as a}from"./jsonc.mjs";import{parseYAML as o,stringifyYAML as s}from"./yaml.mjs";import{parseTOML as c,stringifyTOML as l}from"./toml.mjs";import{parseINI as u,stringifyINI as d}from"./ini.mjs";export{u as parseINI,n as parseJSON,e as parseJSON5,i as parseJSONC,c as parseTOML,o as parseYAML,d as stringifyINI,r as stringifyJSON,t as stringifyJSON5,a as stringifyJSONC,l as stringifyTOML,s as stringifyYAML};
@@ -0,0 +1,59 @@
/**
* Converts an [INI](https://www.ini.org/ini-en.html) string into an object.
*
* **Note:** Style and indentation are not preserved currently.
*/
export declare function parseINI<T = unknown>(text: string, options?: INIParseOptions): T;
/**
* Converts a JavaScript value to an [INI](https://www.ini.org/ini-en.html) string.
*
* **Note:** Style and indentation are not preserved currently.
*/
export declare function stringifyINI(value: any, options?: INIStringifyOptions): string;
export interface INIParseOptions {
/**
* Whether to append `[]` to array keys.
*
* Some parsers treat duplicate names by themselves as arrays.
*/
bracketedArray?: boolean;
}
export interface INIStringifyOptions {
/**
* Whether to insert spaces before & after `=` character.
* Enabled by default.
*/
whitespace?: boolean;
/**
* Whether to align the `=` character for each section.
*/
align?: boolean;
/**
* Identifier to use for global items
* and to prepend to all other sections.
*/
section?: string;
/**
* Whether to sort all sections & their keys alphabetically.
*/
sort?: boolean;
/**
* Whether to insert a newline after each section header.
*/
newline?: boolean;
/**
* Which platforms line-endings should be used.
*
* win32 -> CR+LF
* other -> LF
*
* Default is the current platform
*/
platform?: string;
/**
* Whether to append `[]` to array keys.
*
* Some parsers treat duplicate names by themselves as arrays
*/
bracketedArray?: boolean;
}
@@ -0,0 +1 @@
import{stripBOM as e}from"./_chunks/_format.mjs";import{require_ini as t}from"./_chunks/libs/ini.mjs";var n=t();function r(t,r){return(0,n.parse)(e(t),r)}function i(e,t){return(0,n.stringify)(e,{whitespace:!0,...t})}export{r as parseINI,i as stringifyINI};
@@ -0,0 +1,25 @@
import { FormatOptions } from "./_chunks/_format.mjs";
/**
* Converts a [JSON](https://www.json.org/json-en.html) string into an object.
*
* Indentation status is auto-detected and preserved when stringifying back using `stringifyJSON`
*/
export declare function parseJSON<T = unknown>(text: string, options?: JSONParseOptions): T;
/**
* Converts a JavaScript value to a [JSON](https://www.json.org/json-en.html) string.
*
* Indentation status is auto detected and preserved when using value from parseJSON.
*/
export declare function stringifyJSON(value: any, options?: JSONStringifyOptions): string;
export interface JSONParseOptions extends FormatOptions {
/**
* A function that transforms the results. This function is called for each member of the object.
*/
reviver?: (this: any, key: string, value: any) => any;
}
export interface JSONStringifyOptions extends FormatOptions {
/**
* A function that transforms the results. This function is called for each member of the object.
*/
replacer?: (this: any, key: string, value: any) => any;
}
@@ -0,0 +1 @@
import{getFormat as e,storeFormat as t,stripBOM as n}from"./_chunks/_format.mjs";function r(e,r){let i=JSON.parse(n(e),r?.reviver);return t(e,i,r),i}function i(t,n){let r=e(t,n),i=JSON.stringify(t,n?.replacer,r.indent);return r.whitespace.start+i+r.whitespace.end}export{r as parseJSON,i as stringifyJSON};
@@ -0,0 +1,55 @@
import { FormatOptions } from "./_chunks/_format.mjs";
/**
* Converts a [JSON5](https://json5.org/) string into an object.
*
* @template T The type of the return value.
* @param text The string to parse as JSON5.
* @param options Parsing options.
* @returns The JavaScript value converted from the JSON5 string.
*/
export declare function parseJSON5<T = unknown>(text: string, options?: JSON5ParseOptions): T;
/**
* Converts a JavaScript value to a [JSON5](https://json5.org/) string.
*
* @param value
* @param options
* @returns The JSON string converted from the JavaScript value.
*/
export declare function stringifyJSON5(value: any, options?: JSON5StringifyOptions): string;
export interface JSON5ParseOptions extends FormatOptions {
/**
* A function that alters the behavior of the parsing process, or an array of
* String and Number objects that serve as a allowlist for selecting/filtering
* the properties of the value object to be included in the resulting
* JavaScript object. If this value is null or not provided, all properties of
* the object are included in the resulting JavaScript object.
*/
reviver?: (this: any, key: string, value: any) => any;
}
export interface JSON5StringifyOptions extends FormatOptions {
/**
* A function that alters the behavior of the stringification process, or an
* array of String and Number objects that serve as a allowlist for
* selecting/filtering the properties of the value object to be included in
* the JSON5 string. If this value is null or not provided, all properties
* of the object are included in the resulting JSON5 string.
*/
replacer?: ((this: any, key: string, value: any) => any) | null;
/**
* A String or Number object that's used to insert white space into the
* output JSON5 string for readability purposes. If this is a Number, it
* indicates the number of space characters to use as white space; this
* number is capped at 10 (if it is greater, the value is just 10). Values
* less than 1 indicate that no space should be used. If this is a String,
* the string (or the first 10 characters of the string, if it's longer than
* that) is used as white space. If this parameter is not provided (or is
* null), no white space is used. If white space is used, trailing commas
* will be used in objects and arrays.
*/
space?: string | number | null;
/**
* A String representing the quote character to use when serializing
* strings.
*/
quote?: string | null;
}
@@ -0,0 +1 @@
import{__toESM as e}from"./_chunks/rolldown-runtime.mjs";import{getFormat as t,storeFormat as n,stripBOM as r}from"./_chunks/_format.mjs";import{require_parse as i,require_stringify as a}from"./_chunks/libs/json5.mjs";var o=/* @__PURE__ */ e(i(),1),s=/* @__PURE__ */ e(a(),1);function c(e,t){let i=(0,o.default)(r(e),t?.reviver);return n(e,i,t),i}function l(e,n){let r=t(e,n),i=(0,s.default)(e,n?.replacer,r.indent);return r.whitespace.start+i+r.whitespace.end}export{c as parseJSON5,l as stringifyJSON5};
@@ -0,0 +1,29 @@
import { FormatOptions } from "./_chunks/_format.mjs";
/**
*
* Converts a [JSONC](https://github.com/microsoft/node-jsonc-parser) string into an object.
*
* @NOTE On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
*
* @NOTE Comments and trailing commas are not preserved after parsing.
*
* @template T The type of the return value.
* @param text The string to parse as JSONC.
* @param options Parsing options.
* @returns The JavaScript value converted from the JSONC string.
*/
export declare function parseJSONC<T = unknown>(text: string, options?: JSONCParseOptions): T;
/**
* Converts a JavaScript value to a [JSONC](https://github.com/microsoft/node-jsonc-parser) string.
*
* @NOTE Comments and trailing commas are not preserved in the output.
*
* @param value
* @param options
* @returns The JSON string converted from the JavaScript value.
*/
export declare function stringifyJSONC(value: any, options?: JSONCStringifyOptions): string;
export interface JSONCParseOptions extends FormatOptions {
allowTrailingComma?: boolean;
}
export interface JSONCStringifyOptions extends FormatOptions {}
@@ -0,0 +1 @@
import{storeFormat as e,stripBOM as t}from"./_chunks/_format.mjs";import{stripJsonComments as n}from"./_chunks/libs/strip-json-comments.mjs";import{stringifyJSON as r}from"./json.mjs";function i(r,i){let a=JSON.parse(n(t(r),{trailingCommas:i?.allowTrailingComma}));return e(r,a,i),a}function a(e,t){return r(e,t)}export{i as parseJSONC,a as stringifyJSONC};
@@ -0,0 +1,20 @@
/**
* Converts a [TOML](https://toml.io/) string into an object.
*
* @NOTE Comments and indentation is not preserved after parsing.
*
* @template T The type of the return value.
* @param text The TOML string to parse.
* @returns The JavaScript value converted from the TOML string.
*/
export declare function parseTOML<T = unknown>(text: string): T;
/**
* Converts a JavaScript value to a [TOML](https://toml.io/) string.
*
* @NOTE Comments and indentation is not preserved in the output.
*
* @param value
* @param options
* @returns The YAML string converted from the JavaScript value.
*/
export declare function stringifyTOML(value: any): string;
@@ -0,0 +1 @@
import{getFormat as e,storeFormat as t,stripBOM as n}from"./_chunks/_format.mjs";import{parse as r,stringify as i}from"./_chunks/libs/smol-toml.mjs";function a(e){let i=r(n(e));return t(e,i,{preserveIndentation:!1}),i}function o(t){let n=e(t,{preserveIndentation:!1}),r=i(t);return n.whitespace.start+r+n.whitespace.end}export{a as parseTOML,o as stringifyTOML};
@@ -0,0 +1,101 @@
import { FormatOptions } from "./_chunks/_format.mjs";
import { YAMLException } from "./_chunks/libs/js-yaml.mjs";
/**
* Converts a [YAML](https://yaml.org/) string into an object.
*
* @NOTE This function does **not** understand multi-document or empty sources, it throws exception on those.
*
* @NOTE Comments are not preserved after parsing.
*
* @NOTE Parsing uses the YAML 1.2 core schema. Tags outside of it (`!!timestamp`, `!!merge`,
* `!!binary`, `!!omap`, `!!pairs` and `!!set`) are not resolved, so timestamps are returned as
* strings and `<<` merge keys are kept as-is. Opt back in by installing `js-yaml` alongside
* confbox and passing a schema:
* `parseYAML(text, { schema: CORE_SCHEMA.withTags(mergeTag, timestampTag) })`.
*
* @template T The type of the return value.
* @param text The YAML string to parse.
* @param options Parsing options.
* @returns The JavaScript value converted from the YAML string.
*/
export declare function parseYAML<T = unknown>(text: string, options?: YAMLParseOptions): T;
/**
* Converts a JavaScript value to a [YAML](https://yaml.org/) string.
*
* @NOTE Comments are not preserved in the output.
*
* @param value
* @param options
* @returns The YAML string converted from the JavaScript value.
*/
export declare function stringifyYAML(value: any, options?: YAMLStringifyOptions): string;
export interface YAMLParseOptions extends FormatOptions {
/** File path used in error messages. */
filename?: string;
/** Maximum nesting depth for collections. Aliases are not taken into account. (default: 100) */
maxDepth?: number;
/** Schema to use. (default: `CORE_SCHEMA`) */
schema?: any;
/** Enables compatibility with `JSON.parse` behavior. Duplicate keys in a mapping override values instead of throwing an error. (default: false) */
json?: boolean;
/**
* Maximum total number of keys processed by merge (`<<`) across one load call.
* Each member of a merge sequence also counts as one key. Set to `-1` to disable the limit. (default: 10000)
*/
maxTotalMergeKeys?: number;
/** Maximum number of alias nodes (`*ref`) per document. Set to `0` to reject all aliases, or to `-1` for no limit. (default: -1) */
maxAliases?: number;
}
export interface YAMLStringifyOptions extends FormatOptions {
/** Indentation width in spaces. (default: 2) */
indent?: number;
/** Does not add an indentation level to array elements when enabled. (default: false) */
seqNoIndent?: boolean;
/** Allows a nested collection to start on the same line after `-`. (default: true) */
seqInlineFirst?: boolean;
/** Preferred line width for folding. Unbreakable and more-indented lines may exceed it. Set to `-1` for unlimited width. (default: 80) */
lineWidth?: number;
/** Adds spaces inside flow collection brackets: `{a: 1}` becomes `{ a: 1 }`. (default: false) */
flowBracketPadding?: boolean;
/** Omits the space after commas in flow collections: `[1, 2]` becomes `[1,2]`. (default: false) */
flowSkipCommaSpace?: boolean;
/**
* Omits the space after `:` in flow mappings: `{"a": 1}` becomes `{"a":1}`.
*
* This forces `quoteFlowKeys`; otherwise `a:1` would be parsed as a single plain scalar instead of a mapping entry. (default: false)
*/
flowSkipColonSpace?: boolean;
/** Quotes flow mapping keys: `{a: 1}` becomes `{"a": 1}`. (default: false) */
quoteFlowKeys?: boolean;
/** Quoting style to use when a string needs quotes. (default: `single`) */
quoteStyle?: "single" | "double";
/** Quotes all non-key strings using `quoteStyle`. (default: false) */
forceQuotes?: boolean;
/**
* Customizes how strings are rendered as plain, quoted, literal, or folded scalars.
* Rules are applied in array order; providing this option replaces the default rules.
*/
scalarStyleRules?: readonly ((layout: any) => void)[];
/** Prints an explicit tag before an anchor: `&ref_0 !!set` becomes `!!set &ref_0`. (default: false) */
tagBeforeAnchor?: boolean;
/** Schema to use. (default: `DUMP_SCHEMA`) */
schema?: any;
/**
* Skips invalid types instead of throwing. Invalid mapping pairs and sequence items are skipped;
* `undefined` sequence items are serialized as `null`. (default: false)
*/
skipInvalid?: boolean;
/** Inlines duplicate objects instead of converting them into references. (default: false) */
noRefs?: boolean;
/** Nesting level at which collections switch from block to flow style. Set to `-1` to never switch automatically. (default: -1) */
flowLevel?: number;
/**
* Sorts mapping keys when `true`. A function can be provided to define the sort order. (default: false)
*
* @deprecated Use `transform` to reorder mapping items.
*/
sortKeys?: boolean | ((a: any, b: any) => number);
/** Mutates the generated AST before it is rendered. */
transform?: (documents: any[]) => void;
}
export { YAMLException };
@@ -0,0 +1 @@
import{getFormat as e,storeFormat as t,stripBOM as n}from"./_chunks/_format.mjs";import{YAMLException as r,dump as i,load as a}from"./_chunks/libs/js-yaml.mjs";function o(e,r){let i=a(n(e),r);return t(e,i,r),i}function s(t,n){let r=e(t,{preserveIndentation:!1}),a=typeof r.indent==`string`?r.indent.length:r.indent,o=i(t,{...n,indent:n?.indent||a||2});return r.whitespace.start+o.trim()+r.whitespace.end}export{r as YAMLException,o as parseYAML,s as stringifyYAML};
+68
View File
@@ -0,0 +1,68 @@
{
"name": "confbox",
"version": "0.3.2",
"description": "Compact YAML, TOML, JSONC, JSON5 and INI parser and serializer",
"keywords": [
"config",
"ini",
"json5",
"jsonc",
"toml",
"unjs",
"yaml"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "unjs/confbox"
},
"files": [
"dist"
],
"type": "module",
"sideEffects": false,
"types": "./dist/index.d.mts",
"exports": {
".": "./dist/index.mjs",
"./ini": "./dist/ini.mjs",
"./json": "./dist/json.mjs",
"./json5": "./dist/json5.mjs",
"./jsonc": "./dist/jsonc.mjs",
"./toml": "./dist/toml.mjs",
"./yaml": "./dist/yaml.mjs"
},
"devDependencies": {
"@types/ini": "^4.1.1",
"@types/node": "^26.6.5",
"@vitest/coverage-v8": "^5.0.5",
"automd": "^0.4.3",
"changelogen": "^0.6.2",
"detect-indent": "^7.0.2",
"ini": "^7.0.0",
"jiti": "^2.7.0",
"js-toml": "^2.0.1",
"js-yaml": "^5.5.0",
"json5": "^2.2.3",
"jsonc-parser": "^3.3.1",
"mitata": "^1.0.34",
"obuild": "^0.4.45",
"oxfmt": "^0.75.0",
"oxlint": "^1.90.0",
"smol-toml": "^1.9.1",
"strip-json-comments": "^5.0.3",
"toml": "^5.0.1",
"typescript": "^7.0.2",
"vitest": "^5.0.5",
"yaml": "^2.9.1"
},
"scripts": {
"build": "obuild",
"dev": "vitest dev --coverage",
"bench": "pnpm build && node test/bench.mjs",
"lint": "oxlint && oxfmt --check src test",
"lint:fix": "oxlint --fix && oxfmt src test",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
"test": "pnpm lint && pnpm test:types && vitest run --coverage",
"test:types": "tsc --noEmit --skipLibCheck"
}
}
+44
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.
+342
View File
@@ -0,0 +1,342 @@
# 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 add pkg-types
# bun
bun install pkg-types
# deno
deno install npm: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 pkg = 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");
```
#### `updatePackage`
Reads a package file and passes a proxied PackageJson to a callback (the callback may mutate it in-place or return a new object). The updated package is then written back using the same file format (`.json`/`.json5`/`.yaml`). The proxy auto-creates common map fields (e.g. `scripts`, `dependencies`) when accessed.
```js
import { updatePackage } from "pkg-types";
await updatePackage("path/to/package", (pkg) => {
pkg.version = "1.0.1";
pkg.dependencies.lodash = "^4.17.21";
});
```
#### `sortPackage`
Returns a new PackageJson that reorders known top-level fields according to the convention and alphabetically sorts certain nested maps (like `dependencies`, `devDependencies`, `optionalDependencies`, `peerDependencies` and `scripts`). Unknown top-level keys retain their original relative order. The input object is not mutated.
```js
import { sortPackage } from "pkg-types";
const sorted = sortPackage(pkg);
```
#### `normalizePackage`
Normalizes a `PackageJson` for stable output: sorts top-level fields and dependency maps, and removes dependency fields (`dependencies`, `devDependencies`, `optionalDependencies`, `peerDependencies`) if they are not plain objects. Returns a new normalized object.
```js
import { normalizePackage } from "pkg-types";
const normalized = normalizePackage(pkg);
```
### 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
#### `findFile`
```js
import { findFile } from "pkg-types";
const filename = await findFile("README.md", {
startingFrom: id,
rootPattern: /^node_modules$/,
test: (filename) => filename.endsWith(".md"),
});
```
#### `findNearestFile`
```js
import { findNearestFile } from "pkg-types";
const filename = await findNearestFile("package.json");
```
#### `findFarthestFile`
```js
import { findFarthestFile } from "pkg-types";
const filename = await findFarthestFile("package.json");
```
#### `resolveLockfile`
Find path to the lock file (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`, `npm-shrinkwrap.json`, `bun.lockb`, `bun.lock`, `deno.lock`, `upm.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 work, you need to install `typescript` as a devDependency.
You can directly use typed interfaces:
```ts
import type { TSConfig, PackageJson, GitConfig } from "pkg-types";
```
### Define Utilities
You can use define utilities for type support and auto-completion when working in plain `.js` files. These functions simply return the input object but provide TypeScript type hints.
#### `definePackageJSON`
Provides type safety and auto-completion for package.json objects.
```js
import { definePackageJSON } from "pkg-types";
const pkg = definePackageJSON({
name: "my-package",
version: "1.0.0",
// TypeScript will provide auto-completion here
});
```
#### `defineTSConfig`
Provides type safety and auto-completion for tsconfig.json objects.
```js
import { defineTSConfig } from "pkg-types";
const tsconfig = defineTSConfig({
compilerOptions: {
target: "ES2020",
// TypeScript will provide auto-completion here
},
});
```
#### `defineGitConfig`
Provides type safety and auto-completion for git config objects.
```js
import { defineGitConfig } from "pkg-types";
const gitConfig = defineGitConfig({
user: {
name: "John Doe",
email: "john@example.com",
},
// TypeScript will provide auto-completion here
});
```
## 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 -->
@@ -0,0 +1,695 @@
import { ResolveOptions as ResolveOptions$1 } from "exsolve";
/**
* 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.
*/
export 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.
*/
export 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.
*/
export declare function findFarthestFile(filename: string | string[], options?: FindFileOptions): Promise<string>;
interface TSConfig {
compilerOptions?: CompilerOptions;
exclude?: string[];
compileOnSave?: boolean;
extends?: string | string[];
files?: string[];
include?: string[];
typeAcquisition?: TypeAcquisition;
references?: {
path: string;
}[];
}
/**
* Compiler options as they appear in `tsconfig.json`.
*
* Options that TypeScript models with an enum (`target`, `module`, ...) are typed as `any`,
* since in JSON they are written as (case insensitive) strings.
*
* Options TypeScript has since removed are kept and marked as `@deprecated`,
* so that older `tsconfig.json` files still resolve to a known option.
*/
interface CompilerOptions {
allowArbitraryExtensions?: boolean;
allowImportingTsExtensions?: boolean;
allowJs?: boolean;
allowNonTsExtensions?: boolean;
allowSyntheticDefaultImports?: boolean;
allowUmdGlobalAccess?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
alwaysStrict?: boolean;
assumeChangesOnlyAffectDirectDependencies?: boolean;
/** @deprecated Deprecated since TypeScript 6.0 and removed in 7.0. Use `paths` with `{ "*": ["./*"] }` instead. */
baseUrl?: string;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. */
charset?: string;
checkJs?: boolean;
composite?: boolean;
customConditions?: string[];
declaration?: boolean;
declarationDir?: string;
declarationMap?: boolean;
deduplicatePackages?: boolean;
disableReferencedProjectLoad?: boolean;
disableSizeLimit?: boolean;
disableSolutionSearching?: boolean;
disableSourceOfProjectReferenceRedirect?: boolean;
/** @deprecated Deprecated since TypeScript 6.0 and removed in 7.0. */
downlevelIteration?: boolean;
emitBOM?: boolean;
emitDeclarationOnly?: boolean;
emitDecoratorMetadata?: boolean;
erasableSyntaxOnly?: boolean;
esModuleInterop?: boolean;
exactOptionalPropertyTypes?: boolean;
experimentalDecorators?: boolean;
forceConsistentCasingInFileNames?: boolean;
ignoreConfig?: boolean;
ignoreDeprecations?: string;
importHelpers?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 7.0. Use `verbatimModuleSyntax` instead. */
importsNotUsedAsValues?: any;
incremental?: boolean;
init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
isolatedDeclarations?: boolean;
isolatedModules?: boolean;
jsx?: any;
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. */
keyofStringsOnly?: boolean;
lib?: string[];
libReplacement?: boolean;
locale?: string;
mapRoot?: string;
maxNodeModuleJsDepth?: number;
module?: any;
moduleDetection?: any;
moduleResolution?: any;
moduleSuffixes?: string[];
newLine?: any;
noCheck?: boolean;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noFallthroughCasesInSwitch?: boolean;
noImplicitAny?: boolean;
noImplicitOverride?: boolean;
noImplicitReturns?: boolean;
noImplicitThis?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. */
noImplicitUseStrict?: boolean;
noLib?: boolean;
noPropertyAccessFromIndexSignature?: boolean;
noResolve?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. */
noStrictGenericChecks?: boolean;
noUncheckedIndexedAccess?: boolean;
noUncheckedSideEffectImports?: boolean;
noUnusedLocals?: boolean;
noUnusedParameters?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. Use `outFile` instead. */
out?: string;
outDir?: string;
/** @deprecated Deprecated since TypeScript 6.0 and removed in 7.0. */
outFile?: string;
paths?: Record<string, string[]>;
plugins?: {
name: string;
[option: string]: any;
}[];
preserveConstEnums?: boolean;
preserveSymlinks?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. Use `verbatimModuleSyntax` instead. */
preserveValueImports?: boolean;
project?: string;
reactNamespace?: string;
removeComments?: boolean;
resolveJsonModule?: boolean;
resolvePackageJsonExports?: boolean;
resolvePackageJsonImports?: boolean;
rewriteRelativeImportExtensions?: boolean;
rootDir?: string;
rootDirs?: string[];
skipDefaultLibCheck?: boolean;
skipLibCheck?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
stableTypeOrdering?: boolean;
strict?: boolean;
strictBindCallApply?: boolean;
strictBuiltinIteratorReturn?: boolean;
strictFunctionTypes?: boolean;
strictNullChecks?: boolean;
strictPropertyInitialization?: boolean;
stripInternal?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. */
suppressExcessPropertyErrors?: boolean;
/** @deprecated Deprecated since TypeScript 5.0 and removed in 5.6. */
suppressImplicitAnyIndexErrors?: boolean;
suppressOutputPathCheck?: boolean;
target?: any;
traceResolution?: boolean;
tsBuildInfoFile?: string;
typeRoots?: string[];
types?: string[];
useDefineForClassFields?: boolean;
useUnknownInCatchVariables?: boolean;
verbatimModuleSyntax?: boolean;
[option: string]: any;
}
interface TypeAcquisition {
enable?: boolean;
include?: string[];
exclude?: string[];
disableFilenameBasedTypeAcquisition?: boolean;
}
/**
* Defines a TSConfig structure.
* @param tsconfig - The contents of `tsconfig.json` as an object. See {@link TSConfig}.
* @returns the same `tsconfig.json` object.
*/
export 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.
*/
export 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}.
*/
export 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.
*/
export 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 can’t 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 can’t 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. It’s a string. This helps people discover your package, as it’s listed in `npm search`.
*/
description?: string;
/**
* Put keywords in it. It’s an array of strings. This helps people discover your package as it’s listed in `npm search`.
*/
keywords?: string[];
/**
* The url to the project homepage.
*/
homepage?: string;
/**
* The url to your project’s 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 you’re 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 it’s 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 module’s 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 aren’t 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 don’t want or need to download and build the external test or documentation framework that you use.
* In this case, it’s 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.
*/
export 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.
*/
export 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.
*/
export 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}.
*/
export 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.
*/
export 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}.
*/
export 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.
*/
export 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.
*/
export 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.
*/
export declare function findWorkspaceDir(id?: string, options?: ResolveOptions & Partial<Record<WorkspaceTestName, boolean | "closest" | "furthest">> & {
tests?: WorkspaceTestName[];
}): Promise<string>;
/**
* Reads a package file, allows a callback to mutate it, and writes back the result while preserving the original file format.
*
* @param id - The path to package.json or directory to locate the package file.
* @param callback - A function that receives the package object (proxied) and may mutate it in-place or return a new object.
* @param options - Options for resolving and reading the file. See {@link ResolveOptions} and {@link ReadOptions}.
* @returns A promise that resolves once the package file has been written.
*/
export declare function updatePackage(id: string, callback: (pkg: PackageJson) => PackageJson | void | Promise<PackageJson | void>, options?: ResolveOptions & ReadOptions): Promise<void>;
/**
* Returns a new `PackageJson` with known top-level fields reordered and certain nested maps alphabetically sorted.
*
* Known keys are reordered according to project conventions; unknown keys retain their original relative order.
* Nested maps such as dependency maps and `scripts` are sorted alphabetically by key.
*
* @param pkg - The `package.json` object to sort.
* @returns A new `PackageJson` object with fields and nested maps sorted.
*/
export declare function sortPackage(pkg: PackageJson): PackageJson;
/**
* Normalizes a `PackageJson` for stable output by sorting fields and removing invalid dependency declarations.
*
* Sorts top-level fields and dependency objects alphabetically, and removes dependency fields
* (`dependencies`, `devDependencies`, etc.) that are not plain objects.
*
* @param pkg - The `package.json` object to normalize.
* @returns A new normalized `PackageJson` object.
*/
export 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.
*/
export declare function defineGitConfig(config: GitConfig): GitConfig;
/**
* Finds closest `.git/config` file.
*/
export declare function resolveGitConfig(dir: string, opts?: ResolveOptions): Promise<string>;
/**
* Finds and reads closest `.git/config` file into a JS object.
*/
export declare function readGitConfig(dir: string, opts?: ResolveOptions): Promise<GitConfig>;
/**
* Stringifies git config object into INI text format and writes it to a file.
*/
export declare function writeGitConfig(path: string, config: GitConfig): Promise<void>;
/**
* Parses a git config file in INI text format into a JavaScript object.
*/
export declare function parseGitConfig(ini: string): GitConfig;
/**
* Stringifies a git config object into a git config file INI text format.
*/
export declare function stringifyGitConfig(config: GitConfig): string;
export type { FindFileOptions, GitBranch, GitConfig, GitConfigUser, GitCoreConfig, GitRemote, PackageJson, PackageJsonExports, PackageJsonPerson, ReadOptions, ResolveOptions, TSConfig };
@@ -0,0 +1,345 @@
import { promises, statSync } from "node:fs";
import { dirname, isAbsolute, join, normalize, resolve } from "pathe";
import { parseJSONC, stringifyJSONC } from "confbox/jsonc";
import { resolveModulePath } from "exsolve";
import { fileURLToPath } from "node:url";
import { parseJSON, stringifyJSON } from "confbox/json";
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 filename of filenames) {
const filePath = join(...segments.slice(0, index), filename);
if (await options.test(filePath)) return filePath;
}
else for (let index = segments.length; index > root; index--) for (const filename of filenames) {
const filePath = join(...segments.slice(0, index), filename);
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",
"upm.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")) {
const { parseJSON5 } = await import("confbox/json5");
parsed = parseJSON5(blob);
} else if (resolvedPath.endsWith(".yaml")) {
const { parseYAML } = await import("confbox/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")) {
const { stringifyJSON5 } = await import("confbox/json5");
content = stringifyJSON5(pkg);
} else if (path.endsWith(".yaml")) {
const { stringifyYAML } = await import("confbox/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);
await writePackage(resolvedPath, await callback(new Proxy(pkg, { get(target, prop) {
if (typeof prop === "string" && objectKeys.has(prop) && !Object.hasOwn(target, prop)) target[prop] = {};
return Reflect.get(target, prop);
} })) || pkg);
}
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: _resolvePath(dir, opts)
});
}
async function readGitConfig(dir, opts) {
const path = await resolveGitConfig(dir, opts);
return parseGitConfig(await readFile(path, "utf8"));
}
async function writeGitConfig(path, config) {
await writeFile(path, stringifyGitConfig(config));
}
const _unescapeGitSubsection = (name) => name.replaceAll(/\\(.)/g, "$1");
const _escapeGitSubsection = (name) => name.replaceAll(/(["\\])/g, "\\$1");
const _escapeINISection = (name) => name.replaceAll("\\", String.raw`\\`).replaceAll(".", String.raw`\.`);
const _encodeINISection = (name) => encodeURIComponent(name).replaceAll(".", "%2E");
const _decodeINISection = (name) => decodeURIComponent(name);
const _isSubsection = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
function parseGitConfig(ini) {
return parseINI(ini.replaceAll(/^\[(\w+) "(.*)"\]$/gm, (_, section, subsection) => `[${section}.${_escapeINISection(_unescapeGitSubsection(subsection))}]`));
}
function stringifyGitConfig(config) {
const encoded = {};
for (const [section, value] of Object.entries(config)) {
if (!_isSubsection(value)) {
encoded[section] = value;
continue;
}
const entries = {};
for (const [key, subValue] of Object.entries(value)) entries[_isSubsection(subValue) ? _encodeINISection(key) : key] = subValue;
encoded[section] = entries;
}
return stringifyINI(encoded).replaceAll(/^\[(\w+)\.(.*)\]$/gm, (_, section, subsection) => `[${section} "${_escapeGitSubsection(_decodeINISection(subsection))}"]`);
}
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 };
@@ -0,0 +1,47 @@
{
"name": "pkg-types",
"version": "2.4.0",
"description": "Node.js utilities and TypeScript definitions for `package.json` and `tsconfig.json`",
"license": "MIT",
"repository": {
"type": "git",
"url": "unjs/pkg-types"
},
"files": [
"dist"
],
"sideEffects": false,
"main": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": "./dist/index.mjs"
},
"dependencies": {
"confbox": "^0.3.1",
"exsolve": "^1.1.3",
"pathe": "^2.0.3"
},
"devDependencies": {
"@types/node": "^26.6.5",
"@vitest/coverage-v8": "^5.0.5",
"automd": "^0.4.3",
"changelogen": "^0.6.2",
"eslint-config-unjs": "^0.6.2",
"expect-type": "^1.4.0",
"obuild": "^0.4.45",
"oxfmt": ">=0.73.0",
"oxlint": "^1.88.0",
"prettier": "^3.9.10",
"typescript": "^7",
"vitest": "^5.0.5"
},
"scripts": {
"build": "obuild",
"dev": "vitest --typecheck",
"lint": "oxlint && oxfmt --check .",
"fmt": "automd && oxlint --fix . && oxfmt",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
"test": "pnpm lint && pnpm typecheck",
"typecheck": "tsc --noEmit --skipLibCheck"
}
}
+65
View File
@@ -0,0 +1,65 @@
{
"name": "local-pkg",
"type": "module",
"version": "1.2.1",
"description": "Get information on local packages.",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu-collective/local-pkg#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu-collective/local-pkg.git"
},
"bugs": {
"url": "https://github.com/antfu-collective/local-pkg/issues"
},
"keywords": [
"package"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=14"
},
"dependencies": {
"mlly": "^1.7.4",
"pkg-types": "^2.3.0",
"quansync": "^0.2.11"
},
"devDependencies": {
"@antfu/eslint-config": "^5.2.1",
"@antfu/ni": "^25.0.0",
"@antfu/utils": "^9.2.0",
"@types/chai": "^5.2.2",
"@types/node": "^24.3.0",
"bumpp": "^10.2.3",
"chai": "^5.3.1",
"eslint": "^9.33.0",
"esno": "^4.8.0",
"find-up-simple": "^1.0.1",
"typescript": "^5.9.2",
"unbuild": "^3.6.1",
"unplugin-quansync": "^0.4.4",
"vitest": "^3.2.4"
},
"scripts": {
"build": "unbuild",
"lint": "eslint .",
"release": "bumpp",
"typecheck": "tsc --noEmit",
"test": "vitest run && node ./test/cjs.cjs && node ./test/esm.mjs"
}
}