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 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/api/sync/types.ts"],"names":[],"mappings":""}

View File

@@ -0,0 +1,177 @@
/**
* Compiler-emitted module-graph delta — pure topology (static + dynamic edges).
* `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.
* `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.
* @typedef {{ ids: string[], localCount: number, edges: number[][], dynamicEdges?: number[][] }} ModuleGraphDelta
* @typedef {{ createModuleHotContext(moduleId: string): any, onModuleCacheRemoval(moduleId: string): void }} DevRuntimeHooks
*/
export class MissingFactoryError {
/**
* @param {string} id
*/
constructor(id: string);
id: string;
}
export class DevRuntime {
/**
* @param {string} clientId
*/
constructor(clientId: string);
/**
* Client ID generated at runtime initialization, used for lazy compilation requests.
* @type {string}
*/
clientId: string;
/**
* Static import edges from `registerGraph` — entries persist across `removeModuleCache`
* and change only by replacement from a newer payload (last write wins).
* @type {Map<string, { edges: string[] }>}
*/
staticImports: Map<string, {
edges: string[];
}>;
/**
* Reverse index over the static imports.
* @type {Map<string, Set<string>>}
*/
importers: Map<string, Set<string>>;
/**
* Dynamic `import()` edges from `registerGraph`, keyed by importer — mirror of
* `staticImports` for the dynamic reverse index.
* @type {Map<string, { edges: string[] }>}
*/
dynamicImports: Map<string, {
edges: string[];
}>;
/**
* Reverse index over the dynamic imports.
* @type {Map<string, Set<string>>}
*/
dynamicImporters: Map<string, Set<string>>;
/**
* The module cache. Membership means "this module's side effects ran in this tab" —
* registration is emitted ahead of every module body, and nothing un-registers on
* unwind, so a factory that throws mid-body stays registered. A `Map` rather than a
* plain object: HMR eviction deletes entries, and a `delete` on an object drops V8
* into dictionary mode, taxing every later lookup on the hottest read path.
* @type {Map<string, Module>}
*/
moduleCache: Map<string, Module>;
/**
* Re-runnable factories from HMR patches and lazy chunks. The initial bundle stays
* scope-hoisted and contributes none.
* @type {Map<string, { kind: 'esm' | 'cjs', fn: (id: string) => void }>}
*/
factories: Map<string, {
kind: "esm" | "cjs";
fn: (id: string) => void;
}>;
/**
* Installed by the dev client at boot. The runtime is a store + executor and makes
* no HMR decisions; accepting, disposing, and reloading live behind these hooks.
* @type {DevRuntimeHooks | null}
*/
hooks: DevRuntimeHooks | null;
/**
* @param {ModuleGraphDelta} delta
*/
registerGraph(delta: ModuleGraphDelta): void;
/**
* @param {string} id
* @param {'esm' | 'cjs'} kind
* @param {(id: string) => void} fn
*/
registerFactory(id: string, kind: "esm" | "cjs", fn: (id: string) => void): void;
/**
* @param {string} id
* @param {{ exports: any }} exportsHolder
*/
registerModule(id: string, exportsHolder: {
exports: any;
}): void;
/**
* @param {string} id
* @returns {string[]}
*/
getImporters(id: string): string[];
/**
* @param {string} id
*/
isExecuted(id: string): any;
/**
* @param {string} id
*/
hasFactory(id: string): any;
/**
* Module-cache delete only — static imports and factories persist. Removal is what
* re-arms a cache-gated factory for `initModule`.
* @param {string} id
*/
removeModuleCache(id: string): void;
/**
* The one re-execution gate: registered → return the live exports; otherwise run the
* mapped factory (which registers itself first, then runs the body).
* @param {string} id
*/
initModule(id: string): any;
/**
* @param {string} id
*/
loadExports(id: string): any;
/**
* @param {string} moduleId
*/
createModuleHotContext(moduleId: string): any;
/** @internal */
__toESM: any;
/** @internal */
__toCommonJS: any;
/** @internal */
__exportAll: any;
/**
* @param {boolean} [isNodeMode]
* @returns {(mod: any) => any}
* @internal
*/
__toDynamicImportESM: (isNodeMode?: boolean) => (mod: any) => any;
/** @internal */
__reExport: any;
}
/**
* Compiler-emitted module-graph delta — pure topology (static + dynamic edges).
* `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.
* `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.
*/
export type ModuleGraphDelta = {
ids: string[];
localCount: number;
edges: number[][];
dynamicEdges?: number[][];
};
/**
* Compiler-emitted module-graph delta — pure topology (static + dynamic edges).
* `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.
* `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.
*/
export type DevRuntimeHooks = {
createModuleHotContext(moduleId: string): any;
onModuleCacheRemoval(moduleId: string): void;
};
declare class Module {
/**
* @param {string} id
*/
constructor(id: string);
/**
* @type {{ exports: any }}
*/
exportsHolder: {
exports: any;
};
/**
* @type {string}
*/
id: string;
get exports(): any;
}
export {};

View File

@@ -0,0 +1,227 @@
/**
* @fileoverview Rule that warns when identifier names that are
* specified in the configuration are used.
* @author Keith Cirkel (http://keithcirkel.co.uk)
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether the given node represents assignment target in a normal assignment or destructuring.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is assignment target.
*/
function isAssignmentTarget(node) {
const parent = node.parent;
return (
// normal assignment
(parent.type === "AssignmentExpression" && parent.left === node) ||
// destructuring
parent.type === "ArrayPattern" ||
parent.type === "RestElement" ||
(parent.type === "Property" &&
parent.value === node &&
parent.parent.type === "ObjectPattern") ||
(parent.type === "AssignmentPattern" && parent.left === node)
);
}
/**
* Checks whether the given node represents an imported name that is renamed in the same import/export specifier.
*
* Examples:
* import { a as b } from 'mod'; // node `a` is renamed import
* export { a as b } from 'mod'; // node `a` is renamed import
* @param {ASTNode} node `Identifier` node to check.
* @returns {boolean} `true` if the node is a renamed import.
*/
function isRenamedImport(node) {
const parent = node.parent;
return (
(parent.type === "ImportSpecifier" &&
parent.imported !== parent.local &&
parent.imported === node) ||
(parent.type === "ExportSpecifier" &&
parent.parent.source && // re-export
parent.local !== parent.exported &&
parent.local === node)
);
}
/**
* Checks whether the given node is an ObjectPattern destructuring.
*
* Examples:
* const { a : b } = foo;
* @param {ASTNode} node `Identifier` node to check.
* @returns {boolean} `true` if the node is in an ObjectPattern destructuring.
*/
function isPropertyNameInDestructuring(node) {
const parent = node.parent;
return (
!parent.computed &&
parent.type === "Property" &&
parent.parent.type === "ObjectPattern" &&
parent.key === node
);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [],
docs: {
description: "Disallow specified identifiers",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/id-denylist",
},
schema: {
type: "array",
items: {
type: "string",
},
uniqueItems: true,
},
messages: {
restricted: "Identifier '{{name}}' is restricted.",
restrictedPrivate: "Identifier '#{{name}}' is restricted.",
},
},
create(context) {
const denyList = new Set(context.options);
const reportedNodes = new Set();
const sourceCode = context.sourceCode;
let globalScope;
/**
* Checks whether the given name is restricted.
* @param {string} name The name to check.
* @returns {boolean} `true` if the name is restricted.
* @private
*/
function isRestricted(name) {
return denyList.has(name);
}
/**
* Checks whether the given node represents a reference to a global variable that is not declared in the source code.
* These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
* @param {ASTNode} node `Identifier` node to check.
* @returns {boolean} `true` if the node is a reference to a global variable.
*/
function isReferenceToGlobalVariable(node) {
const variable = globalScope.set.get(node.name);
return (
variable &&
variable.defs.length === 0 &&
variable.references.some(ref => ref.identifier === node)
);
}
/**
* Determines whether the given node should be checked.
* @param {ASTNode} node `Identifier` node.
* @returns {boolean} `true` if the node should be checked.
*/
function shouldCheck(node) {
// Import attributes are defined by environments, so naming conventions shouldn't apply to them
if (astUtils.isImportAttributeKey(node)) {
return false;
}
const parent = node.parent;
if (parent.type === "MetaProperty") {
return false;
}
/*
* Member access has special rules for checking property names.
* Read access to a property with a restricted name is allowed, because it can be on an object that user has no control over.
* Write access isn't allowed, because it potentially creates a new property with a restricted name.
*/
if (
parent.type === "MemberExpression" &&
parent.property === node &&
!parent.computed
) {
return isAssignmentTarget(parent);
}
return (
parent.type !== "CallExpression" &&
parent.type !== "NewExpression" &&
!isRenamedImport(node) &&
!isPropertyNameInDestructuring(node) &&
!isReferenceToGlobalVariable(node)
);
}
/**
* Reports an AST node as a rule violation.
* @param {ASTNode} node The node to report.
* @returns {void}
* @private
*/
function report(node) {
/*
* We used the range instead of the node because it's possible
* for the same identifier to be represented by two different
* nodes, with the most clear example being shorthand properties:
* { foo }
* In this case, "foo" is represented by one node for the name
* and one for the value. The only way to know they are the same
* is to look at the range.
*/
if (!reportedNodes.has(node.range.toString())) {
const isPrivate = node.type === "PrivateIdentifier";
context.report({
node,
messageId: isPrivate ? "restrictedPrivate" : "restricted",
data: {
name: node.name,
},
});
reportedNodes.add(node.range.toString());
}
}
return {
Program(node) {
globalScope = sourceCode.getScope(node);
},
[["Identifier", "PrivateIdentifier"]](node) {
if (isRestricted(node.name) && shouldCheck(node)) {
report(node);
}
},
};
},
};

View File

@@ -0,0 +1,6 @@
function _getPrototypeOf(t) {
return module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
return t.__proto__ || Object.getPrototypeOf(t);
}, module.exports.__esModule = true, module.exports["default"] = module.exports, _getPrototypeOf(t);
}
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015-2017 Evgeny Poberezkin
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,22 @@
/*! *****************************************************************************
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,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference lib="es2025" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />

View File

@@ -0,0 +1,4 @@
function _is_native_function(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
export { _is_native_function as _ };

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Matteo Collina and Undici 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.

View File

@@ -0,0 +1,70 @@
// Zod 3 compat layer
import * as core from "../core/index.js";
import type { ZodType } from "./schemas.js";
export type {
/** @deprecated Use `z.output<T>` instead. */
output as TypeOf,
/** @deprecated Use `z.output<T>` instead. */
output as Infer,
/** @deprecated Use `z.core.$$ZodFirstPartyTypes` instead */
$ZodTypes as ZodFirstPartySchemaTypes,
} from "../core/index.js";
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
export const ZodIssueCode = {
invalid_type: "invalid_type",
too_big: "too_big",
too_small: "too_small",
invalid_format: "invalid_format",
not_multiple_of: "not_multiple_of",
unrecognized_keys: "unrecognized_keys",
invalid_union: "invalid_union",
invalid_key: "invalid_key",
invalid_element: "invalid_element",
invalid_value: "invalid_value",
custom: "custom",
} as const;
/** @deprecated Use `z.$ZodFlattenedError` */
export type inferFlattenedErrors<T extends core.$ZodType, U = string> = core.$ZodFlattenedError<core.output<T>, U>;
/** @deprecated Use `z.$ZodFormattedError` */
export type inferFormattedError<T extends core.$ZodType<any, any>, U = string> = core.$ZodFormattedError<
core.output<T>,
U
>;
/** Use `z.$brand` instead */
export type BRAND<T extends string | number | symbol = string | number | symbol> = {
[core.$brand]: { [k in T]: true };
};
export { $brand, config } from "../core/index.js";
/** @deprecated Use `z.config(params)` instead. */
export function setErrorMap(map: core.$ZodErrorMap): void {
core.config({
customError: map,
});
}
/** @deprecated Use `z.config()` instead. */
export function getErrorMap(): core.$ZodErrorMap<core.$ZodIssue> | undefined {
return core.config().customError;
}
export type {
/** @deprecated Use z.ZodType (without generics) instead. */
ZodType as ZodTypeAny,
/** @deprecated Use `z.ZodType` */
ZodType as ZodSchema,
/** @deprecated Use `z.ZodType` */
ZodType as Schema,
};
/** Included for Zod 3 compatibility */
export type ZodRawShape = core.$ZodShape;
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
export enum ZodFirstPartyTypeKind {}

View File

@@ -0,0 +1,13 @@
"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.es2019_object = void 0;
const base_config_1 = require("./base-config");
const es2015_iterable_1 = require("./es2015.iterable");
exports.es2019_object = {
libs: [es2015_iterable_1.es2015_iterable],
variables: [['ObjectConstructor', base_config_1.TYPE]],
};

View File

@@ -0,0 +1,35 @@
/*! *****************************************************************************
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 ArrayConstructor {
/**
* Creates an array from an async iterator or iterable object.
* @param iterableOrArrayLike An async iterator or array-like object to convert to an array.
*/
fromAsync<T>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T | PromiseLike<T>> | ArrayLike<T | PromiseLike<T>>): Promise<T[]>;
/**
* Creates an array from an async iterator or iterable object.
*
* @param iterableOrArrayLike An async iterator or array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of itarableOrArrayLike.
* Each return value is awaited before being added to result array.
* @param thisArg Value of 'this' used when executing mapfn.
*/
fromAsync<T, U>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>, mapFn: (value: Awaited<T>) => U, thisArg?: any): Promise<Awaited<U>[]>;
}

View File

@@ -0,0 +1,13 @@
/**
* RIPEMD-160 legacy hash function.
* https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
* https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
* @module
* @deprecated
*/
import { RIPEMD160 as RIPEMD160n, ripemd160 as ripemd160n } from "./legacy.js";
/** @deprecated Use import from `noble/hashes/legacy` module */
export const RIPEMD160 = RIPEMD160n;
/** @deprecated Use import from `noble/hashes/legacy` module */
export const ripemd160 = ripemd160n;
//# sourceMappingURL=ripemd160.js.map

View File

@@ -0,0 +1,65 @@
import type { ProjectServiceOptions } from '@typescript-eslint/types';
import type * as ts from 'typescript/lib/tsserverlibrary';
/**
* Shortcut type to refer to TypeScript's server ProjectService.
*/
export type TypeScriptProjectService = ts.server.ProjectService;
/**
* A created Project Service instance, as well as metadata on its creation.
*/
export interface ProjectServiceAndMetadata {
/**
* Files allowed to be loaded from the default project, if any were specified.
*/
allowDefaultProject: string[] | undefined;
/**
* The performance.now() timestamp of the last reload of the project service.
*/
lastReloadTimestamp: number;
/**
* The maximum number of files that can be matched by the default project.
*/
maximumDefaultProjectFileMatchCount: number;
/**
* The created TypeScript Project Service instance.
*/
service: TypeScriptProjectService;
}
/**
* Settings to create a new Project Service instance with {@link createProjectService}.
*/
export interface CreateProjectServiceSettings {
/**
* Granular options to configure the project service.
*/
options?: ProjectServiceOptions;
/**
* How aggressively (and slowly) to parse JSDoc comments.
*/
jsDocParsingMode?: ts.JSDocParsingMode;
/**
* Root directory for the tsconfig.json file, if not the current directory.
*/
tsconfigRootDir?: string;
/**
* Custom project service host.
*
* @default `ts.sys` with stub watchers
*/
host?: Partial<ts.server.ServerHost>;
}
/**
* Creates a new Project Service instance, as well as metadata on its creation.
* @param settings Settings to create a new Project Service instance.
* @returns A new Project Service instance, as well as metadata on its creation.
* @example
* ```ts
* import { createProjectService } from '@typescript-eslint/project-service';
*
* const { service } = createProjectService();
*
* service.openClientFile('index.ts');
* ```
*/
export declare function createProjectService({ host, jsDocParsingMode, options: optionsRaw, tsconfigRootDir, }?: CreateProjectServiceSettings): ProjectServiceAndMetadata;
export { type ProjectServiceOptions } from '@typescript-eslint/types';

View File

@@ -0,0 +1,12 @@
import type { TSESLint } from '@typescript-eslint/utils';
export type MessageIds = 'redeclared' | 'redeclaredAsBuiltin' | 'redeclaredBySyntax';
export type Options = [
{
builtinGlobals?: boolean;
ignoreDeclarationMerge?: boolean;
}
];
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,8 @@
import type * as ts from 'typescript';
import type { ParseSettings } from '../parseSettings';
import type { ASTAndDefiniteProgram } from './shared';
/**
* @param parseSettings Internal settings for parsing the file
* @returns If found, the source file corresponding to the code and the containing program
*/
export declare function createProjectProgram(parseSettings: ParseSettings, programsForProjects: readonly ts.Program[]): ASTAndDefiniteProgram;

View File

@@ -0,0 +1,59 @@
# ms
![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

View File

@@ -0,0 +1,14 @@
var setPrototypeOf = require("./setPrototypeOf.js");
function _inherits(t, e) {
if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
t.prototype = Object.create(e && e.prototype, {
constructor: {
value: t,
writable: !0,
configurable: !0
}
}), Object.defineProperty(t, "prototype", {
writable: !1
}), e && setPrototypeOf(t, e);
}
module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,20 @@
Copyright (c) 2023 Solana Labs, Inc
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,139 @@
"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;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const tsutils = __importStar(require("ts-api-utils"));
const ts = __importStar(require("typescript"));
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('dot-notation');
const defaultOptions = [
{
allowIndexSignaturePropertyAccess: false,
allowKeywords: true,
allowPattern: '',
allowPrivateClassPropertyAccess: false,
allowProtectedClassPropertyAccess: false,
},
];
exports.default = (0, util_1.createRule)({
name: 'dot-notation',
meta: {
type: 'suggestion',
defaultOptions,
docs: {
description: 'Enforce dot notation whenever possible',
extendsBaseRule: true,
frozen: true,
recommended: 'stylistic',
requiresTypeChecking: true,
},
fixable: baseRule.meta.fixable,
hasSuggestions: baseRule.meta.hasSuggestions,
messages: baseRule.meta.messages,
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowIndexSignaturePropertyAccess: {
type: 'boolean',
description: 'Whether to allow accessing properties matching an index signature with array notation.',
},
allowKeywords: {
type: 'boolean',
description: 'Whether to allow keywords such as ["class"]`.',
},
allowPattern: {
type: 'string',
description: 'Regular expression of names to allow.',
},
allowPrivateClassPropertyAccess: {
type: 'boolean',
description: 'Whether to allow accessing class members marked as `private` with array notation.',
},
allowProtectedClassPropertyAccess: {
type: 'boolean',
description: 'Whether to allow accessing class members marked as `protected` with array notation.',
},
},
},
],
},
defaultOptions,
create(context, [options]) {
const rules = baseRule.create(context);
const services = (0, util_1.getParserServices)(context);
const checker = services.program.getTypeChecker();
const allowPrivateClassPropertyAccess = options.allowPrivateClassPropertyAccess;
const allowProtectedClassPropertyAccess = options.allowProtectedClassPropertyAccess;
const allowIndexSignaturePropertyAccess = (options.allowIndexSignaturePropertyAccess ?? false) ||
tsutils.isCompilerOptionEnabled(services.program.getCompilerOptions(), 'noPropertyAccessFromIndexSignature');
return {
MemberExpression(node) {
if ((allowPrivateClassPropertyAccess ||
allowProtectedClassPropertyAccess ||
allowIndexSignaturePropertyAccess) &&
node.computed) {
// for perf reasons - only fetch symbols if we have to
const propertySymbol = services.getSymbolAtLocation(node.property) ??
services
.getTypeAtLocation(node.object)
.getNonNullableType()
.getProperties()
.find(propertySymbol => node.property.type === utils_1.AST_NODE_TYPES.Literal &&
propertySymbol.escapedName === node.property.value);
const modifierKind = (0, util_1.getModifiers)(propertySymbol?.getDeclarations()?.[0])?.[0].kind;
if ((allowPrivateClassPropertyAccess &&
modifierKind === ts.SyntaxKind.PrivateKeyword) ||
(allowProtectedClassPropertyAccess &&
modifierKind === ts.SyntaxKind.ProtectedKeyword)) {
return;
}
if (propertySymbol == null && allowIndexSignaturePropertyAccess) {
const objectType = services
.getTypeAtLocation(node.object)
.getNonNullableType();
const indexInfos = checker.getIndexInfosOfType(objectType);
if (indexInfos.some(info => tsutils.isTypeFlagSet(info.keyType, ts.TypeFlags.StringLike))) {
return;
}
}
}
rules.MemberExpression(node);
},
};
},
});

View File

@@ -0,0 +1,27 @@
extends: eslint:recommended
env:
node: true
browser: true
rules:
block-scoped-var: 2
complexity: [2, 13]
curly: [2, multi-or-nest, consistent]
dot-location: [2, property]
dot-notation: 2
indent: [2, 2, SwitchCase: 1]
linebreak-style: [2, unix]
new-cap: 2
no-console: [2, allow: [warn, error]]
no-else-return: 2
no-eq-null: 2
no-fallthrough: 2
no-invalid-this: 2
no-return-assign: 2
no-shadow: 1
no-trailing-spaces: 2
no-use-before-define: [2, nofunc]
quotes: [2, single, avoid-escape]
semi: [2, always]
strict: [2, global]
valid-jsdoc: [2, requireReturn: false]
no-control-regex: 0

View File

@@ -0,0 +1,43 @@
import { expect, test } from "vitest";
import * as z from "zod/mini";
declare module "zod/v4/core" {
interface $ZodType {
/** @deprecated */
_core(): string;
}
}
test("prototype extension", () => {
z.core.$ZodType.prototype._core = function () {
return "_core";
};
// should pass
const result = z.string()._core();
expect(result).toBe("_core");
// expectTypeOf<typeof result>().toEqualTypeOf<string>();
// clean up
z.ZodMiniType.prototype._core = undefined;
});
declare module "zod/v4/mini" {
interface ZodMiniType {
/** @deprecated */
_mini(): string;
}
}
test("prototype extension", () => {
z.ZodMiniType.prototype._mini = function () {
return "_mini";
};
// should pass
const result = z.string()._mini();
expect(result).toBe("_mini");
// clean up
z.ZodMiniType.prototype._mini = undefined;
});

View File

@@ -0,0 +1,74 @@
"use strict";
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Semaphore = void 0;
const ral_1 = __importDefault(require("./ral"));
class Semaphore {
_capacity;
_active;
_waiting;
constructor(capacity = 1) {
if (capacity <= 0) {
throw new Error('Capacity must be greater than 0');
}
this._capacity = capacity;
this._active = 0;
this._waiting = [];
}
lock(thunk) {
return new Promise((resolve, reject) => {
this._waiting.push({ thunk, resolve, reject });
this.runNext();
});
}
get active() {
return this._active;
}
runNext() {
if (this._waiting.length === 0 || this._active === this._capacity) {
return;
}
(0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
}
doRunNext() {
if (this._waiting.length === 0 || this._active === this._capacity) {
return;
}
const next = this._waiting.shift();
this._active++;
if (this._active > this._capacity) {
throw new Error(`Too many thunks active`);
}
try {
const result = next.thunk();
if (result instanceof Promise) {
result.then((value) => {
this._active--;
next.resolve(value);
this.runNext();
}, (err) => {
this._active--;
next.reject(err);
this.runNext();
});
}
else {
this._active--;
next.resolve(result);
this.runNext();
}
}
catch (err) {
this._active--;
next.reject(err);
this.runNext();
}
}
}
exports.Semaphore = Semaphore;

View File

@@ -0,0 +1,4 @@
function _read_only_error(name) {
throw new TypeError("\"" + name + "\" is read-only");
}
export { _read_only_error as _ };

View File

@@ -0,0 +1,181 @@
/**
* @fileoverview Rule to disallow loops with a body that allows only one iteration
* @author Milos Djermanovic
*/
"use strict";
const { isAnySegmentReachable } = require("./utils/code-path-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const allLoopTypes = [
"WhileStatement",
"DoWhileStatement",
"ForStatement",
"ForInStatement",
"ForOfStatement",
];
/**
* Determines whether the given node is the first node in the code path to which a loop statement
* 'loops' for the next iteration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a looping target.
*/
function isLoopingTarget(node) {
const parent = node.parent;
if (parent) {
switch (parent.type) {
case "WhileStatement":
return node === parent.test;
case "DoWhileStatement":
return node === parent.body;
case "ForStatement":
return node === (parent.update || parent.test || parent.body);
case "ForInStatement":
case "ForOfStatement":
return node === parent.left;
// no default
}
}
return false;
}
/**
* Creates an array with elements from the first given array that are not included in the second given array.
* @param {Array} arrA The array to compare from.
* @param {Array} arrB The array to compare against.
* @returns {Array} a new array that represents `arrA \ arrB`.
*/
function getDifference(arrA, arrB) {
return arrA.filter(a => !arrB.includes(a));
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [{ ignore: [] }],
docs: {
description:
"Disallow loops with a body that allows only one iteration",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-unreachable-loop",
},
schema: [
{
type: "object",
properties: {
ignore: {
type: "array",
items: {
enum: allLoopTypes,
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
invalid: "Invalid loop. Its body allows only one iteration.",
},
},
create(context) {
const [{ ignore: ignoredLoopTypes }] = context.options;
const loopTypesToCheck = getDifference(allLoopTypes, ignoredLoopTypes);
const loopSelector = loopTypesToCheck.join(",");
if (!loopSelector) {
return {};
}
const loopsByTargetSegments = new Map();
const loopsToReport = new Set();
const codePathSegments = [];
let currentCodePathSegments = new Set();
return {
onCodePathStart() {
codePathSegments.push(currentCodePathSegments);
currentCodePathSegments = new Set();
},
onCodePathEnd() {
currentCodePathSegments = codePathSegments.pop();
},
onUnreachableCodePathSegmentStart(segment) {
currentCodePathSegments.add(segment);
},
onUnreachableCodePathSegmentEnd(segment) {
currentCodePathSegments.delete(segment);
},
onCodePathSegmentEnd(segment) {
currentCodePathSegments.delete(segment);
},
onCodePathSegmentStart(segment, node) {
currentCodePathSegments.add(segment);
if (isLoopingTarget(node)) {
const loop = node.parent;
loopsByTargetSegments.set(segment, loop);
}
},
onCodePathSegmentLoop(_, toSegment, node) {
const loop = loopsByTargetSegments.get(toSegment);
/**
* The second iteration is reachable, meaning that the loop is valid by the logic of this rule,
* only if there is at least one loop event with the appropriate target (which has been already
* determined in the `loopsByTargetSegments` map), raised from either:
*
* - the end of the loop's body (in which case `node === loop`)
* - a `continue` statement
*
* This condition skips loop events raised from `ForInStatement > .right` and `ForOfStatement > .right` nodes.
*/
if (node === loop || node.type === "ContinueStatement") {
// Removes loop if it exists in the set. Otherwise, `Set#delete` has no effect and doesn't throw.
loopsToReport.delete(loop);
}
},
[loopSelector](node) {
/**
* Ignore unreachable loop statements to avoid unnecessary complexity in the implementation, or false positives otherwise.
* For unreachable segments, the code path analysis does not raise events required for this implementation.
*/
if (isAnySegmentReachable(currentCodePathSegments)) {
loopsToReport.add(node);
}
},
"Program:exit"() {
loopsToReport.forEach(node =>
context.report({ node, messageId: "invalid" }),
);
},
};
},
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AACH,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC"}

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'prefer-namespace-keyword',
meta: {
type: 'suggestion',
docs: {
description: 'Require using `namespace` keyword over `module` keyword to declare custom TypeScript modules',
recommended: 'recommended',
},
fixable: 'code',
messages: {
useNamespace: "Use 'namespace' instead of 'module' to declare custom TypeScript modules.",
},
schema: [],
},
defaultOptions: [],
create(context) {
return {
TSModuleDeclaration(node) {
// Do nothing if the name is a string.
if (node.id.type === utils_1.AST_NODE_TYPES.Literal) {
return;
}
// Get tokens of the declaration header.
const moduleType = context.sourceCode.getTokenBefore(node.id);
if (moduleType?.type === utils_1.AST_TOKEN_TYPES.Identifier &&
moduleType.value === 'module') {
context.report({
node,
messageId: 'useNamespace',
fix(fixer) {
return fixer.replaceText(moduleType, 'namespace');
},
});
}
},
};
},
});