WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSUtils = exports.TSESLint = exports.JSONSchema = exports.ESLintUtils = exports.ASTUtils = void 0;
exports.ASTUtils = __importStar(require("./ast-utils"));
exports.ESLintUtils = __importStar(require("./eslint-utils"));
exports.JSONSchema = __importStar(require("./json-schema"));
exports.TSESLint = __importStar(require("./ts-eslint"));
__exportStar(require("./ts-estree"), exports);
exports.TSUtils = __importStar(require("./ts-utils"));

View File

@@ -0,0 +1 @@
{"version":3,"file":"signatureKind.d.ts","sourceRoot":"","sources":["../../src/enums/signatureKind.ts"],"names":[],"mappings":"AACA,eAAO,IAAI,aAAa,EAAE,GAAG,CAAC"}

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte

View File

@@ -0,0 +1,5 @@
type MessageIds = 'suggestRemove' | 'suggestSatisfies' | 'unnecessaryTypeConversion';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageIds, [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,295 @@
import { H as ResolverFactory, J as moduleRunnerTransform, K as isolatedDeclaration, L as NapiResolveOptions, M as IsolatedDeclarationsOptions, N as IsolatedDeclarationsResult, V as ResolveResult, _ as BindingTsconfigCompilerOptions, i as BindingClientHmrUpdate, k as BindingViteTransformPluginConfig, n as BindingBundleAnalyzerPluginConfig, p as BindingRebuildStrategy, q as isolatedDeclarationSync, r as BindingBundleState, u as BindingLazyChunkOutput, v as BindingTsconfigRawOptions, w as BindingViteManifestPluginConfig } from "./shared/binding-CVtkJvyl.mjs";
import { $ as defineParallelPlugin, Gt as StringOrRegExp, I as BuiltinPlugin, Qt as freeExternalMemory, Vt as OutputOptions, Xt as RolldownOutput, l as InputOptions, ut as NormalizedOutputOptions } from "./shared/define-config-Dsp5YQR4.mjs";
import { a as MinifyOptions$1, c as minifySync$1, d as parse$1, f as parseSync$1, i as transformSync$1, l as ParseResult$1, m as resolveTsconfig, n as TransformResult$1, o as MinifyResult$1, p as TsconfigCache$1, r as transform$1, s as minify$1, t as TransformOptions$1, u as ParserOptions$1 } from "./shared/transform-WmU_cI8e.mjs";
import { a as viteDynamicImportVarsPlugin, c as viteLoadFallbackPlugin, d as viteReporterPlugin, f as viteResolvePlugin, i as viteBuildImportAnalysisPlugin, l as viteModulePreloadPolyfillPlugin, n as isolatedDeclarationPlugin, o as viteImportGlobPlugin, p as viteWebWorkerPostPlugin, r as oxcRuntimePlugin, s as viteJsonPlugin, u as viteReactRefreshWrapperPlugin } from "./shared/constructors-CGzna3vk.mjs";
//#region src/api/dev/dev-options.d.ts
type DevOnHmrUpdates = (result: Error | {
updates: BindingClientHmrUpdate[];
changedFiles: string[];
}) => void | Promise<void>;
type DevOnOutput = (result: Error | RolldownOutput) => void | Promise<void>;
type DevOnAdditionalAssets = (output: RolldownOutput) => void | Promise<void>;
interface DevWatchOptions {
/**
* If `false`, no file system watcher is started, so file changes are never
* picked up and no rebuild or HMR update is triggered on their own.
* @default true
*/
enabled?: boolean;
/**
* If `true`, files are not written to disk.
* @default false
*/
skipWrite?: boolean;
/**
* If `true`, use polling instead of native file system events for watching.
* @default false
*/
usePolling?: boolean;
/**
* Poll interval in milliseconds (only used when usePolling is true).
* @default 100
*/
pollInterval?: number;
/**
* If `true`, use debounced watcher. If `false`, use non-debounced watcher for immediate responses.
* @default true
*/
useDebounce?: boolean;
/**
* Debounce duration in milliseconds (only used when useDebounce is true).
* @default 10
*/
debounceDuration?: number;
/**
* Whether to compare file contents for poll-based watchers (only used when usePolling is true).
* When enabled, poll watchers will check file contents to determine if they actually changed.
* @default false
*/
compareContentsForPolling?: boolean;
/**
* Tick rate in milliseconds for debounced watchers (only used when useDebounce is true).
* Controls how frequently the debouncer checks for events to process.
* When not specified, the debouncer will auto-select an appropriate tick rate (1/4 of the debounce duration).
* @default undefined (auto-select)
*/
debounceTickRate?: number;
/**
* Filter to limit which discovered files are registered with the file watcher.
*
* Strings are treated as glob patterns.
*
* @default []
*/
include?: StringOrRegExp | StringOrRegExp[];
/**
* Filter to prevent discovered files from being registered with the file watcher.
*
* Strings are treated as glob patterns.
*
* @default []
*/
exclude?: StringOrRegExp | StringOrRegExp[];
}
interface DevOptions {
onHmrUpdates?: DevOnHmrUpdates;
onOutput?: DevOnOutput;
/**
* Called with assets emitted while generating an HMR patch or compiling a
* lazy entry (e.g. an image newly imported by the changed/lazy module).
*
* These never go through {@link onOutput}, so a consumer that serves built
* files (e.g. Vite's bundled dev server) must register this to receive them
* and write them to its in-memory file store before the client requests them.
*/
onAdditionalAssets?: DevOnAdditionalAssets;
/**
* Strategy for triggering rebuilds after HMR updates.
* - `'always'`: Always trigger a rebuild after HMR updates
* - `'never'`: Never trigger rebuild after HMR updates. The server no longer
* decides full reloads, so there is no `'auto'` upgrade anymore; pull fresh
* bundle output explicitly (e.g. `ensureLatestBuildOutput`) when needed.
* @default 'never'
*/
rebuildStrategy?: "always" | "never";
watch?: DevWatchOptions;
}
//#endregion
//#region src/api/dev/dev-engine.d.ts
declare class DevEngine {
#private;
static create(inputOptions: InputOptions, outputOptions?: OutputOptions, devOptions?: DevOptions): Promise<DevEngine>;
private constructor();
run(): Promise<void>;
ensureCurrentBuildFinish(): Promise<void>;
getBundleState(): Promise<BindingBundleState>;
ensureLatestBuildOutput(): Promise<void>;
triggerFullBuild(): void;
/**
* Client-connect signal (the clientId hello): creates the per-client session
* with an empty ship map. Reconnects arrive as fresh clientIds.
*/
registerClient(clientId: string): Promise<void>;
/**
* Delivery notification from the serving middleware: the response for
* `filename` completed, so record its modules as shipped to that client.
*/
notifyPayloadDelivered(filename: string): Promise<void>;
removeClient(clientId: string): Promise<void>;
close(): Promise<void>;
/**
* Compile a lazy entry module and return HMR-style patch code.
*
* This is called when a dynamically imported module is first requested at runtime.
* The module was previously stubbed with a proxy, and now we need to compile the
* actual module and its dependencies.
*
* @param moduleId - The absolute file path of the module to compile
* @param clientId - The client ID requesting this compilation
* @returns The compiled chunk: its code plus the filename whose delivery the
* serving middleware reports via {@link notifyPayloadDelivered}
*/
compileEntry(moduleId: string, clientId: string): Promise<BindingLazyChunkOutput>;
}
//#endregion
//#region src/api/dev/index.d.ts
declare const dev: typeof DevEngine.create;
//#endregion
//#region src/api/experimental.d.ts
/**
* This is an experimental API. Its behavior may change in the future.
*
* - Calling this API will only execute the `scan/build` stage of rolldown.
* - `scan` will clean up all resources automatically, but if you want to ensure timely cleanup, you need to wait for the returned promise to resolve.
*
* @example To ensure cleanup of resources, use the returned promise to wait for the scan to complete.
* ```ts
* import { scan } from 'rolldown/api/experimental';
*
* const cleanupPromise = await scan(...);
* await cleanupPromise;
* // Now all resources have been cleaned up.
* ```
*/
declare const scan: (rawInputOptions: InputOptions, rawOutputOptions?: {}) => Promise<Promise<void>>;
//#endregion
//#region src/builtin-plugin/alias-plugin.d.ts
type ViteAliasPluginConfig = {
entries: {
find: string | RegExp;
replacement: string;
}[];
};
declare function viteAliasPlugin(config: ViteAliasPluginConfig): BuiltinPlugin;
//#endregion
//#region src/builtin-plugin/bundle-analyzer-plugin.d.ts
/**
* A plugin that analyzes bundle composition and generates detailed reports.
*
* The plugin outputs a file containing detailed information about:
* - All chunks and their relationships
* - Modules bundled in each chunk
* - Import dependencies between chunks
* - Reachable modules from each entry point
*
* @example
* ```js
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
*
* export default {
* plugins: [
* bundleAnalyzerPlugin()
* ]
* }
* ```
*
* @example
* **Custom filename**
* ```js
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
*
* export default {
* plugins: [
* bundleAnalyzerPlugin({
* fileName: 'bundle-analysis.json'
* })
* ]
* }
* ```
*
* @example
* **LLM-friendly markdown output**
* ```js
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
*
* export default {
* plugins: [
* bundleAnalyzerPlugin({
* format: 'md'
* })
* ]
* }
* ```
*/
declare function bundleAnalyzerPlugin(config?: BindingBundleAnalyzerPluginConfig): BuiltinPlugin;
//#endregion
//#region src/builtin-plugin/transform-plugin.d.ts
type TransformPattern = string | RegExp | readonly (RegExp | string)[];
type TransformPluginConfig = Omit<BindingViteTransformPluginConfig, "include" | "exclude" | "jsxRefreshInclude" | "jsxRefreshExclude" | "yarnPnp"> & {
include?: TransformPattern;
exclude?: TransformPattern;
jsxRefreshInclude?: TransformPattern;
jsxRefreshExclude?: TransformPattern;
};
declare function viteTransformPlugin(config: TransformPluginConfig): BuiltinPlugin;
//#endregion
//#region src/builtin-plugin/vite-manifest-plugin.d.ts
type ViteManifestPluginConfig = Omit<BindingViteManifestPluginConfig, "isLegacy"> & {
isOutputOptionsForLegacyChunks?: (outputOptions: NormalizedOutputOptions) => boolean;
};
declare function viteManifestPlugin(config: ViteManifestPluginConfig): BuiltinPlugin;
//#endregion
//#region src/experimental-index.d.ts
/**
* In-memory file system for browser builds.
*
* This is a re-export of the {@link https://github.com/streamich/memfs | memfs} package used by the WASI runtime.
* It allows you to read and write files to a virtual filesystem when using rolldown in browser environments.
*
* - `fs`: A Node.js-compatible filesystem API (`IFs` from memfs)
* - `volume`: The underlying `Volume` instance that stores the filesystem state
*
* Returns `undefined` in Node.js builds (only available in browser builds via `@rolldown/browser`).
*
* @example
* ```typescript
* import { memfs } from 'rolldown/experimental';
*
* // Write files to virtual filesystem before bundling
* memfs?.volume.fromJSON({
* '/src/index.js': 'export const foo = 42;',
* '/package.json': '{"name": "my-app"}'
* });
*
* // Read files from the virtual filesystem
* const content = memfs?.fs.readFileSync('/src/index.js', 'utf8');
* ```
*
* @see {@link https://github.com/streamich/memfs} for more information on the memfs API.
*/
declare const memfs: {
fs: any;
volume: any;
} | undefined;
/** @deprecated Use from `rolldown/utils` instead. */
declare const parse: typeof parse$1;
/** @deprecated Use from `rolldown/utils` instead. */
declare const parseSync: typeof parseSync$1;
/** @deprecated Use from `rolldown/utils` instead. */
type ParseResult = ParseResult$1;
/** @deprecated Use from `rolldown/utils` instead. */
type ParserOptions = ParserOptions$1;
/** @deprecated Use from `rolldown/utils` instead. */
declare const minify: typeof minify$1;
/** @deprecated Use from `rolldown/utils` instead. */
declare const minifySync: typeof minifySync$1;
/** @deprecated Use from `rolldown/utils` instead. */
type MinifyOptions = MinifyOptions$1;
/** @deprecated Use from `rolldown/utils` instead. */
type MinifyResult = MinifyResult$1;
/** @deprecated Use from `rolldown/utils` instead. */
declare const transform: typeof transform$1;
/** @deprecated Use from `rolldown/utils` instead. */
declare const transformSync: typeof transformSync$1;
/** @deprecated Use from `rolldown/utils` instead. */
type TransformOptions = TransformOptions$1;
/** @deprecated Use from `rolldown/utils` instead. */
type TransformResult = TransformResult$1;
/** @deprecated Use from `rolldown/utils` instead. */
declare const TsconfigCache: typeof TsconfigCache$1;
/** @deprecated Use from `rolldown/utils` instead. */
type TsconfigRawOptions = BindingTsconfigRawOptions;
/** @deprecated Use from `rolldown/utils` instead. */
type TsconfigCompilerOptions = BindingTsconfigCompilerOptions;
//#endregion
export { type BindingClientHmrUpdate, BindingRebuildStrategy, DevEngine, type DevOptions, type DevWatchOptions, type IsolatedDeclarationsOptions, type IsolatedDeclarationsResult, MinifyOptions, MinifyResult, ParseResult, ParserOptions, type NapiResolveOptions as ResolveOptions, type ResolveResult, ResolverFactory, TransformOptions, TransformResult, TsconfigCache, TsconfigCompilerOptions, TsconfigRawOptions, bundleAnalyzerPlugin, defineParallelPlugin, dev, viteDynamicImportVarsPlugin as dynamicImportVarsPlugin, viteDynamicImportVarsPlugin, freeExternalMemory, viteImportGlobPlugin as importGlobPlugin, viteImportGlobPlugin, isolatedDeclaration, isolatedDeclarationPlugin, isolatedDeclarationSync, memfs, minify, minifySync, moduleRunnerTransform, oxcRuntimePlugin, parse, parseSync, resolveTsconfig, scan, transform, transformSync, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReactRefreshWrapperPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWebWorkerPostPlugin };

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.aoutput = exports.anumber = exports.aexists = exports.abytes = void 0;
/**
* Internal assertion helpers.
* @module
* @deprecated
*/
const utils_ts_1 = require("./utils.js");
/** @deprecated Use import from `noble/hashes/utils` module */
exports.abytes = utils_ts_1.abytes;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.aexists = utils_ts_1.aexists;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.anumber = utils_ts_1.anumber;
/** @deprecated Use import from `noble/hashes/utils` module */
exports.aoutput = utils_ts_1.aoutput;
//# sourceMappingURL=_assert.js.map

View File

@@ -0,0 +1,24 @@
import { Test } from '@vitest/runner';
import { ChainableFunction } from '@vitest/runner/utils';
import { TaskResult, Bench, Options } from 'tinybench';
interface Benchmark extends Test {
meta: {
benchmark: true;
result?: TaskResult;
};
}
interface BenchmarkResult extends TaskResult {
name: string;
rank: number;
sampleCount: number;
median: number;
}
type BenchFunction = (this: Bench) => Promise<void> | void;
type ChainableBenchmarkAPI = ChainableFunction<"skip" | "only" | "todo", (name: string | Function, fn?: BenchFunction, options?: Options) => void>;
type BenchmarkAPI = ChainableBenchmarkAPI & {
skipIf: (condition: any) => ChainableBenchmarkAPI;
runIf: (condition: any) => ChainableBenchmarkAPI;
};
export type { BenchmarkResult as B, BenchFunction as a, Benchmark as b, BenchmarkAPI as c };

View File

@@ -0,0 +1 @@
{"version":3,"file":"urn-uuid.js","sourceRoot":"","sources":["../../../src/schemes/urn-uuid.ts"],"names":[],"mappings":"AAQA,MAAM,IAAI,GAAG,0DAA0D,CAAC;AACxE,MAAM,UAAU,GAAG,oBAAoB,CAAC;AAExC,UAAU;AACV,MAAM,OAAO,GAA+D;IAC3E,MAAM,EAAG,UAAU;IAEnB,KAAK,EAAG,UAAU,aAA2B,EAAE,OAAkB;QAChE,MAAM,cAAc,GAAG,aAA+B,CAAC;QACvD,cAAc,CAAC,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC;QACzC,cAAc,CAAC,GAAG,GAAG,SAAS,CAAC;QAE/B,IAAI,CAAC,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC,cAAc,CAAC,IAAI,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE;YACpF,cAAc,CAAC,KAAK,GAAG,cAAc,CAAC,KAAK,IAAI,oBAAoB,CAAC;SACpE;QAED,OAAO,cAAc,CAAC;IACvB,CAAC;IAED,SAAS,EAAG,UAAU,cAA6B,EAAE,OAAkB;QACtE,MAAM,aAAa,GAAG,cAA+B,CAAC;QACtD,gBAAgB;QAChB,aAAa,CAAC,GAAG,GAAG,CAAC,cAAc,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC9D,OAAO,aAAa,CAAC;IACtB,CAAC;CACD,CAAC;AAEF,eAAe,OAAO,CAAC"}

View File

@@ -0,0 +1,114 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// SEE https://typescript-eslint.io/users/configs
//
// For developers working in the typescript-eslint monorepo:
// You can regenerate it using `pnpm run generate-configs`
module.exports = {
extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'],
rules: {
'@typescript-eslint/await-thenable': 'error',
'@typescript-eslint/ban-ts-comment': [
'error',
{ minimumDescriptionLength: 10 },
],
'no-array-constructor': 'off',
'@typescript-eslint/no-array-constructor': 'error',
'@typescript-eslint/no-array-delete': 'error',
'@typescript-eslint/no-base-to-string': 'error',
'@typescript-eslint/no-confusing-void-expression': 'error',
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/no-duplicate-enum-values': 'error',
'@typescript-eslint/no-duplicate-type-constituents': 'error',
'@typescript-eslint/no-dynamic-delete': 'error',
'@typescript-eslint/no-empty-object-type': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-extra-non-null-assertion': 'error',
'@typescript-eslint/no-extraneous-class': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-for-in-array': 'error',
'no-implied-eval': 'off',
'@typescript-eslint/no-implied-eval': 'error',
'@typescript-eslint/no-invalid-void-type': 'error',
'@typescript-eslint/no-meaningless-void-operator': 'error',
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-misused-promises': 'error',
'@typescript-eslint/no-misused-spread': 'error',
'@typescript-eslint/no-mixed-enums': 'error',
'@typescript-eslint/no-namespace': 'error',
'@typescript-eslint/no-non-null-asserted-nullish-coalescing': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-non-null-assertion': 'error',
'@typescript-eslint/no-redundant-type-constituents': 'error',
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error',
'@typescript-eslint/no-unnecessary-condition': 'error',
'@typescript-eslint/no-unnecessary-template-expression': 'error',
'@typescript-eslint/no-unnecessary-type-arguments': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unnecessary-type-conversion': 'error',
'@typescript-eslint/no-unnecessary-type-parameters': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-call': 'error',
'@typescript-eslint/no-unsafe-declaration-merging': 'error',
'@typescript-eslint/no-unsafe-enum-comparison': 'error',
'@typescript-eslint/no-unsafe-function-type': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-return': 'error',
'@typescript-eslint/no-unsafe-unary-minus': 'error',
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 'error',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-useless-default-assignment': 'error',
'@typescript-eslint/no-wrapper-object-types': 'error',
'no-throw-literal': 'off',
'@typescript-eslint/only-throw-error': 'error',
'@typescript-eslint/prefer-as-const': 'error',
'@typescript-eslint/prefer-literal-enum-member': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
'prefer-promise-reject-errors': 'off',
'@typescript-eslint/prefer-promise-reject-errors': 'error',
'@typescript-eslint/prefer-reduce-type-parameter': 'error',
'@typescript-eslint/prefer-return-this-type': 'error',
'@typescript-eslint/related-getter-setter-pairs': 'error',
'require-await': 'off',
'@typescript-eslint/require-await': 'error',
'@typescript-eslint/restrict-plus-operands': [
'error',
{
allowAny: false,
allowBoolean: false,
allowNullish: false,
allowNumberAndString: false,
allowRegExp: false,
},
],
'@typescript-eslint/restrict-template-expressions': [
'error',
{
allowAny: false,
allowBoolean: false,
allowNever: false,
allowNullish: false,
allowNumber: false,
allowRegExp: false,
},
],
'no-return-await': 'off',
'@typescript-eslint/return-await': [
'error',
'error-handling-correctness-only',
],
'@typescript-eslint/triple-slash-reference': 'error',
'@typescript-eslint/unbound-method': 'error',
'@typescript-eslint/unified-signatures': 'error',
'@typescript-eslint/use-unknown-in-catch-callback-variable': 'error',
},
};

View File

@@ -0,0 +1,230 @@
<p align="center">
<a href="#"><img src="./docs/images/banner.png" /></a>
</p>
<p align="center">
A simple and composable way <br/>
to validate data in JavaScript (and TypeScript).
</p>
<br/>
<br/>
<p align="center">
<a href="#usage">Usage</a> •
<a href="#why">Why?</a> •
<a href="#principles">Principles</a> •
<a href="#demo">Demo</a> •
<a href="#examples">Examples</a> •
<a href="#documentation">Documentation</a>
</p>
<p align="center">
<a href="https://unpkg.com/superstruct/umd/superstruct.min.js">
<img src="https://badgen.net/bundlephobia/minzip/superstruct?color=green&label=size">
</a>
<a href="./package.json">
<img src="https://badgen.net/npm/v/superstruct?color=blue&label=version">
</a>
</p>
<br/>
<br/>
Superstruct makes it easy to define interfaces and then validate JavaScript data against them. Its type annotation API was inspired by [Typescript](https://www.typescriptlang.org/docs/handbook/basic-types.html), [Flow](https://flow.org/en/docs/types/), [Go](https://gobyexample.com/structs), and [GraphQL](http://graphql.org/learn/schema/), giving it a familiar and easy to understand API.
But Superstruct is designed for validating data at runtime, so it throws (or returns) detailed runtime errors for you or your end users. This is especially useful in situations like accepting arbitrary input in a REST or GraphQL API. But it can even be used to validate internal data structures at runtime when needed.
<br/>
### Usage
Superstruct allows you to define the shape of data you want to validate:
```js
import { assert, object, number, string, array } from 'superstruct'
const Article = object({
id: number(),
title: string(),
tags: array(string()),
author: object({
id: number(),
}),
})
const data = {
id: 34,
title: 'Hello World',
tags: ['news', 'features'],
author: {
id: 1,
},
}
assert(data, Article)
// This will throw an error when the data is invalid.
// If you'd rather not throw, you can use `is()` or `validate()`.
```
Superstruct ships with validators for all the common JavaScript data types, and you can define custom ones too:
```js
import { is, define, object, string } from 'superstruct'
import isUuid from 'is-uuid'
import isEmail from 'is-email'
const Email = define('Email', isEmail)
const Uuid = define('Uuid', isUuid.v4)
const User = object({
id: Uuid,
email: Email,
name: string(),
})
const data = {
id: 'c8d63140-a1f7-45e0-bfc6-df72973fea86',
email: 'jane@example.com',
name: 'Jane',
}
if (is(data, User)) {
// Your data is guaranteed to be valid in this block.
}
```
Superstruct can also handle coercion of your data before validating it, for example to mix in default values:
```ts
import { create, object, number, string, defaulted } from 'superstruct'
let i = 0
const User = object({
id: defaulted(number(), () => i++),
name: string(),
})
const data = {
name: 'Jane',
}
// You can apply the defaults to your data while validating.
const user = create(data, User)
// {
// id: 0,
// name: 'Jane',
// }
```
And if you use TypeScript, Superstruct automatically ensures that your data has proper typings whenever you validate it:
```ts
import { is, object, number, string } from 'superstruct'
const User = object({
id: number(),
name: string()
})
const data: unknown = { ... }
if (is(data, User)) {
// TypeScript knows the shape of `data` here, so it is safe to access
// properties like `data.id` and `data.name`.
}
```
Superstruct supports more complex use cases too like defining arrays or nested objects, composing structs inside each other, returning errors instead of throwing them, and more! For more information read the full [Documentation](#documentation).
<br/>
### Why?
There are lots of existing validation libraries—[`joi`](https://github.com/hapijs/joi), [`express-validator`](https://github.com/ctavan/express-validator), [`validator.js`](https://github.com/chriso/validator.js), [`yup`](https://github.com/jquense/yup), [`ajv`](https://github.com/epoberezkin/ajv), [`is-my-json-valid`](https://github.com/mafintosh/is-my-json-valid)... But they exhibit many issues that lead to your codebase becoming hard to maintain...
- **They don't expose detailed errors.** Many validators simply return string-only errors or booleans without any details as to why, making it difficult to customize the errors to be helpful for end-users.
- **They make custom types hard.** Many validators ship with built-in types like emails, URLs, UUIDs, etc. with no way to know what they check for, and complicated APIs for defining new types.
- **They don't encourage single sources of truth.** Many existing APIs encourage re-defining custom data types over and over, with the source of truth being spread out across your entire code base.
- **They don't throw errors.** Many don't actually throw the errors, forcing you to wrap everywhere. Although helpful in the days of callbacks, not using `throw` in modern JavaScript makes code much more complex.
- **They're tightly coupled to other concerns.** Many validators are tightly coupled to Express or other frameworks, which results in one-off, confusing code that isn't reusable across your code base.
- **They use JSON Schema.** Don't get me wrong, JSON Schema _can_ be useful. But it's kind of like HATEOAS—it's usually way more complexity than you need and you aren't using any of its benefits. (Sorry, I said it.)
Of course, not every validation library suffers from all of these issues, but most of them exhibit at least one. If you've run into this problem before, you might like Superstruct.
Which brings me to how Superstruct solves these issues...
<br/>
### Principles
1. **Customizable types.** Superstruct's power is in making it easy to define an entire set of custom data types that are specific to your application, and defined in a _single_ place, so you have full control over your requirements.
2. **Unopinionated defaults.** Superstruct ships with native JavaScript types, and everything else is customizable, so you never have to fight to override decisions made by "core" that differ from your application's needs.
3. **Composable interfaces.** Superstruct interfaces are composable, so you can break down commonly-repeated pieces of data into components, and compose them to build up the more complex objects.
4. **Useful errors.** The errors that Superstruct throws contain all the information you need to convert them into your own application-specific errors easy, which means more helpful errors for your end users!
5. **Familiar API.** The Superstruct API was heavily inspired by [Typescript](https://www.typescriptlang.org/docs/handbook/basic-types.html), [Flow](https://flow.org/en/docs/types/), [Go](https://gobyexample.com/structs), and [GraphQL](http://graphql.org/learn/schema/). If you're familiar with any of those, then its schema definition API will feel very natural to use, so you can get started quickly.
<br/>
### Demo
Try out the [live demo on CodeSandbox](https://codesandbox.io/s/bold-water-s2cr8d?file=/index.js) to get an idea for how the API works, or to quickly verify your use case:
[![Demo screenshot.](./docs/images/demo-screenshot.png)](https://codesandbox.io/s/bold-water-s2cr8d?file=/index.js)
<br/>
### Examples
Superstruct's API is very flexible, allowing it to be used for a variety of use cases on your servers and in the browser. Here are a few examples of common patterns...
- [Basic Validation](./examples/basic-validation.js)
- [Custom Types](./examples/custom-types.js)
- [Default Values](./examples/default-values.js)
- [Optional Values](./examples/optional-values.js)
- [Composing Structs](./examples/composing-structs.js)
- [Throwing Errors](./examples/throwing-errors.js)
- [Returning Errors](./examples/returning-errors.js)
- [Testing Values](./examples/testing-values.js)
- [Custom Errors](./examples/custom-errors.js)
<br/>
### Documentation
Read the getting started guide to familiarize yourself with how Superstruct works. After that, check out the full API reference for more detailed information about structs, types and errors...
- [**Guide**](https://docs.superstructjs.org/guides/01-getting-started)
- [Getting Started](https://docs.superstructjs.org/guides/01-getting-started)
- [Validating Data](https://docs.superstructjs.org/guides/02-validating-data)
- [Coercing Data](https://docs.superstructjs.org/guides/03-coercing-data)
- [Refining Validation](https://docs.superstructjs.org/guides/04-refining-validation)
- [Handling Errors](https://docs.superstructjs.org/guides/05-handling-errors)
- [Using TypeScript](https://docs.superstructjs.org/guides/06-using-typescript)
- [**Reference**](https://docs.superstructjs.org/api-reference/core)
- [Core](https://docs.superstructjs.org/api-reference/core)
- [Types](https://docs.superstructjs.org/api-reference/types)
- [Refinements](https://docs.superstructjs.org/api-reference/refinements)
- [Coercions](https://docs.superstructjs.org/api-reference/coercions)
- [Utilities](https://docs.superstructjs.org/api-reference/utilities)
- [Errors](https://docs.superstructjs.org/api-reference/errors)
- [TypeScript](https://docs.superstructjs.org/api-reference/typescript)
- [**FAQ**](https://docs.superstructjs.org/resources/faq)
- [**Resources**](https://docs.superstructjs.org/resources/links)
[![Docs screenshot.](./docs/images/docs-screenshot.png)](https://docs.superstructjs.org)
<br/>
### License
This package is [MIT-licensed](./License.md).

View File

@@ -0,0 +1,13 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
# [*.md]
# trim_trailing_whitespace = false

View File

@@ -0,0 +1,11 @@
"use strict";
var _array_without_holes = require("./_array_without_holes.cjs");
var _iterable_to_array = require("./_iterable_to_array.cjs");
var _non_iterable_spread = require("./_non_iterable_spread.cjs");
var _unsupported_iterable_to_array = require("./_unsupported_iterable_to_array.cjs");
function _to_consumable_array(arr) {
return _array_without_holes._(arr) || _iterable_to_array._(arr) || _unsupported_iterable_to_array._(arr) || _non_iterable_spread._();
}
exports._ = _to_consumable_array;

View File

@@ -0,0 +1,236 @@
//
// Eyes.js - a customizable value inspector for Node.js
//
// usage:
//
// var inspect = require('eyes').inspector({styles: {all: 'magenta'}});
// inspect(something); // inspect with the settings passed to `inspector`
//
// or
//
// var eyes = require('eyes');
// eyes.inspect(something); // inspect with the default settings
//
var eyes = exports,
stack = [];
eyes.defaults = {
styles: { // Styles applied to stdout
all: 'cyan', // Overall style applied to everything
label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]`
other: 'inverted', // Objects which don't have a literal representation, such as functions
key: 'bold', // The keys in object literals, like 'a' in `{a: 1}`
special: 'grey', // null, undefined...
string: 'green',
number: 'magenta',
bool: 'blue', // true false
regexp: 'green', // /\d+/
},
pretty: true, // Indent object literals
hideFunctions: false,
showHidden: false,
stream: process.stdout,
maxLength: 2048 // Truncate output if longer
};
// Return a curried inspect() function, with the `options` argument filled in.
eyes.inspector = function (options) {
var that = this;
return function (obj, label, opts) {
return that.inspect.call(that, obj, label,
merge(options || {}, opts || {}));
};
};
// If we have a `stream` defined, use it to print a styled string,
// if not, we just return the stringified object.
eyes.inspect = function (obj, label, options) {
options = merge(this.defaults, options || {});
if (options.stream) {
return this.print(stringify(obj, options), label, options);
} else {
return stringify(obj, options) + (options.styles ? '\033[39m' : '');
}
};
// Output using the 'stream', and an optional label
// Loop through `str`, and truncate it after `options.maxLength` has been reached.
// Because escape sequences are, at this point embeded within
// the output string, we can't measure the length of the string
// in a useful way, without separating what is an escape sequence,
// versus a printable character (`c`). So we resort to counting the
// length manually.
eyes.print = function (str, label, options) {
for (var c = 0, i = 0; i < str.length; i++) {
if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5
else if (c === options.maxLength) {
str = str.slice(0, i - 1) + '…';
break;
} else { c++ }
}
return options.stream.write.call(options.stream, (label ?
this.stylize(label, options.styles.label, options.styles) + ': ' : '') +
this.stylize(str, options.styles.all, options.styles) + '\033[0m' + "\n");
};
// Apply a style to a string, eventually,
// I'd like this to support passing multiple
// styles.
eyes.stylize = function (str, style, styles) {
var codes = {
'bold' : [1, 22],
'underline' : [4, 24],
'inverse' : [7, 27],
'cyan' : [36, 39],
'magenta' : [35, 39],
'blue' : [34, 39],
'yellow' : [33, 39],
'green' : [32, 39],
'red' : [31, 39],
'grey' : [90, 39]
}, endCode;
if (style && codes[style]) {
endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0]
: codes[style][1];
return '\033[' + codes[style][0] + 'm' + str +
'\033[' + endCode + 'm';
} else { return str }
};
// Convert any object to a string, ready for output.
// When an 'array' or an 'object' are encountered, they are
// passed to specialized functions, which can then recursively call
// stringify().
function stringify(obj, options) {
var that = this, stylize = function (str, style) {
return eyes.stylize(str, options.styles[style], options.styles)
}, index, result;
if ((index = stack.indexOf(obj)) !== -1) {
return stylize(new(Array)(stack.length - index + 1).join('.'), 'special');
}
stack.push(obj);
result = (function (obj) {
switch (typeOf(obj)) {
case "string" : obj = stringifyString(obj.indexOf("'") === -1 ? "'" + obj + "'"
: '"' + obj + '"');
return stylize(obj, 'string');
case "regexp" : return stylize('/' + obj.source + '/', 'regexp');
case "number" : return stylize(obj + '', 'number');
case "function" : return options.stream ? stylize("Function", 'other') : '[Function]';
case "null" : return stylize("null", 'special');
case "undefined": return stylize("undefined", 'special');
case "boolean" : return stylize(obj + '', 'bool');
case "date" : return stylize(obj.toUTCString());
case "array" : return stringifyArray(obj, options, stack.length);
case "object" : return stringifyObject(obj, options, stack.length);
}
})(obj);
stack.pop();
return result;
};
// Escape invisible characters in a string
function stringifyString (str, options) {
return str.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n')
.replace(/[\u0001-\u001F]/g, function (match) {
return '\\0' + match[0].charCodeAt(0).toString(8);
});
}
// Convert an array to a string, such as [1, 2, 3].
// This function calls stringify() for each of the elements
// in the array.
function stringifyArray(ary, options, level) {
var out = [];
var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) {
return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) ||
(Array.isArray(o) && o.length > 0);
}));
var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' ';
for (var i = 0; i < ary.length; i++) {
out.push(stringify(ary[i], options));
}
if (out.length === 0) {
return '[]';
} else {
return '[' + ws
+ out.join(',' + (pretty ? ws : ' '))
+ (pretty ? ws.slice(0, -4) : ws) +
']';
}
};
// Convert an object to a string, such as {a: 1}.
// This function calls stringify() for each of its values,
// and does not output functions or prototype values.
function stringifyObject(obj, options, level) {
var out = [];
var pretty = options.pretty && (Object.keys(obj).length > 2 ||
Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' }));
var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' ';
var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj);
keys.forEach(function (k) {
if (Object.prototype.hasOwnProperty.call(obj, k)
&& !(obj[k] instanceof Function && options.hideFunctions)) {
out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' +
stringify(obj[k], options));
}
});
if (out.length === 0) {
return '{}';
} else {
return "{" + ws
+ out.join(',' + (pretty ? ws : ' '))
+ (pretty ? ws.slice(0, -4) : ws) +
"}";
}
};
// A better `typeof`
function typeOf(value) {
var s = typeof(value),
types = [Object, Array, String, RegExp, Number, Function, Boolean, Date];
if (s === 'object' || s === 'function') {
if (value) {
types.forEach(function (t) {
if (value instanceof t) { s = t.name.toLowerCase() }
});
} else { s = 'null' }
}
return s;
}
function merge(/* variable args */) {
var objs = Array.prototype.slice.call(arguments);
var target = {};
objs.forEach(function (o) {
Object.keys(o).forEach(function (k) {
if (k === 'styles') {
if (! o.styles) {
target.styles = false;
} else {
target.styles = {}
for (var s in o.styles) {
target.styles[s] = o.styles[s];
}
}
} else {
target[k] = o[k];
}
});
});
return target;
}

View File

@@ -0,0 +1,116 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "Zeichen", verb: "zu haben" },
file: { unit: "Bytes", verb: "zu haben" },
array: { unit: "Elemente", verb: "zu haben" },
set: { unit: "Elemente", verb: "zu haben" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "Eingabe",
email: "E-Mail-Adresse",
url: "URL",
emoji: "Emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO-Datum und -Uhrzeit",
date: "ISO-Datum",
time: "ISO-Uhrzeit",
duration: "ISO-Dauer",
ipv4: "IPv4-Adresse",
ipv6: "IPv6-Adresse",
cidrv4: "IPv4-Bereich",
cidrv6: "IPv6-Bereich",
base64: "Base64-codierter String",
base64url: "Base64-URL-codierter String",
json_string: "JSON-String",
e164: "E.164-Nummer",
jwt: "JWT",
template_literal: "Eingabe",
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: string;
} = {
nan: "NaN",
number: "Zahl",
array: "Array",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Ungültige Eingabe: erwartet instanceof ${issue.expected}, erhalten ${received}`;
}
return `Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `Ungültige Eingabe: erwartet ${util.stringifyPrimitive(issue.values[0])}`;
return `Ungültige Option: erwartet eine von ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ist`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`;
}
return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`;
if (_issue.format === "ends_with") return `Ungültiger String: muss mit "${_issue.suffix}" enden`;
if (_issue.format === "includes") return `Ungültiger String: muss "${_issue.includes}" enthalten`;
if (_issue.format === "regex") return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;
return `Ungültig: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`;
case "unrecognized_keys":
return `${issue.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Ungültiger Schlüssel in ${issue.origin}`;
case "invalid_union":
return "Ungültige Eingabe";
case "invalid_element":
return `Ungültiger Wert in ${issue.origin}`;
default:
return `Ungültige Eingabe`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,7 @@
"use strict";
const RuleTester = require("./rule-tester");
module.exports = {
RuleTester,
};

View File

@@ -0,0 +1,12 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2023_intl = void 0;
const base_config_1 = require("./base-config");
exports.es2023_intl = {
libs: [],
variables: [['Intl', base_config_1.TYPE_VALUE]],
};

View File

@@ -0,0 +1,5 @@
import { Parser } from "../index.js";
export declare const parsers: {
meriyah: Parser;
};

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Colin McDonnell
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.

View File

@@ -0,0 +1,79 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
type FlatArray<Arr, Depth extends number> = {
done: Arr;
recur: Arr extends ReadonlyArray<infer InnerArr> ? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
: Arr;
}[Depth extends -1 ? "done" : "recur"];
interface ReadonlyArray<T> {
/**
* Calls a defined callback function on each element of an array. Then, flattens the result into
* a new array.
* This is identical to a map followed by flat with depth 1.
*
* @param callback A function that accepts up to three arguments. The flatMap method calls the
* callback function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callback function. If
* thisArg is omitted, undefined is used as the this value.
*/
flatMap<U, This = undefined>(
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
thisArg?: This,
): U[];
/**
* Returns a new array with all sub-array elements concatenated into it recursively up to the
* specified depth.
*
* @param depth The maximum recursion depth
*/
flat<A, D extends number = 1>(
this: A,
depth?: D,
): FlatArray<A, D>[];
}
interface Array<T> {
/**
* Calls a defined callback function on each element of an array. Then, flattens the result into
* a new array.
* This is identical to a map followed by flat with depth 1.
*
* @param callback A function that accepts up to three arguments. The flatMap method calls the
* callback function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callback function. If
* thisArg is omitted, undefined is used as the this value.
*/
flatMap<U, This = undefined>(
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
thisArg?: This,
): U[];
/**
* Returns a new array with all sub-array elements concatenated into it recursively up to the
* specified depth.
*
* @param depth The maximum recursion depth
*/
flat<A, D extends number = 1>(
this: A,
depth?: D,
): FlatArray<A, D>[];
}

View File

@@ -0,0 +1,152 @@
import { WalkerBase } from './walker.js';
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
* this: WalkerContext,
* node: Node,
* parent: Node | null,
* key: string | number | symbol | null | undefined,
* index: number | null | undefined
* ) => Promise<void>} AsyncHandler
*/
export class AsyncWalker extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
/** @type {boolean} */
this.should_skip = false;
/** @type {boolean} */
this.should_remove = false;
/** @type {Node | null} */
this.replacement = null;
/** @type {WalkerContext} */
this.context = {
skip: () => (this.should_skip = true),
remove: () => (this.should_remove = true),
replace: (node) => (this.replacement = node)
};
/** @type {AsyncHandler | undefined} */
this.enter = enter;
/** @type {AsyncHandler | undefined} */
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
/** @type {keyof Node} */
let key;
for (key in node) {
/** @type {unknown} */
const value = node[key];
if (value && typeof value === 'object') {
if (Array.isArray(value)) {
const nodes = /** @type {Array<unknown>} */ (value);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!(await this.visit(item, node, key, i))) {
// removed
i--;
}
}
}
} else if (isNode(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
}
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
return (
value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string'
);
}

View File

@@ -0,0 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
const pino = require(require.resolve('./../../../'))
const log = pino({ prettyPrint: true })
const obj = Object.create(null)
Object.assign(obj, { foo: 'bar' })
log.info(obj, 'hello')

View File

@@ -0,0 +1,501 @@
import type { Angle, CssColor, Rule, CustomProperty, EnvironmentVariable, Function, Image, LengthValue, MediaQuery, Declaration, Ratio, Resolution, Selector, SupportsCondition, Time, Token, TokenOrValue, UnknownAtRule, Url, Variable, StyleRule, DeclarationBlock, ParsedComponent, Multiplier, StyleSheet, Location2 } from './ast';
import { Targets, Features } from './targets';
export * from './ast';
export { Targets, Features };
export interface TransformOptions<C extends CustomAtRules> {
/** The filename being transformed. Used for error messages and source maps. */
filename: string,
/** The source code to transform. */
code: Uint8Array,
/** Whether to enable minification. */
minify?: boolean,
/** Whether to output a source map. */
sourceMap?: boolean,
/** An input source map to extend. */
inputSourceMap?: string,
/**
* An optional project root path, used as the source root in the output source map.
* Also used to generate relative paths for sources used in CSS module hashes.
*/
projectRoot?: string,
/** The browser targets for the generated code. */
targets?: Targets,
/** Features that should always be compiled, even when supported by targets. */
include?: number,
/** Features that should never be compiled, even when unsupported by targets. */
exclude?: number,
/** Whether to enable parsing various draft syntax. */
drafts?: Drafts,
/** Whether to enable various non-standard syntax. */
nonStandard?: NonStandard,
/** Whether to compile this file as a CSS module. */
cssModules?: boolean | CSSModulesConfig,
/**
* Whether to analyze dependencies (e.g. `@import` and `url()`).
* When enabled, `@import` rules are removed, and `url()` dependencies
* are replaced with hashed placeholders that can be replaced with the final
* urls later (after bundling). Dependencies are returned as part of the result.
*/
analyzeDependencies?: boolean | DependencyOptions,
/**
* Replaces user action pseudo classes with class names that can be applied from JavaScript.
* This is useful for polyfills, for example.
*/
pseudoClasses?: PseudoClasses,
/**
* A list of class names, ids, and custom identifiers (e.g. @keyframes) that are known
* to be unused. These will be removed during minification. Note that these are not
* selectors but individual names (without any . or # prefixes).
*/
unusedSymbols?: string[],
/**
* Whether to ignore invalid rules and declarations rather than erroring.
* When enabled, warnings are returned, and the invalid rule or declaration is
* omitted from the output code.
*/
errorRecovery?: boolean,
/**
* An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript.
* Multiple visitors can be composed into one using the `composeVisitors` function.
* For optimal performance, visitors should be as specific as possible about what types of values
* they care about so that JavaScript has to be called as little as possible.
*/
visitor?: Visitor<C> | VisitorFunction<C>,
/**
* Defines how to parse custom CSS at-rules. Each at-rule can have a prelude, defined using a CSS
* [syntax string](https://drafts.css-houdini.org/css-properties-values-api/#syntax-strings), and
* a block body. The body can be a declaration list, rule list, or style block as defined in the
* [css spec](https://drafts.csswg.org/css-syntax/#declaration-rule-list).
*/
customAtRules?: C
}
// This is a hack to make TS still provide autocomplete for `property` vs. just making it `string`.
type PropertyStart = '-' | '_' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';
export type ReturnedDeclaration = Declaration | {
/** The property name. */
property: `${PropertyStart}${string}`,
/** The raw string value for the declaration. */
raw: string
};
export type ReturnedMediaQuery = MediaQuery | {
/** The raw string value for the media query. */
raw: string
};
type FindByType<Union, Name> = Union extends { type: Name } ? Union : never;
export type ReturnedRule = Rule<ReturnedDeclaration, ReturnedMediaQuery>;
type RequiredValue<Rule> = Rule extends { value: object }
? Rule['value'] extends StyleRule
? Rule & { value: Required<StyleRule> & { declarations: Required<DeclarationBlock> } }
: Rule & { value: Required<Rule['value']> }
: Rule;
type RuleVisitor<R = RequiredValue<Rule>> = ((rule: R) => ReturnedRule | ReturnedRule[] | void);
type MappedRuleVisitors = {
[Name in Exclude<Rule['type'], 'unknown' | 'custom'>]?: RuleVisitor<RequiredValue<FindByType<Rule, Name>>>;
}
type UnknownVisitors<T> = {
[name: string]: RuleVisitor<T>
}
type CustomVisitors<T extends CustomAtRules> = {
[Name in keyof T]?: RuleVisitor<CustomAtRule<Name, T[Name]>>
};
type AnyCustomAtRule<C extends CustomAtRules> = {
[Key in keyof C]: CustomAtRule<Key, C[Key]>
}[keyof C];
type RuleVisitors<C extends CustomAtRules> = MappedRuleVisitors & {
unknown?: UnknownVisitors<UnknownAtRule> | Omit<RuleVisitor<UnknownAtRule>, keyof CallableFunction>,
custom?: CustomVisitors<C> | Omit<RuleVisitor<AnyCustomAtRule<C>>, keyof CallableFunction>
};
type PreludeTypes = Exclude<ParsedComponent['type'], 'literal' | 'repeated' | 'token'>;
type SyntaxString = `<${PreludeTypes}>` | `<${PreludeTypes}>+` | `<${PreludeTypes}>#` | (string & {});
type ComponentTypes = {
[Key in PreludeTypes as `<${Key}>`]: FindByType<ParsedComponent, Key>
};
type Repetitions = {
[Key in PreludeTypes as `<${Key}>+` | `<${Key}>#`]: {
type: "repeated",
value: {
components: FindByType<ParsedComponent, Key>[],
multiplier: Multiplier
}
}
};
type MappedPrelude = ComponentTypes & Repetitions;
type MappedBody<P extends CustomAtRuleDefinition['body']> = P extends 'style-block' ? 'rule-list' : P;
interface CustomAtRule<N, R extends CustomAtRuleDefinition> {
name: N,
prelude: R['prelude'] extends keyof MappedPrelude ? MappedPrelude[R['prelude']] : ParsedComponent,
body: FindByType<CustomAtRuleBody, MappedBody<R['body']>>,
loc: Location2
}
type CustomAtRuleBody = {
type: 'declaration-list',
value: Required<DeclarationBlock>
} | {
type: 'rule-list',
value: RequiredValue<Rule>[]
};
type FindProperty<Union, Name> = Union extends { property: Name } ? Union : never;
type DeclarationVisitor<P = Declaration> = ((property: P) => ReturnedDeclaration | ReturnedDeclaration[] | void);
type MappedDeclarationVisitors = {
[Name in Exclude<Declaration['property'], 'unparsed' | 'custom'>]?: DeclarationVisitor<FindProperty<Declaration, Name> | FindProperty<Declaration, 'unparsed'>>;
}
type CustomPropertyVisitors = {
[name: string]: DeclarationVisitor<CustomProperty>
}
type DeclarationVisitors = MappedDeclarationVisitors & {
custom?: CustomPropertyVisitors | DeclarationVisitor<CustomProperty>
}
interface RawValue {
/** A raw string value which will be parsed like CSS. */
raw: string
}
type TokenReturnValue = TokenOrValue | TokenOrValue[] | RawValue | void;
type TokenVisitor = (token: Token) => TokenReturnValue;
type VisitableTokenTypes = 'ident' | 'at-keyword' | 'hash' | 'id-hash' | 'string' | 'number' | 'percentage' | 'dimension';
type TokenVisitors = {
[Name in VisitableTokenTypes]?: (token: FindByType<Token, Name>) => TokenReturnValue;
}
type FunctionVisitor = (fn: Function) => TokenReturnValue;
type EnvironmentVariableVisitor = (env: EnvironmentVariable) => TokenReturnValue;
type EnvironmentVariableVisitors = {
[name: string]: EnvironmentVariableVisitor
};
export interface Visitor<C extends CustomAtRules> {
StyleSheet?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
StyleSheetExit?(stylesheet: StyleSheet): StyleSheet<ReturnedDeclaration, ReturnedMediaQuery> | void;
Rule?: RuleVisitor | RuleVisitors<C>;
RuleExit?: RuleVisitor | RuleVisitors<C>;
Declaration?: DeclarationVisitor | DeclarationVisitors;
DeclarationExit?: DeclarationVisitor | DeclarationVisitors;
Url?(url: Url): Url | void;
Color?(color: CssColor): CssColor | void;
Image?(image: Image): Image | void;
ImageExit?(image: Image): Image | void;
Length?(length: LengthValue): LengthValue | void;
Angle?(angle: Angle): Angle | void;
Ratio?(ratio: Ratio): Ratio | void;
Resolution?(resolution: Resolution): Resolution | void;
Time?(time: Time): Time | void;
CustomIdent?(ident: string): string | void;
DashedIdent?(ident: string): string | void;
MediaQuery?(query: MediaQuery): ReturnedMediaQuery | ReturnedMediaQuery[] | void;
MediaQueryExit?(query: MediaQuery): ReturnedMediaQuery | ReturnedMediaQuery[] | void;
SupportsCondition?(condition: SupportsCondition): SupportsCondition;
SupportsConditionExit?(condition: SupportsCondition): SupportsCondition;
Selector?(selector: Selector): Selector | Selector[] | void;
Token?: TokenVisitor | TokenVisitors;
Function?: FunctionVisitor | { [name: string]: FunctionVisitor };
FunctionExit?: FunctionVisitor | { [name: string]: FunctionVisitor };
Variable?(variable: Variable): TokenReturnValue;
VariableExit?(variable: Variable): TokenReturnValue;
EnvironmentVariable?: EnvironmentVariableVisitor | EnvironmentVariableVisitors;
EnvironmentVariableExit?: EnvironmentVariableVisitor | EnvironmentVariableVisitors;
}
export type VisitorDependency = FileDependency | GlobDependency;
export interface VisitorOptions {
addDependency: (dep: VisitorDependency) => void
}
export type VisitorFunction<C extends CustomAtRules> = (options: VisitorOptions) => Visitor<C>;
export interface CustomAtRules {
[name: string]: CustomAtRuleDefinition
}
export interface CustomAtRuleDefinition {
/**
* Defines the syntax for a custom at-rule prelude. The value should be a
* CSS [syntax string](https://drafts.css-houdini.org/css-properties-values-api/#syntax-strings)
* representing the types of values that are accepted. This property may be omitted or
* set to null to indicate that no prelude is accepted.
*/
prelude?: SyntaxString | null,
/**
* Defines the type of body contained within the at-rule block.
* - declaration-list: A CSS declaration list, as in a style rule.
* - rule-list: A list of CSS rules, as supported within a non-nested
* at-rule such as `@media` or `@supports`.
* - style-block: Both a declaration list and rule list, as accepted within
* a nested at-rule within a style rule (e.g. `@media` inside a style rule
* with directly nested declarations).
*/
body?: 'declaration-list' | 'rule-list' | 'style-block' | null
}
export interface DependencyOptions {
/** Whether to preserve `@import` rules rather than removing them. */
preserveImports?: boolean
}
export type BundleOptions<C extends CustomAtRules> = Omit<TransformOptions<C>, 'code'>;
export interface BundleAsyncOptions<C extends CustomAtRules> extends BundleOptions<C> {
resolver?: Resolver;
}
type MaybePromise<T> = T | Promise<T>;
/** Custom resolver to use when loading CSS files. */
export interface Resolver {
/** Read the given file and return its contents as a string. */
read?: (file: string) => string | Promise<string>;
/**
* Resolve the given CSS import specifier from the provided originating file to a
* path which gets passed to `read()`.
*/
resolve?: (specifier: string, originatingFile: string) => MaybePromise<string | { external: string }>;
}
export interface Drafts {
/** Whether to enable @custom-media rules. */
customMedia?: boolean
/**
* Whether to enable the scroll navigation controls.
* https://drafts.csswg.org/css-overflow-5/#scroll-navigation
*/
scrollNavigationControls?: boolean
}
export interface NonStandard {
/** Whether to enable the non-standard >>> and /deep/ selector combinators used by Angular and Vue. */
deepSelectorCombinator?: boolean
}
export interface PseudoClasses {
hover?: string,
active?: string,
focus?: string,
focusVisible?: string,
focusWithin?: string
}
export interface TransformResult {
/** The transformed code. */
code: Uint8Array,
/** The generated source map, if enabled. */
map: Uint8Array | void,
/** CSS module exports, if enabled. */
exports: CSSModuleExports | void,
/** CSS module references, if `dashedIdents` is enabled. */
references: CSSModuleReferences,
/** `@import` and `url()` dependencies, if enabled. */
dependencies: Dependency[] | void,
/** Warnings that occurred during compilation. */
warnings: Warning[]
}
export interface Warning {
message: string,
type: string,
value?: any,
loc: ErrorLocation
}
export interface CSSModulesConfig {
/** The pattern to use when renaming class names and other identifiers. Default is `[hash]_[local]`. */
pattern?: string,
/** Whether to rename dashed identifiers, e.g. custom properties. */
dashedIdents?: boolean,
/** Whether to enable hashing for `@keyframes`. */
animation?: boolean,
/** Whether to enable hashing for CSS grid identifiers. */
grid?: boolean,
/** Whether to enable hashing for `@container` names. */
container?: boolean,
/** Whether to enable hashing for custom identifiers. */
customIdents?: boolean,
/** Whether to require at least one class or id selector in each rule. */
pure?: boolean
}
export type CSSModuleExports = {
/** Maps exported (i.e. original) names to local names. */
[name: string]: CSSModuleExport
};
export interface CSSModuleExport {
/** The local (compiled) name for this export. */
name: string,
/** Whether the export is referenced in this file. */
isReferenced: boolean,
/** Other names that are composed by this export. */
composes: CSSModuleReference[]
}
export type CSSModuleReferences = {
/** Maps placeholder names to references. */
[name: string]: DependencyCSSModuleReference,
};
export type CSSModuleReference = LocalCSSModuleReference | GlobalCSSModuleReference | DependencyCSSModuleReference;
export interface LocalCSSModuleReference {
type: 'local',
/** The local (compiled) name for the reference. */
name: string,
}
export interface GlobalCSSModuleReference {
type: 'global',
/** The referenced global name. */
name: string,
}
export interface DependencyCSSModuleReference {
type: 'dependency',
/** The name to reference within the dependency. */
name: string,
/** The dependency specifier for the referenced file. */
specifier: string
}
export type Dependency = ImportDependency | UrlDependency | FileDependency | GlobDependency;
export interface ImportDependency {
type: 'import',
/** The url of the `@import` dependency. */
url: string,
/** The media query for the `@import` rule. */
media: string | null,
/** The `supports()` query for the `@import` rule. */
supports: string | null,
/** The source location where the `@import` rule was found. */
loc: SourceLocation,
/** The placeholder that the import was replaced with. */
placeholder: string
}
export interface UrlDependency {
type: 'url',
/** The url of the dependency. */
url: string,
/** The source location where the `url()` was found. */
loc: SourceLocation,
/** The placeholder that the url was replaced with. */
placeholder: string
}
export interface FileDependency {
type: 'file',
filePath: string
}
export interface GlobDependency {
type: 'glob',
glob: string
}
export interface SourceLocation {
/** The file path in which the dependency exists. */
filePath: string,
/** The start location of the dependency. */
start: Location,
/** The end location (inclusive) of the dependency. */
end: Location
}
export interface Location {
/** The line number (1-based). */
line: number,
/** The column number (0-based). */
column: number
}
export interface ErrorLocation extends Location {
filename: string
}
/**
* Compiles a CSS file, including optionally minifying and lowering syntax to the given
* targets. A source map may also be generated, but this is not enabled by default.
*/
export declare function transform<C extends CustomAtRules>(options: TransformOptions<C>): TransformResult;
export interface TransformAttributeOptions {
/** The filename in which the style attribute appeared. Used for error messages and dependencies. */
filename?: string,
/** The source code to transform. */
code: Uint8Array,
/** Whether to enable minification. */
minify?: boolean,
/** The browser targets for the generated code. */
targets?: Targets,
/**
* Whether to analyze `url()` dependencies.
* When enabled, `url()` dependencies are replaced with hashed placeholders
* that can be replaced with the final urls later (after bundling).
* Dependencies are returned as part of the result.
*/
analyzeDependencies?: boolean,
/**
* Whether to ignore invalid rules and declarations rather than erroring.
* When enabled, warnings are returned, and the invalid rule or declaration is
* omitted from the output code.
*/
errorRecovery?: boolean,
/**
* An AST visitor object. This allows custom transforms or analysis to be implemented in JavaScript.
* Multiple visitors can be composed into one using the `composeVisitors` function.
* For optimal performance, visitors should be as specific as possible about what types of values
* they care about so that JavaScript has to be called as little as possible.
*/
visitor?: Visitor<never> | VisitorFunction<never>
}
export interface TransformAttributeResult {
/** The transformed code. */
code: Uint8Array,
/** `@import` and `url()` dependencies, if enabled. */
dependencies: Dependency[] | void,
/** Warnings that occurred during compilation. */
warnings: Warning[]
}
/**
* Compiles a single CSS declaration list, such as an inline style attribute in HTML.
*/
export declare function transformStyleAttribute(options: TransformAttributeOptions): TransformAttributeResult;
/**
* Converts a browserslist result into targets that can be passed to lightningcss.
* @param browserslist the result of calling `browserslist`
*/
export declare function browserslistToTargets(browserslist: string[]): Targets;
/**
* Bundles a CSS file and its dependencies, inlining @import rules.
*/
export declare function bundle<C extends CustomAtRules>(options: BundleOptions<C>): TransformResult;
/**
* Bundles a CSS file and its dependencies asynchronously, inlining @import rules.
*/
export declare function bundleAsync<C extends CustomAtRules>(options: BundleAsyncOptions<C>): Promise<TransformResult>;
/**
* Composes multiple visitor objects into a single one.
*/
export declare function composeVisitors<C extends CustomAtRules>(visitors: (Visitor<C> | VisitorFunction<C>)[]): Visitor<C> | VisitorFunction<C>;

View File

@@ -0,0 +1,57 @@
var assert = require("assert");
var indexStringify = require('../index');
var jsonStableStringify = require('json-stable-stringify');
var fasterStableStringify = require('faster-stable-stringify');
var validateLibOutput = require('./validate');
var data = require("../fixtures/index").input;
var dataLength = JSON.stringify(data).length;
suite("libs", function() {
var minSamples = 120;
// This needs to be true before anything else
console.log('Checking index validity...');
validateLibOutput(indexStringify);
console.log('Checking index validity success');
benchmark('native', function () {
var result = JSON.stringify(data);
assert.equal(result.length, dataLength);
}, {
minSamples: minSamples
});
benchmark('index', function () {
var result = indexStringify(data);
assert.equal(result.length, dataLength);
}, {
minSamples: minSamples
});
benchmark('json-stable-stringify', function () {
var result = jsonStableStringify(data);
assert.equal(result.length, dataLength);
}, {
minSamples: minSamples
});
benchmark('faster-stable-stringify', function () {
var result = fasterStableStringify(data);
assert.equal(result.length, dataLength);
}, {
minSamples: minSamples
});
}, {
onComplete: function() {
var namesFastest = this
.filter(function(bench) {
return bench.name !== 'native';
})
.filter('fastest')
.map('name');
assert.notEqual(namesFastest.indexOf('index'), -1, "index should be among the fastest");
}
});

View File

@@ -0,0 +1,35 @@
{
"for + if": {
"name": "for + if",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "itar-short",
"hz": 203203.20404721753,
"success": true,
"fastest": false,
"rme": 0.031725599593069885,
"rhz": 0.8894144359714051,
"sampleSize": 201
},
"while + if": {
"name": "while + if",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "itar-short",
"hz": 228468.5247156822,
"success": true,
"fastest": true,
"rme": 0.012472328119036293,
"rhz": 1,
"sampleSize": 211
},
"array join": {
"name": "array join",
"browser": "Mobile Safari 10.0.0 (iOS 10.3.0)",
"suite": "itar-short",
"hz": 227457.50626324932,
"success": true,
"fastest": false,
"rme": 0.02322443731392338,
"rhz": 0.9955748020271455,
"sampleSize": 206
}
}

View File

@@ -0,0 +1,47 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all
* of the provided Promises resolve or reject.
* @param values An array of Promises.
* @returns A new Promise.
*/
allSettled<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>; }>;
/**
* Creates a Promise that is resolved with an array of results when all
* of the provided Promises resolve or reject.
* @param values An array of Promises.
* @returns A new Promise.
*/
allSettled<T>(values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]>;
}

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSModuleScope = void 0;
const ScopeBase_1 = require("./ScopeBase");
const ScopeType_1 = require("./ScopeType");
class TSModuleScope extends ScopeBase_1.ScopeBase {
constructor(scopeManager, upperScope, block) {
super(scopeManager, ScopeType_1.ScopeType.tsModule, upperScope, block, false);
}
}
exports.TSModuleScope = TSModuleScope;

View File

@@ -0,0 +1,15 @@
import type { TSESTree } from '@typescript-eslint/utils';
import type { InferMessageIdsTypeFromRule, InferOptionsTypeFromRule } from '../util';
declare const baseRule: import("@typescript-eslint/utils/ts-eslint").RuleModule<"initialized" | "notInitialized", ["always" | "never", ({
ignoreForLoopInit?: boolean;
} | undefined)?], unknown, {
'VariableDeclaration:exit'(node: TSESTree.VariableDeclaration): void;
}>;
export type Options = InferOptionsTypeFromRule<typeof baseRule>;
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"initialized" | "notInitialized", ["always" | "never", ({
ignoreForLoopInit?: boolean;
} | undefined)?], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;