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,8 @@
import { _ as _class_check_private_static_access } from "./_class_check_private_static_access.js";
function _class_static_private_method_get(receiver, classConstructor, method) {
_class_check_private_static_access(receiver, classConstructor);
return method;
}
export { _class_static_private_method_get as _ };

View File

@@ -0,0 +1,68 @@
/**
* @fileoverview Optimized version of the `text-table` npm module to improve performance by replacing inefficient regex-based
* whitespace trimming with a modern built-in method.
*
* This modification addresses a performance issue reported in https://github.com/eslint/eslint/issues/18709
*
* The `text-table` module is published under the MIT License. For the original source, refer to:
* https://www.npmjs.com/package/text-table.
*/
/*
*
* This software is released under the MIT license:
*
* 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.
*/
"use strict";
module.exports = function (rows_, opts) {
const hsep = " ";
const align = opts.align;
const stringLength = opts.stringLength;
const sizes = rows_.reduce((acc, row) => {
row.forEach((c, ix) => {
const n = stringLength(c);
if (!acc[ix] || n > acc[ix]) {
acc[ix] = n;
}
});
return acc;
}, []);
return rows_
.map(row =>
row
.map((c, ix) => {
const n = sizes[ix] - stringLength(c) || 0;
const s = Array(Math.max(n + 1, 1)).join(" ");
if (align[ix] === "r") {
return s + c;
}
return c + s;
})
.join(hsep)
.trimEnd(),
)
.join("\n");
};

View File

@@ -0,0 +1,4 @@
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,73 @@
/**
* @fileoverview Require or disallow Unicode BOM
* @author Andrew Johnston <https://github.com/ehjay>
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "layout",
defaultOptions: ["never"],
docs: {
description: "Require or disallow Unicode byte order mark (BOM)",
recommended: false,
url: "https://eslint.org/docs/latest/rules/unicode-bom",
},
fixable: "whitespace",
schema: [
{
enum: ["always", "never"],
},
],
messages: {
expected: "Expected Unicode BOM (Byte Order Mark).",
unexpected: "Unexpected Unicode BOM (Byte Order Mark).",
},
},
create(context) {
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program: function checkUnicodeBOM(node) {
const sourceCode = context.sourceCode,
location = { column: 0, line: 1 };
const [requireBOM] = context.options;
if (!sourceCode.hasBOM && requireBOM === "always") {
context.report({
node,
loc: location,
messageId: "expected",
fix(fixer) {
return fixer.insertTextBeforeRange(
[0, 1],
"\uFEFF",
);
},
});
} else if (sourceCode.hasBOM && requireBOM === "never") {
context.report({
node,
loc: location,
messageId: "unexpected",
fix(fixer) {
return fixer.removeRange([-1, 0]);
},
});
}
},
};
},
};

View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variable = exports.ImplicitLibVariable = exports.ESLintScopeVariable = void 0;
var ESLintScopeVariable_1 = require("./ESLintScopeVariable");
Object.defineProperty(exports, "ESLintScopeVariable", { enumerable: true, get: function () { return ESLintScopeVariable_1.ESLintScopeVariable; } });
var ImplicitLibVariable_1 = require("./ImplicitLibVariable");
Object.defineProperty(exports, "ImplicitLibVariable", { enumerable: true, get: function () { return ImplicitLibVariable_1.ImplicitLibVariable; } });
var Variable_1 = require("./Variable");
Object.defineProperty(exports, "Variable", { enumerable: true, get: function () { return Variable_1.Variable; } });

View File

@@ -0,0 +1,289 @@
import { SolanaError, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE } from '@solana/errors';
import { combineCodec, createDecoder, createEncoder, assertByteArrayIsNotEmptyForCodec, assertByteArrayHasEnoughBytesForCodec } from '@solana/codecs-core';
// src/assertions.ts
function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
if (value < min || value > max) {
throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {
codecDescription,
max,
min,
value
});
}
}
// src/common.ts
var Endian = /* @__PURE__ */ ((Endian2) => {
Endian2[Endian2["Little"] = 0] = "Little";
Endian2[Endian2["Big"] = 1] = "Big";
return Endian2;
})(Endian || {});
function isLittleEndian(config) {
return config?.endian === 1 /* Big */ ? false : true;
}
function numberEncoderFactory(input) {
return createEncoder({
fixedSize: input.size,
write(value, bytes, offset) {
if (input.range) {
assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
}
const arrayBuffer = new ArrayBuffer(input.size);
input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));
bytes.set(new Uint8Array(arrayBuffer), offset);
return offset + input.size;
}
});
}
function numberDecoderFactory(input) {
return createDecoder({
fixedSize: input.size,
read(bytes, offset = 0) {
assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);
assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);
const view = new DataView(toArrayBuffer(bytes, offset, input.size));
return [input.get(view, isLittleEndian(input.config)), offset + input.size];
}
});
}
function toArrayBuffer(bytes, offset, length) {
const bytesOffset = bytes.byteOffset + (offset ?? 0);
const bytesLength = length ?? bytes.byteLength;
return bytes.buffer.slice(bytesOffset, bytesOffset + bytesLength);
}
// src/f32.ts
var getF32Encoder = (config = {}) => numberEncoderFactory({
config,
name: "f32",
set: (view, value, le) => view.setFloat32(0, Number(value), le),
size: 4
});
var getF32Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getFloat32(0, le),
name: "f32",
size: 4
});
var getF32Codec = (config = {}) => combineCodec(getF32Encoder(config), getF32Decoder(config));
var getF64Encoder = (config = {}) => numberEncoderFactory({
config,
name: "f64",
set: (view, value, le) => view.setFloat64(0, Number(value), le),
size: 8
});
var getF64Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getFloat64(0, le),
name: "f64",
size: 8
});
var getF64Codec = (config = {}) => combineCodec(getF64Encoder(config), getF64Decoder(config));
var getI128Encoder = (config = {}) => numberEncoderFactory({
config,
name: "i128",
range: [-BigInt("0x7fffffffffffffffffffffffffffffff") - 1n, BigInt("0x7fffffffffffffffffffffffffffffff")],
set: (view, value, le) => {
const leftOffset = le ? 8 : 0;
const rightOffset = le ? 0 : 8;
const rightMask = 0xffffffffffffffffn;
view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);
view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);
},
size: 16
});
var getI128Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => {
const leftOffset = le ? 8 : 0;
const rightOffset = le ? 0 : 8;
const left = view.getBigInt64(leftOffset, le);
const right = view.getBigUint64(rightOffset, le);
return (left << 64n) + right;
},
name: "i128",
size: 16
});
var getI128Codec = (config = {}) => combineCodec(getI128Encoder(config), getI128Decoder(config));
var getI16Encoder = (config = {}) => numberEncoderFactory({
config,
name: "i16",
range: [-Number("0x7fff") - 1, Number("0x7fff")],
set: (view, value, le) => view.setInt16(0, Number(value), le),
size: 2
});
var getI16Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getInt16(0, le),
name: "i16",
size: 2
});
var getI16Codec = (config = {}) => combineCodec(getI16Encoder(config), getI16Decoder(config));
var getI32Encoder = (config = {}) => numberEncoderFactory({
config,
name: "i32",
range: [-Number("0x7fffffff") - 1, Number("0x7fffffff")],
set: (view, value, le) => view.setInt32(0, Number(value), le),
size: 4
});
var getI32Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getInt32(0, le),
name: "i32",
size: 4
});
var getI32Codec = (config = {}) => combineCodec(getI32Encoder(config), getI32Decoder(config));
var getI64Encoder = (config = {}) => numberEncoderFactory({
config,
name: "i64",
range: [-BigInt("0x7fffffffffffffff") - 1n, BigInt("0x7fffffffffffffff")],
set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),
size: 8
});
var getI64Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getBigInt64(0, le),
name: "i64",
size: 8
});
var getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));
var getI8Encoder = () => numberEncoderFactory({
name: "i8",
range: [-Number("0x7f") - 1, Number("0x7f")],
set: (view, value) => view.setInt8(0, Number(value)),
size: 1
});
var getI8Decoder = () => numberDecoderFactory({
get: (view) => view.getInt8(0),
name: "i8",
size: 1
});
var getI8Codec = () => combineCodec(getI8Encoder(), getI8Decoder());
var getShortU16Encoder = () => createEncoder({
getSizeFromValue: (value) => {
if (value <= 127) return 1;
if (value <= 16383) return 2;
return 3;
},
maxSize: 3,
write: (value, bytes, offset) => {
assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
const shortU16Bytes = [0];
for (let ii = 0; ; ii += 1) {
const alignedValue = Number(value) >> ii * 7;
if (alignedValue === 0) {
break;
}
const nextSevenBits = 127 & alignedValue;
shortU16Bytes[ii] = nextSevenBits;
if (ii > 0) {
shortU16Bytes[ii - 1] |= 128;
}
}
bytes.set(shortU16Bytes, offset);
return offset + shortU16Bytes.length;
}
});
var getShortU16Decoder = () => createDecoder({
maxSize: 3,
read: (bytes, offset) => {
let value = 0;
let byteCount = 0;
while (++byteCount) {
const byteIndex = byteCount - 1;
const currentByte = bytes[offset + byteIndex];
const nextSevenBits = 127 & currentByte;
value |= nextSevenBits << byteIndex * 7;
if ((currentByte & 128) === 0) {
break;
}
}
return [value, offset + byteCount];
}
});
var getShortU16Codec = () => combineCodec(getShortU16Encoder(), getShortU16Decoder());
var getU128Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u128",
range: [0n, BigInt("0xffffffffffffffffffffffffffffffff")],
set: (view, value, le) => {
const leftOffset = le ? 8 : 0;
const rightOffset = le ? 0 : 8;
const rightMask = 0xffffffffffffffffn;
view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);
view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);
},
size: 16
});
var getU128Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => {
const leftOffset = le ? 8 : 0;
const rightOffset = le ? 0 : 8;
const left = view.getBigUint64(leftOffset, le);
const right = view.getBigUint64(rightOffset, le);
return (left << 64n) + right;
},
name: "u128",
size: 16
});
var getU128Codec = (config = {}) => combineCodec(getU128Encoder(config), getU128Decoder(config));
var getU16Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u16",
range: [0, Number("0xffff")],
set: (view, value, le) => view.setUint16(0, Number(value), le),
size: 2
});
var getU16Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getUint16(0, le),
name: "u16",
size: 2
});
var getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));
var getU32Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u32",
range: [0, Number("0xffffffff")],
set: (view, value, le) => view.setUint32(0, Number(value), le),
size: 4
});
var getU32Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getUint32(0, le),
name: "u32",
size: 4
});
var getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));
var getU64Encoder = (config = {}) => numberEncoderFactory({
config,
name: "u64",
range: [0n, BigInt("0xffffffffffffffff")],
set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),
size: 8
});
var getU64Decoder = (config = {}) => numberDecoderFactory({
config,
get: (view, le) => view.getBigUint64(0, le),
name: "u64",
size: 8
});
var getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));
var getU8Encoder = () => numberEncoderFactory({
name: "u8",
range: [0, Number("0xff")],
set: (view, value) => view.setUint8(0, Number(value)),
size: 1
});
var getU8Decoder = () => numberDecoderFactory({
get: (view) => view.getUint8(0),
name: "u8",
size: 1
});
var getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());
export { Endian, assertNumberIsBetweenForCodec, getF32Codec, getF32Decoder, getF32Encoder, getF64Codec, getF64Decoder, getF64Encoder, getI128Codec, getI128Decoder, getI128Encoder, getI16Codec, getI16Decoder, getI16Encoder, getI32Codec, getI32Decoder, getI32Encoder, getI64Codec, getI64Decoder, getI64Encoder, getI8Codec, getI8Decoder, getI8Encoder, getShortU16Codec, getShortU16Decoder, getShortU16Encoder, getU128Codec, getU128Decoder, getU128Encoder, getU16Codec, getU16Decoder, getU16Encoder, getU32Codec, getU32Decoder, getU32Encoder, getU64Codec, getU64Decoder, getU64Encoder, getU8Codec, getU8Decoder, getU8Encoder };
//# sourceMappingURL=index.native.mjs.map
//# sourceMappingURL=index.native.mjs.map

View File

@@ -0,0 +1,6 @@
export var errorUtil;
(function (errorUtil) {
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
// biome-ignore lint:
errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));

View File

@@ -0,0 +1,6 @@
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
return Array.from(iter);
}
}
export { _iterable_to_array as _ };

View File

@@ -0,0 +1,24 @@
import { TSESLint } from '@typescript-eslint/utils';
export type MessageIds = 'removeUnusedImportDeclaration' | 'removeUnusedVar' | 'unusedVar' | 'usedIgnoredVar' | 'usedOnlyAsType';
export type Options = [
'all' | 'local' | {
args?: 'after-used' | 'all' | 'none';
argsIgnorePattern?: string;
caughtErrors?: 'all' | 'none';
caughtErrorsIgnorePattern?: string;
destructuredArrayIgnorePattern?: string;
enableAutofixRemoval?: {
imports?: boolean;
};
ignoreClassWithStaticInitBlock?: boolean;
ignoreRestSiblings?: boolean;
ignoreUsingDeclarations?: boolean;
reportUsedIgnorePattern?: boolean;
vars?: 'all' | 'local';
varsIgnorePattern?: string;
}
];
declare const _default: TSESLint.RuleModule<MessageIds, Options, import("../../rules").ESLintPluginDocs, TSESLint.RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1,13 @@
notifications:
email: false
language: node_js
node_js:
- node
deploy:
provider: npm
email:
secure: Y10Dvn9UbfpZPbulnl/e7dsiN/1xr06h7k6nJZyxRzr9Hh0UUFPism6k5CFaSegyPIF7sODNBQz4lvXIi2NwcvTLQruw5ehXW0NJ/G7x1TU94pzzhVJ31KBlRWzjKdvVTDsDzFxe5wKWxagPUTkieiIN9CWTQjafByNs3zbK8HL7cmu4Nc42JquVGbtpGgLs7Js+tY+WVB1dMQ4SfqpFgWjm2h05uyXCWHLK5amEAZJLP755lOVgMzw/jQGRg7J4vX4+eRE0r/g0v09x9FUU3ROEmJvqYa14CmGESRhSUyRlv4pnMIs/aK8ZDD8ia3eoTSvMJv8mzdvpkvKzWV1HSZFUX3QZVgWJEmeoF6XP+mdkWu5gnZVlOIBc8NANcS60Dr8QwF470xpPxsyAyf2o9UzX8Xy2qO8XNY/TykGO4soCfOEuVNdw5F9hHEldMHY8p9Z8EJSCn/xfM//LEvxRKREYsMqFtsnwUsv+qiAkHPSHXWQo6HYp+/xDchv63NxtjGHdPs9VpUFr1F8CxZjdis2HZfOnx51W0JIwNYlXNxeqC3WjRUqvRp2NknS982lRHCkHtZfHijGvMm7kj3QL+Ufc7pIfEGnMAKKiNv9kOryjQc29046pRZww9lWjrhoCeEPRhFbkgFV7Mo3bvOExstsSdRnOTlogCe4NviKOwfE=
api_key:
secure: cAmf8extX/sPl+sxC/6sWTmaiSGrXQY9C/lLg9c76Qn12MLysxDYgCRXfl8Az3RIbRuajq0SbyWXeDa/4wZc1PazuUGjZG82na+kuEDg8m5z0gLiJlhp60C0nj3WMJaRBRsOha1Jbs59eU3XNy+H0U5VczHrdw6v2yCHTlauhT/NYiPXMyKmTIJPB/X7gryFuXVhCPNdRBp3rPicbt0d68J+vWv9KNpjA1WB0WDUSl5rMUQbjjsRF2/DKj9WxXjmci+ac+/pCN3rQxgYZ0Ot5o5/RcWucc21ZdFgsLo8dq5YZDl/EQf/pPmkhquiiLRhiTyCBbEw1sDzYHTbTJThrukrZALg0on7XvxbXSQrxgc/IMJ/RT0PoGLEqyAZUSzGa6HPVlHUBt4LB3zgrswGmGUVkZmbiag0foIFeCKlydwEyBYfnFdRddxF6n3irft1l1NJ1HKNxKLnKvyt8iaOlGteXOOfLXzU17DgMgwTsZsvFmtFQcs6yolLHW9RnRTLf56+x/kJZ4kVJjHuyb/98pS4F7etJ2SpZqt1cVUFd/AYtnxL3jKiUhJLNL8hNUIH3eSpMfZUOUxGv1OWuwgyEhSONkITF2VPn4yuyxS23Ewq4LLj/u/9sPlLaGSN4Avaw21gi6L+M9x620sTZHYtNLniVMTAu6aPiM32zPreK2I=
on:
tags: true

View File

@@ -0,0 +1,12 @@
function _using(o, n, e) {
if (null == n) return n;
if (Object(n) !== n) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
if (e) var r = n[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
if (null == r && (r = n[Symbol.dispose || Symbol["for"]("Symbol.dispose")]), "function" != typeof r) throw new TypeError("Property [Symbol.dispose] is not a function.");
return o.push({
v: n,
d: r,
a: e
}), n;
}
module.exports = _using, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1 @@
{"version":3,"file":"moduleDetectionKind.enum.d.ts","sourceRoot":"","sources":["../../src/enums/moduleDetectionKind.enum.ts"],"names":[],"mappings":"AAEA,oBAAY,mBAAmB;IAC3B,IAAI,IAAI;IACR,IAAI,IAAI;IACR,MAAM,IAAI;IACV,KAAK,IAAI;CACZ"}

View File

@@ -0,0 +1,60 @@
"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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZodISODuration = exports.ZodISOTime = exports.ZodISODate = exports.ZodISODateTime = void 0;
exports.datetime = datetime;
exports.date = date;
exports.time = time;
exports.duration = duration;
const core = __importStar(require("../core/index.cjs"));
const schemas = __importStar(require("./schemas.cjs"));
exports.ZodISODateTime = core.$constructor("ZodISODateTime", (inst, def) => {
core.$ZodISODateTime.init(inst, def);
schemas.ZodStringFormat.init(inst, def);
});
function datetime(params) {
return core._isoDateTime(exports.ZodISODateTime, params);
}
exports.ZodISODate = core.$constructor("ZodISODate", (inst, def) => {
core.$ZodISODate.init(inst, def);
schemas.ZodStringFormat.init(inst, def);
});
function date(params) {
return core._isoDate(exports.ZodISODate, params);
}
exports.ZodISOTime = core.$constructor("ZodISOTime", (inst, def) => {
core.$ZodISOTime.init(inst, def);
schemas.ZodStringFormat.init(inst, def);
});
function time(params) {
return core._isoTime(exports.ZodISOTime, params);
}
exports.ZodISODuration = core.$constructor("ZodISODuration", (inst, def) => {
core.$ZodISODuration.init(inst, def);
schemas.ZodStringFormat.init(inst, def);
});
function duration(params) {
return core._isoDuration(exports.ZodISODuration, params);
}

View File

@@ -0,0 +1,52 @@
{
"name": "@eslint/core",
"version": "1.2.1",
"description": "Runtime-agnostic core of ESLint",
"type": "module",
"types": "./dist/esm/types.d.ts",
"exports": {
"types": {
"import": "./dist/esm/types.d.ts",
"require": "./dist/cjs/types.d.cts"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build:cts": "node -e \"fs.cpSync('dist/esm/types.d.ts', 'dist/cjs/types.d.cts')\"",
"build": "tsc && npm run build:cts",
"lint:types": "attw --pack",
"pretest": "npm run build",
"test": "npm run test:types",
"test:jsr": "npx -y jsr@latest publish --dry-run",
"test:types": "tsc -p tests/types/tsconfig.json"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git",
"directory": "packages/core"
},
"keywords": [
"eslint",
"core"
],
"author": "Nicholas C. Zakas",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/core#readme",
"dependencies": {
"@types/json-schema": "^7.0.15"
},
"devDependencies": {
"json-schema": "^0.4.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
}
}

View File

@@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pbkdf2 = pbkdf2;
exports.pbkdf2Async = pbkdf2Async;
/**
* PBKDF (RFC 2898). Can be used to create a key from password and salt.
* @module
*/
const hmac_ts_1 = require("./hmac.js");
// prettier-ignore
const utils_ts_1 = require("./utils.js");
// Common prologue and epilogue for sync/async functions
function pbkdf2Init(hash, _password, _salt, _opts) {
(0, utils_ts_1.ahash)(hash);
const opts = (0, utils_ts_1.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts);
const { c, dkLen, asyncTick } = opts;
(0, utils_ts_1.anumber)(c);
(0, utils_ts_1.anumber)(dkLen);
(0, utils_ts_1.anumber)(asyncTick);
if (c < 1)
throw new Error('iterations (c) should be >= 1');
const password = (0, utils_ts_1.kdfInputToBytes)(_password);
const salt = (0, utils_ts_1.kdfInputToBytes)(_salt);
// DK = PBKDF2(PRF, Password, Salt, c, dkLen);
const DK = new Uint8Array(dkLen);
// U1 = PRF(Password, Salt + INT_32_BE(i))
const PRF = hmac_ts_1.hmac.create(hash, password);
const PRFSalt = PRF._cloneInto().update(salt);
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
PRF.destroy();
PRFSalt.destroy();
if (prfW)
prfW.destroy();
(0, utils_ts_1.clean)(u);
return DK;
}
/**
* PBKDF2-HMAC: RFC 2898 key derivation function
* @param hash - hash function that would be used e.g. sha256
* @param password - password from which a derived key is generated
* @param salt - cryptographic salt
* @param opts - {c, dkLen} where c is work factor and dkLen is output message size
* @example
* const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
*/
function pbkdf2(hash, password, salt, opts) {
const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
let prfW; // Working copy
const arr = new Uint8Array(4);
const view = (0, utils_ts_1.createView)(arr);
const u = new Uint8Array(PRF.outputLen);
// DK = T1 + T2 + ⋯ + Tdklen/hlen
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
// Ti = F(Password, Salt, c, i)
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
// F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
// U1 = PRF(Password, Salt + INT_32_BE(i))
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
for (let ui = 1; ui < c; ui++) {
// Uc = PRF(Password, Uc1)
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i = 0; i < Ti.length; i++)
Ti[i] ^= u[i];
}
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
/**
* PBKDF2-HMAC: RFC 2898 key derivation function. Async version.
* @example
* await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
*/
async function pbkdf2Async(hash, password, salt, opts) {
const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
let prfW; // Working copy
const arr = new Uint8Array(4);
const view = (0, utils_ts_1.createView)(arr);
const u = new Uint8Array(PRF.outputLen);
// DK = T1 + T2 + ⋯ + Tdklen/hlen
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
// Ti = F(Password, Salt, c, i)
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
// F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
// U1 = PRF(Password, Salt + INT_32_BE(i))
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
await (0, utils_ts_1.asyncLoop)(c - 1, asyncTick, () => {
// Uc = PRF(Password, Uc1)
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i = 0; i < Ti.length; i++)
Ti[i] ^= u[i];
});
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
//# sourceMappingURL=pbkdf2.js.map

View File

@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2020_promise: LibDefinition;

View File

@@ -0,0 +1,8 @@
declare module "node:path/posix" {
import path = require("node:path");
export = path.posix;
}
declare module "path/posix" {
import path = require("path");
export = path.posix;
}

View File

@@ -0,0 +1,505 @@
<!--
-- This file is auto-generated from README_js.md. Changes should be made there.
-->
# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser)
For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs
- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs
- **Cross-platform** - Support for ...
- CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds)
- Node 8, 10, 12, 14
- Chrome, Safari, Firefox, Edge, IE 11 browsers
- Webpack and rollup.js module bundlers
- [React Native / Expo](#react-native--expo)
- **Secure** - Cryptographically-strong random values
- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers
- **CLI** - Includes the [`uuid` command line](#command-line) utility
**Upgrading from `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#upgrading-from-uuid3x) for details.
## Quickstart
To create a random UUID...
**1. Install**
```shell
npm install uuid
```
**2. Create a UUID** (ES6 module syntax)
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
```
... or using CommonJS syntax:
```javascript
const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
```
For timestamp UUIDs, namespace UUIDs, and other options read on ...
## API Summary
| | | |
| --- | --- | --- |
| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` |
| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` |
| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` |
| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | |
| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | |
| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | |
| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | |
| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` |
| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` |
## API
### uuid.NIL
The nil UUID string (all zeros).
Example:
```javascript
import { NIL as NIL_UUID } from 'uuid';
NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000'
```
### uuid.parse(str)
Convert UUID string to array of bytes
| | |
| --------- | ---------------------------------------- |
| `str` | A valid UUID `String` |
| _returns_ | `Uint8Array[16]` |
| _throws_ | `TypeError` if `str` is not a valid UUID |
Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below.
Example:
```javascript
import { parse as uuidParse } from 'uuid';
// Parse a UUID
const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b');
// Convert to hex strings to show byte order (for documentation purposes)
[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨
// [
// '6e', 'c0', 'bd', '7f',
// '11', 'c0', '43', 'da',
// '97', '5e', '2a', '8a',
// 'd9', 'eb', 'ae', '0b'
// ]
```
### uuid.stringify(arr[, offset])
Convert array of bytes to UUID string
| | |
| -------------- | ---------------------------------------------------------------------------- |
| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. |
| [`offset` = 0] | `Number` Starting index in the Array |
| _returns_ | `String` |
| _throws_ | `TypeError` if a valid UUID string cannot be generated |
Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below.
Example:
```javascript
import { stringify as uuidStringify } from 'uuid';
const uuidBytes = [
0x6e,
0xc0,
0xbd,
0x7f,
0x11,
0xc0,
0x43,
0xda,
0x97,
0x5e,
0x2a,
0x8a,
0xd9,
0xeb,
0xae,
0x0b,
];
uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'
```
### uuid.v1([options[, buffer[, offset]]])
Create an RFC version 1 (timestamp) UUID
| | |
| --- | --- |
| [`options`] | `Object` with one or more of the following properties: |
| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) |
| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff |
| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) |
| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanseconds to add to `msecs`, should be 0-10,000) |
| [`options.random`] | `Array` of 16 random bytes (0-255) |
| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
| _throws_ | `Error` if more than 10M UUIDs/sec are requested |
Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process.
Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields.
Example:
```javascript
import { v1 as uuidv1 } from 'uuid';
uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d'
```
Example using `options`:
```javascript
import { v1 as uuidv1 } from 'uuid';
const v1options = {
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
clockseq: 0x1234,
msecs: new Date('2011-11-01').getTime(),
nsecs: 5678,
};
uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
```
### uuid.v3(name, namespace[, buffer[, offset]])
Create an RFC version 3 (namespace w/ MD5) UUID
API is identical to `v5()`, but uses "v3" instead.
&#x26a0;&#xfe0f; Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_."
### uuid.v4([options[, buffer[, offset]]])
Create an RFC version 4 (random) UUID
| | |
| --- | --- |
| [`options`] | `Object` with one or more of the following properties: |
| [`options.random`] | `Array` of 16 random bytes (0-255) |
| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) |
| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
Example:
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
```
Example using predefined `random` values:
```javascript
import { v4 as uuidv4 } from 'uuid';
const v4options = {
random: [
0x10,
0x91,
0x56,
0xbe,
0xc4,
0xfb,
0xc1,
0xea,
0x71,
0xb4,
0xef,
0xe1,
0x67,
0x1c,
0x58,
0x36,
],
};
uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836'
```
### uuid.v5(name, namespace[, buffer[, offset]])
Create an RFC version 5 (namespace w/ SHA-1) UUID
| | |
| --- | --- |
| `name` | `String \| Array` |
| `namespace` | `String \| Array[16]` Namespace UUID |
| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` |
| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` |
| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` |
Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`.
Example with custom namespace:
```javascript
import { v5 as uuidv5 } from 'uuid';
// Define a custom namespace. Readers, create your own using something like
// https://www.uuidgenerator.net/
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
```
Example with RFC `URL` namespace:
```javascript
import { v5 as uuidv5 } from 'uuid';
uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1'
```
### uuid.validate(str)
Test a string to see if it is a valid UUID
| | |
| --------- | --------------------------------------------------- |
| `str` | `String` to validate |
| _returns_ | `true` if string is a valid UUID, `false` otherwise |
Example:
```javascript
import { validate as uuidValidate } from 'uuid';
uuidValidate('not a UUID'); // ⇨ false
uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true
```
Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds.
```javascript
import { version as uuidVersion } from 'uuid';
import { validate as uuidValidate } from 'uuid';
function uuidValidateV4(uuid) {
return uuidValidate(uuid) && uuidVersion(uuid) === 4;
}
const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210';
const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836';
uuidValidateV4(v4Uuid); // ⇨ true
uuidValidateV4(v1Uuid); // ⇨ false
```
### uuid.version(str)
Detect RFC version of a UUID
| | |
| --------- | ---------------------------------------- |
| `str` | A valid UUID `String` |
| _returns_ | `Number` The RFC version of the UUID |
| _throws_ | `TypeError` if `str` is not a valid UUID |
Example:
```javascript
import { version as uuidVersion } from 'uuid';
uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1
uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4
```
## Command Line
UUIDs can be generated from the command line using `uuid`.
```shell
$ uuid
ddeb27fb-d9a0-4624-be4d-4615062daed4
```
The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details:
```shell
$ uuid --help
Usage:
uuid
uuid v1
uuid v3 <name> <namespace uuid>
uuid v4
uuid v5 <name> <namespace uuid>
uuid --help
Note: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs
defined by RFC4122
```
## ECMAScript Modules
This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments).
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
```
To run the examples you must first create a dist build of this library in the module root:
```shell
npm run build
```
## CDN Builds
### ECMAScript Modules
To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/):
```html
<script type="module">
import { v4 as uuidv4 } from 'https://jspm.dev/uuid';
console.log(uuidv4()); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
</script>
```
### UMD
To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs:
**Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**:
```html
<script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script>
```
**Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**:
```html
<script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuidv4.min.js"></script>
```
**Using [cdnjs](https://cdnjs.com/libraries/uuid)**:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.1.0/uuidv4.min.js"></script>
```
These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method:
```html
<script>
uuidv4(); // ⇨ '55af1e37-0734-46d8-b070-a1e42e4fc392'
</script>
```
Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively.
## "getRandomValues() not supported"
This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill:
### React Native / Expo
1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme)
1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point:
```javascript
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
```
Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`.
### Web Workers / Service Workers (Edge <= 18)
[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please).
## Upgrading From `uuid@7.x`
### Only Named Exports Supported When Using with Node.js ESM
`uuid@7.x` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports.
Instead of doing:
```javascript
import uuid from 'uuid';
uuid.v4();
```
you will now have to use the named exports:
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4();
```
### Deep Requires No Longer Supported
Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported.
## Upgrading From `uuid@3.x`
"_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_"
In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped.
### Deep Requires Now Deprecated
`uuid@3.x` encouraged the use of deep requires to minimize the bundle size of browser builds:
```javascript
const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED!
uuidv4();
```
As of `uuid@7.x` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax:
```javascript
import { v4 as uuidv4 } from 'uuid';
uuidv4();
```
... or for CommonJS:
```javascript
const { v4: uuidv4 } = require('uuid');
uuidv4();
```
### Default Export Removed
`uuid@3.x` was exporting the Version 4 UUID method as a default export:
```javascript
const uuid = require('uuid'); // <== REMOVED!
```
This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`.
----
Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd)

View File

@@ -0,0 +1 @@
{"version":3,"file":"p384.d.ts","sourceRoot":"","sources":["../src/p384.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AACtE,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAe,IAAI,IAAI,KAAK,EAAE,MAAM,WAAW,CAAC;AACvD,sEAAsE;AACtE,eAAO,MAAM,IAAI,EAAE,OAAO,KAAa,CAAC;AACxC,sEAAsE;AACtE,eAAO,MAAM,SAAS,EAAE,OAAO,KAAa,CAAC;AAC7C,6EAA6E;AAC7E,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAAqD,CAAC;AAChG,6EAA6E;AAC7E,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,MAAM,CAAuD,CAAC"}

View File

@@ -0,0 +1,101 @@
{
"name": "ts-api-utils",
"version": "2.5.0",
"description": "Utility functions for working with TypeScript's API. Successor to the wonderful tsutils. 🛠️️",
"repository": {
"type": "git",
"url": "https://github.com/JoshuaKGoldberg/ts-api-utils"
},
"license": "MIT",
"author": {
"name": "JoshuaKGoldberg",
"email": "npm@joshuakgoldberg.com"
},
"sideEffects": false,
"type": "module",
"exports": {
".": {
"types": {
"import": "./lib/index.d.ts",
"require": "./lib/index.d.cts"
},
"import": "./lib/index.js",
"require": "./lib/index.cjs"
}
},
"main": "./lib/index.js",
"files": [
"lib/"
],
"scripts": {
"build": "tsup src/index.ts && cp lib/index.d.ts lib/index.d.cts",
"docs": "typedoc",
"docs:serve": "npx --yes http-server docs/generated",
"format": "prettier \"**/*\" --ignore-unknown",
"lint": "eslint . --max-warnings 0",
"lint:docs": "typedoc --validation --treatValidationWarningsAsErrors",
"lint:knip": "knip",
"lint:md": "markdownlint \"**/*.md\" \".github/**/*.md\" --rules sentences-per-line",
"lint:package": "publint --strict",
"lint:packages": "pnpm dedupe --check",
"lint:spelling": "cspell \"**\" \".github/**/*\"",
"prepare": "husky",
"should-semantic-release": "should-semantic-release --verbose",
"test": "vitest",
"tsc": "tsc"
},
"lint-staged": {
"*": "prettier --ignore-unknown --write"
},
"devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
"@eslint/js": "^10.0.0",
"@phenomnomnominal/tsquery": "^6.1.3",
"@release-it/conventional-changelog": "^10.0.0",
"@types/eslint-plugin-markdown": "^2.0.2",
"@types/node": "^18.19.74",
"@typescript/vfs": "^1.6.0",
"@vitest/coverage-v8": "^3.0.0",
"@vitest/eslint-plugin": "^1.1.25",
"console-fail-test": "^0.6.0",
"cspell": "^9.0.0",
"eslint": "^10.0.0",
"eslint-plugin-jsdoc": "^62.0.0",
"eslint-plugin-jsonc": "^3.0.0",
"eslint-plugin-markdown": "^5.1.0",
"eslint-plugin-n": "^17.15.1",
"eslint-plugin-package-json": "^0.91.0",
"eslint-plugin-perfectionist": "^5.0.0",
"eslint-plugin-regexp": "^3.0.0",
"eslint-plugin-yml": "^3.0.0",
"husky": "^9.1.7",
"jsonc-eslint-parser": "^3.0.0",
"knip": "^5.46.0",
"lint-staged": "^16.0.0",
"markdownlint": "^0.40.0",
"markdownlint-cli": "^0.48.0",
"prettier": "^3.4.2",
"prettier-plugin-curly": "^0.4.0",
"prettier-plugin-packagejson": "^3.0.0",
"publint": "^0.3.17",
"release-it": "^19.0.0",
"sentences-per-line": "^0.3.0",
"should-semantic-release": "^0.3.0",
"tsup": "^8.3.6",
"typedoc": "^0.28.0",
"typedoc-plugin-coverage": "^4.0.0",
"typedoc-plugin-custom-validation": "^2.0.2",
"typedoc-plugin-konamimojisplosion": "^0.0.2",
"typedoc-plugin-mdn-links": "^5.0.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.22.0",
"vitest": "^3.0.0"
},
"peerDependencies": {
"typescript": ">=4.8.4"
},
"packageManager": "pnpm@10.32.1",
"engines": {
"node": ">=18.12"
}
}

View File

@@ -0,0 +1,9 @@
import Dispatcher from './dispatcher'
declare function setGlobalDispatcher<DispatcherImplementation extends Dispatcher> (dispatcher: DispatcherImplementation): void
declare function getGlobalDispatcher (): Dispatcher
export {
getGlobalDispatcher,
setGlobalDispatcher
}

View File

@@ -0,0 +1,19 @@
"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.es2025_float16 = void 0;
const base_config_1 = require("./base-config");
const es2015_iterable_1 = require("./es2015.iterable");
const es2015_symbol_1 = require("./es2015.symbol");
exports.es2025_float16 = {
libs: [es2015_symbol_1.es2015_symbol, es2015_iterable_1.es2015_iterable],
variables: [
['Float16Array', base_config_1.TYPE_VALUE],
['Float16ArrayConstructor', base_config_1.TYPE],
['Math', base_config_1.TYPE],
['DataView', base_config_1.TYPE],
],
};

View File

@@ -0,0 +1,4 @@
#!/usr/bin/env node
"use strict"
require("../dist/bin.js")

View File

@@ -0,0 +1,625 @@
"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 (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJSONSchema = fromJSONSchema;
const registries_js_1 = require("../core/registries.cjs");
const _checks = __importStar(require("./checks.cjs"));
const _iso = __importStar(require("./iso.cjs"));
const _schemas = __importStar(require("./schemas.cjs"));
// Local z object to avoid circular dependency with ../index.js
const z = {
..._schemas,
..._checks,
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
"$defs",
"definitions",
// Core schema keywords
"$id",
"id",
"$comment",
"$anchor",
"$vocabulary",
"$dynamicRef",
"$dynamicAnchor",
// Type
"type",
"enum",
"const",
// Composition
"anyOf",
"oneOf",
"allOf",
"not",
// Object
"properties",
"required",
"additionalProperties",
"patternProperties",
"propertyNames",
"minProperties",
"maxProperties",
// Array
"items",
"prefixItems",
"additionalItems",
"minItems",
"maxItems",
"uniqueItems",
"contains",
"minContains",
"maxContains",
// String
"minLength",
"maxLength",
"pattern",
"format",
// Number
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
// Already handled metadata
"description",
"default",
// Content
"contentEncoding",
"contentMediaType",
"contentSchema",
// Unsupported (error-throwing)
"unevaluatedItems",
"unevaluatedProperties",
"if",
"then",
"else",
"dependentSchemas",
"dependentRequired",
// OpenAPI
"nullable",
"readOnly",
]);
function detectVersion(schema, defaultTarget) {
const $schema = schema.$schema;
if ($schema === "https://json-schema.org/draft/2020-12/schema") {
return "draft-2020-12";
}
if ($schema === "http://json-schema.org/draft-07/schema#") {
return "draft-7";
}
if ($schema === "http://json-schema.org/draft-04/schema#") {
return "draft-4";
}
// Use defaultTarget if provided, otherwise default to draft-2020-12
return defaultTarget ?? "draft-2020-12";
}
function resolveRef(ref, ctx) {
if (!ref.startsWith("#")) {
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
}
const path = ref.slice(1).split("/").filter(Boolean);
// Handle root reference "#"
if (path.length === 0) {
return ctx.rootSchema;
}
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
if (path[0] === defsKey) {
const key = path[1];
if (!key || !ctx.defs[key]) {
throw new Error(`Reference not found: ${ref}`);
}
return ctx.defs[key];
}
throw new Error(`Reference not found: ${ref}`);
}
function convertBaseSchema(schema, ctx) {
// Handle unsupported features
if (schema.not !== undefined) {
// Special case: { not: {} } represents never
if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
return z.never();
}
throw new Error("not is not supported in Zod (except { not: {} } for never)");
}
if (schema.unevaluatedItems !== undefined) {
throw new Error("unevaluatedItems is not supported");
}
if (schema.unevaluatedProperties !== undefined) {
throw new Error("unevaluatedProperties is not supported");
}
if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
throw new Error("Conditional schemas (if/then/else) are not supported");
}
if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
throw new Error("dependentSchemas and dependentRequired are not supported");
}
// Handle $ref
if (schema.$ref) {
const refPath = schema.$ref;
if (ctx.refs.has(refPath)) {
return ctx.refs.get(refPath);
}
if (ctx.processing.has(refPath)) {
// Circular reference - use lazy
return z.lazy(() => {
if (!ctx.refs.has(refPath)) {
throw new Error(`Circular reference not resolved: ${refPath}`);
}
return ctx.refs.get(refPath);
});
}
ctx.processing.add(refPath);
const resolved = resolveRef(refPath, ctx);
const zodSchema = convertSchema(resolved, ctx);
ctx.refs.set(refPath, zodSchema);
ctx.processing.delete(refPath);
return zodSchema;
}
// Handle enum
if (schema.enum !== undefined) {
const enumValues = schema.enum;
// Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] }
if (ctx.version === "openapi-3.0" &&
schema.nullable === true &&
enumValues.length === 1 &&
enumValues[0] === null) {
return z.null();
}
if (enumValues.length === 0) {
return z.never();
}
if (enumValues.length === 1) {
return z.literal(enumValues[0]);
}
// Check if all values are strings
if (enumValues.every((v) => typeof v === "string")) {
return z.enum(enumValues);
}
// Mixed types - use union of literals
const literalSchemas = enumValues.map((v) => z.literal(v));
if (literalSchemas.length < 2) {
return literalSchemas[0];
}
return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
}
// Handle const
if (schema.const !== undefined) {
return z.literal(schema.const);
}
// Handle type
const type = schema.type;
if (Array.isArray(type)) {
// Expand type array into anyOf union
const typeSchemas = type.map((t) => {
const typeSchema = { ...schema, type: t };
return convertBaseSchema(typeSchema, ctx);
});
if (typeSchemas.length === 0) {
return z.never();
}
if (typeSchemas.length === 1) {
return typeSchemas[0];
}
return z.union(typeSchemas);
}
if (!type) {
// No type specified - empty schema (any)
return z.any();
}
let zodSchema;
switch (type) {
case "string": {
let stringSchema = z.string();
// Apply format using .check() with Zod format functions
if (schema.format) {
const format = schema.format;
// Map common formats to Zod check functions
if (format === "email") {
stringSchema = stringSchema.check(z.email());
}
else if (format === "uri" || format === "uri-reference") {
stringSchema = stringSchema.check(z.url());
}
else if (format === "uuid" || format === "guid") {
stringSchema = stringSchema.check(z.uuid());
}
else if (format === "date-time") {
stringSchema = stringSchema.check(z.iso.datetime());
}
else if (format === "date") {
stringSchema = stringSchema.check(z.iso.date());
}
else if (format === "time") {
stringSchema = stringSchema.check(z.iso.time());
}
else if (format === "duration") {
stringSchema = stringSchema.check(z.iso.duration());
}
else if (format === "ipv4") {
stringSchema = stringSchema.check(z.ipv4());
}
else if (format === "ipv6") {
stringSchema = stringSchema.check(z.ipv6());
}
else if (format === "mac") {
stringSchema = stringSchema.check(z.mac());
}
else if (format === "cidr") {
stringSchema = stringSchema.check(z.cidrv4());
}
else if (format === "cidr-v6") {
stringSchema = stringSchema.check(z.cidrv6());
}
else if (format === "base64") {
stringSchema = stringSchema.check(z.base64());
}
else if (format === "base64url") {
stringSchema = stringSchema.check(z.base64url());
}
else if (format === "e164") {
stringSchema = stringSchema.check(z.e164());
}
else if (format === "jwt") {
stringSchema = stringSchema.check(z.jwt());
}
else if (format === "emoji") {
stringSchema = stringSchema.check(z.emoji());
}
else if (format === "nanoid") {
stringSchema = stringSchema.check(z.nanoid());
}
else if (format === "cuid") {
stringSchema = stringSchema.check(z.cuid());
}
else if (format === "cuid2") {
stringSchema = stringSchema.check(z.cuid2());
}
else if (format === "ulid") {
stringSchema = stringSchema.check(z.ulid());
}
else if (format === "xid") {
stringSchema = stringSchema.check(z.xid());
}
else if (format === "ksuid") {
stringSchema = stringSchema.check(z.ksuid());
}
// Note: json-string format is not currently supported by Zod
// Custom formats are ignored - keep as plain string
}
// Apply constraints
if (typeof schema.minLength === "number") {
stringSchema = stringSchema.min(schema.minLength);
}
if (typeof schema.maxLength === "number") {
stringSchema = stringSchema.max(schema.maxLength);
}
if (schema.pattern) {
// JSON Schema patterns are not implicitly anchored (match anywhere in string)
stringSchema = stringSchema.regex(new RegExp(schema.pattern));
}
zodSchema = stringSchema;
break;
}
case "number":
case "integer": {
let numberSchema = type === "integer" ? z.number().int() : z.number();
// Apply constraints
if (typeof schema.minimum === "number") {
numberSchema = numberSchema.min(schema.minimum);
}
if (typeof schema.maximum === "number") {
numberSchema = numberSchema.max(schema.maximum);
}
if (typeof schema.exclusiveMinimum === "number") {
numberSchema = numberSchema.gt(schema.exclusiveMinimum);
}
else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
numberSchema = numberSchema.gt(schema.minimum);
}
if (typeof schema.exclusiveMaximum === "number") {
numberSchema = numberSchema.lt(schema.exclusiveMaximum);
}
else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
numberSchema = numberSchema.lt(schema.maximum);
}
if (typeof schema.multipleOf === "number") {
numberSchema = numberSchema.multipleOf(schema.multipleOf);
}
zodSchema = numberSchema;
break;
}
case "boolean": {
zodSchema = z.boolean();
break;
}
case "null": {
zodSchema = z.null();
break;
}
case "object": {
const shape = {};
const properties = schema.properties || {};
const requiredSet = new Set(schema.required || []);
// Convert properties - mark optional ones
for (const [key, propSchema] of Object.entries(properties)) {
const propZodSchema = convertSchema(propSchema, ctx);
// If not in required array, make it optional
shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
}
// Handle propertyNames
if (schema.propertyNames) {
const keySchema = convertSchema(schema.propertyNames, ctx);
const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object"
? convertSchema(schema.additionalProperties, ctx)
: z.any();
// Case A: No properties (pure record)
if (Object.keys(shape).length === 0) {
zodSchema = z.record(keySchema, valueSchema);
break;
}
// Case B: With properties (intersection of object and looseRecord)
const objectSchema = z.object(shape).passthrough();
const recordSchema = z.looseRecord(keySchema, valueSchema);
zodSchema = z.intersection(objectSchema, recordSchema);
break;
}
// Handle patternProperties
if (schema.patternProperties) {
// patternProperties: keys matching pattern must satisfy corresponding schema
// Use loose records so non-matching keys pass through
const patternProps = schema.patternProperties;
const patternKeys = Object.keys(patternProps);
const looseRecords = [];
for (const pattern of patternKeys) {
const patternValue = convertSchema(patternProps[pattern], ctx);
const keySchema = z.string().regex(new RegExp(pattern));
looseRecords.push(z.looseRecord(keySchema, patternValue));
}
// Build intersection: object schema + all pattern property records
const schemasToIntersect = [];
if (Object.keys(shape).length > 0) {
// Use passthrough so patternProperties can validate additional keys
schemasToIntersect.push(z.object(shape).passthrough());
}
schemasToIntersect.push(...looseRecords);
if (schemasToIntersect.length === 0) {
zodSchema = z.object({}).passthrough();
}
else if (schemasToIntersect.length === 1) {
zodSchema = schemasToIntersect[0];
}
else {
// Chain intersections: (A & B) & C & D ...
let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
for (let i = 2; i < schemasToIntersect.length; i++) {
result = z.intersection(result, schemasToIntersect[i]);
}
zodSchema = result;
}
break;
}
// Handle additionalProperties
// In JSON Schema, additionalProperties defaults to true (allow any extra properties)
// In Zod, objects strip unknown keys by default, so we need to handle this explicitly
const objectSchema = z.object(shape);
if (schema.additionalProperties === false) {
// Strict mode - no extra properties allowed
zodSchema = objectSchema.strict();
}
else if (typeof schema.additionalProperties === "object") {
// Extra properties must match the specified schema
zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));
}
else {
// additionalProperties is true or undefined - allow any extra properties (passthrough)
zodSchema = objectSchema.passthrough();
}
break;
}
case "array": {
// TODO: uniqueItems is not supported
// TODO: contains/minContains/maxContains are not supported
// Check if this is a tuple (prefixItems or items as array)
const prefixItems = schema.prefixItems;
const items = schema.items;
if (prefixItems && Array.isArray(prefixItems)) {
// Tuple with prefixItems (draft-2020-12)
const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
const rest = items && typeof items === "object" && !Array.isArray(items)
? convertSchema(items, ctx)
: undefined;
if (rest) {
zodSchema = z.tuple(tupleItems).rest(rest);
}
else {
zodSchema = z.tuple(tupleItems);
}
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (Array.isArray(items)) {
// Tuple with items array (draft-7)
const tupleItems = items.map((item) => convertSchema(item, ctx));
const rest = schema.additionalItems && typeof schema.additionalItems === "object"
? convertSchema(schema.additionalItems, ctx)
: undefined; // additionalItems: false means no rest, handled by default tuple behavior
if (rest) {
zodSchema = z.tuple(tupleItems).rest(rest);
}
else {
zodSchema = z.tuple(tupleItems);
}
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (items !== undefined) {
// Regular array
const element = convertSchema(items, ctx);
let arraySchema = z.array(element);
// Apply constraints
if (typeof schema.minItems === "number") {
arraySchema = arraySchema.min(schema.minItems);
}
if (typeof schema.maxItems === "number") {
arraySchema = arraySchema.max(schema.maxItems);
}
zodSchema = arraySchema;
}
else {
// No items specified - array of any
zodSchema = z.array(z.any());
}
break;
}
default:
throw new Error(`Unsupported type: ${type}`);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Convert base schema first (ignoring composition keywords)
let baseSchema = convertBaseSchema(schema, ctx);
const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
// Process composition keywords LAST (they can appear together)
// Handle anyOf - wrap base schema with union
if (schema.anyOf && Array.isArray(schema.anyOf)) {
const options = schema.anyOf.map((s) => convertSchema(s, ctx));
const anyOfUnion = z.union(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
}
// Handle oneOf - exclusive union (exactly one must match)
if (schema.oneOf && Array.isArray(schema.oneOf)) {
const options = schema.oneOf.map((s) => convertSchema(s, ctx));
const oneOfUnion = z.xor(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
}
// Handle allOf - wrap base schema with intersection
if (schema.allOf && Array.isArray(schema.allOf)) {
if (schema.allOf.length === 0) {
baseSchema = hasExplicitType ? baseSchema : z.any();
}
else {
let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
const startIdx = hasExplicitType ? 0 : 1;
for (let i = startIdx; i < schema.allOf.length; i++) {
result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
}
baseSchema = result;
}
}
// Handle nullable (OpenAPI 3.0)
if (schema.nullable === true && ctx.version === "openapi-3.0") {
baseSchema = z.nullable(baseSchema);
}
// Handle readOnly
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Apply `default` so it wraps the fully-composed schema. This ensures
// `parse(undefined) -> default` works regardless of which branch of
// `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied
// registry. Description is handled separately below via `.describe()` to
// preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
extraMeta[key] = schema[key];
}
}
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets
// `_zod.parent` on the clone, so registry lookups on the returned reference
// still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
function fromJSONSchema(schema, params) {
// Handle boolean schemas
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Normalize input via a JSON round-trip. This guarantees the converter
// walks a plain, finite, JSON-valid object graph: cyclic inputs fail here,
// getter/Proxy-based properties are materialized into static values, and
// class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: normalized,
registry: params?.registry ?? registries_js_1.globalRegistry,
};
return convertSchema(normalized, ctx);
}

View File

@@ -0,0 +1,305 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SCHEMA = void 0;
const util_1 = require("../../util");
const enums_1 = require("./enums");
const $DEFS = {
// enums
predefinedFormats: {
enum: (0, util_1.getEnumNames)(enums_1.PredefinedFormats),
type: 'string',
},
typeModifiers: {
enum: (0, util_1.getEnumNames)(enums_1.TypeModifiers),
type: 'string',
},
underscoreOptions: {
enum: (0, util_1.getEnumNames)(enums_1.UnderscoreOptions),
type: 'string',
},
// repeated types
formatOptionsConfig: {
oneOf: [
{
additionalItems: false,
items: {
$ref: '#/$defs/predefinedFormats',
},
type: 'array',
},
{
type: 'null',
},
],
},
matchRegexConfig: {
additionalProperties: false,
properties: {
match: { type: 'boolean' },
regex: { type: 'string' },
},
required: ['match', 'regex'],
type: 'object',
},
prefixSuffixConfig: {
additionalItems: false,
items: {
minLength: 1,
type: 'string',
},
type: 'array',
},
};
const UNDERSCORE_SCHEMA = {
$ref: '#/$defs/underscoreOptions',
};
const PREFIX_SUFFIX_SCHEMA = {
$ref: '#/$defs/prefixSuffixConfig',
};
const MATCH_REGEX_SCHEMA = {
$ref: '#/$defs/matchRegexConfig',
};
const FORMAT_OPTIONS_PROPERTIES = {
custom: MATCH_REGEX_SCHEMA,
failureMessage: {
type: 'string',
},
format: {
$ref: '#/$defs/formatOptionsConfig',
},
leadingUnderscore: UNDERSCORE_SCHEMA,
prefix: PREFIX_SUFFIX_SCHEMA,
suffix: PREFIX_SUFFIX_SCHEMA,
trailingUnderscore: UNDERSCORE_SCHEMA,
};
function selectorSchema(selectorString, allowType, modifiers) {
const selector = {
filter: {
oneOf: [
{
minLength: 1,
type: 'string',
},
MATCH_REGEX_SCHEMA,
],
},
selector: {
enum: [selectorString],
type: 'string',
},
};
if (modifiers && modifiers.length > 0) {
selector.modifiers = {
additionalItems: false,
items: {
enum: modifiers,
type: 'string',
},
type: 'array',
};
}
if (allowType) {
selector.types = {
additionalItems: false,
items: {
$ref: '#/$defs/typeModifiers',
},
type: 'array',
};
}
return [
{
additionalProperties: false,
description: `Selector '${selectorString}'`,
properties: {
...FORMAT_OPTIONS_PROPERTIES,
...selector,
},
required: ['selector', 'format'],
type: 'object',
},
];
}
function selectorsSchema() {
return {
additionalProperties: false,
description: 'Multiple selectors in one config',
properties: {
...FORMAT_OPTIONS_PROPERTIES,
filter: {
oneOf: [
{
minLength: 1,
type: 'string',
},
MATCH_REGEX_SCHEMA,
],
},
modifiers: {
additionalItems: false,
items: {
enum: (0, util_1.getEnumNames)(enums_1.Modifiers),
type: 'string',
},
type: 'array',
},
selector: {
additionalItems: false,
items: {
enum: [...(0, util_1.getEnumNames)(enums_1.MetaSelectors), ...(0, util_1.getEnumNames)(enums_1.Selectors)],
type: 'string',
},
type: 'array',
},
types: {
additionalItems: false,
items: {
$ref: '#/$defs/typeModifiers',
},
type: 'array',
},
},
required: ['selector', 'format'],
type: 'object',
};
}
exports.SCHEMA = {
$defs: $DEFS,
additionalItems: false,
items: {
oneOf: [
selectorsSchema(),
...selectorSchema('default', false, (0, util_1.getEnumNames)(enums_1.Modifiers)),
...selectorSchema('variableLike', false, ['unused', 'async']),
...selectorSchema('variable', true, [
'const',
'destructured',
'exported',
'global',
'unused',
'async',
]),
...selectorSchema('function', false, [
'exported',
'global',
'unused',
'async',
]),
...selectorSchema('parameter', true, ['destructured', 'unused']),
...selectorSchema('memberLike', false, [
'abstract',
'private',
'#private',
'protected',
'public',
'readonly',
'requiresQuotes',
'static',
'override',
'async',
]),
...selectorSchema('classProperty', true, [
'abstract',
'private',
'#private',
'protected',
'public',
'readonly',
'requiresQuotes',
'static',
'override',
]),
...selectorSchema('objectLiteralProperty', true, [
'public',
'requiresQuotes',
]),
...selectorSchema('typeProperty', true, [
'public',
'readonly',
'requiresQuotes',
]),
...selectorSchema('parameterProperty', true, [
'private',
'protected',
'public',
'readonly',
]),
...selectorSchema('property', true, [
'abstract',
'private',
'#private',
'protected',
'public',
'readonly',
'requiresQuotes',
'static',
'override',
'async',
]),
...selectorSchema('classMethod', false, [
'abstract',
'private',
'#private',
'protected',
'public',
'requiresQuotes',
'static',
'override',
'async',
]),
...selectorSchema('objectLiteralMethod', false, [
'public',
'requiresQuotes',
'async',
]),
...selectorSchema('typeMethod', false, ['public', 'requiresQuotes']),
...selectorSchema('method', false, [
'abstract',
'private',
'#private',
'protected',
'public',
'requiresQuotes',
'static',
'override',
'async',
]),
...selectorSchema('classicAccessor', true, [
'abstract',
'private',
'protected',
'public',
'requiresQuotes',
'static',
'override',
]),
...selectorSchema('autoAccessor', true, [
'abstract',
'private',
'protected',
'public',
'requiresQuotes',
'static',
'override',
]),
...selectorSchema('accessor', true, [
'abstract',
'private',
'protected',
'public',
'requiresQuotes',
'static',
'override',
]),
...selectorSchema('enumMember', false, ['requiresQuotes']),
...selectorSchema('typeLike', false, ['abstract', 'exported', 'unused']),
...selectorSchema('class', false, ['abstract', 'exported', 'unused']),
...selectorSchema('interface', false, ['exported', 'unused']),
...selectorSchema('typeAlias', false, ['exported', 'unused']),
...selectorSchema('enum', false, ['exported', 'unused']),
...selectorSchema('typeParameter', false, ['unused']),
...selectorSchema('import', false, ['default', 'namespace']),
],
},
type: 'array',
};

View File

@@ -0,0 +1,9 @@
function _applyDecoratedDescriptor(i, e, r, n, l) {
var a = {};
return Object.keys(n).forEach(function (i) {
a[i] = n[i];
}), a.enumerable = !!a.enumerable, a.configurable = !!a.configurable, ("value" in a || a.initializer) && (a.writable = !0), a = r.slice().reverse().reduce(function (r, n) {
return n(i, e, r) || r;
}, a), l && void 0 !== a.initializer && (a.value = a.initializer ? a.initializer.call(l) : void 0, a.initializer = void 0), void 0 === a.initializer ? (Object.defineProperty(i, e, a), null) : a;
}
export { _applyDecoratedDescriptor as default };

View File

@@ -0,0 +1,16 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeDeclaredInFile = typeDeclaredInFile;
const typescript_estree_1 = require("@typescript-eslint/typescript-estree");
const node_path_1 = __importDefault(require("node:path"));
function typeDeclaredInFile(relativePath, declarationFiles, program) {
if (relativePath == null) {
const cwd = (0, typescript_estree_1.getCanonicalFileName)(program.getCurrentDirectory());
return declarationFiles.some(declaration => (0, typescript_estree_1.getCanonicalFileName)(declaration.fileName).startsWith(cwd));
}
const absolutePath = (0, typescript_estree_1.getCanonicalFileName)(node_path_1.default.join(program.getCurrentDirectory(), relativePath));
return declarationFiles.some(declaration => (0, typescript_estree_1.getCanonicalFileName)(declaration.fileName) === absolutePath);
}