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,95 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/mini";
test("z.number", () => {
const a = z.number();
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, 123.45)).toEqual(123.45);
expect(() => z.parse(a, "123")).toThrow();
expect(() => z.parse(a, false)).toThrow();
type a = z.infer<typeof a>;
expectTypeOf<a>().toEqualTypeOf<number>();
});
test("z.number async", async () => {
const a = z.number().check(z.refine(async (_) => _ > 0));
await expect(z.parseAsync(a, 123)).resolves.toEqual(123);
await expect(() => z.parseAsync(a, -123)).rejects.toThrow();
await expect(() => z.parseAsync(a, "123")).rejects.toThrow();
});
test("z.int", () => {
const a = z.int();
expect(z.parse(a, 123)).toEqual(123);
expect(() => z.parse(a, 123.45)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
expect(() => z.parse(a, false)).toThrow();
});
test("z.float32", () => {
const a = z.float32();
expect(z.parse(a, 123.45)).toEqual(123.45);
expect(() => z.parse(a, "123.45")).toThrow();
expect(() => z.parse(a, false)).toThrow();
// -3.4028234663852886e38, 3.4028234663852886e38;
expect(() => z.parse(a, 3.4028234663852886e38 * 2)).toThrow(); // Exceeds max
expect(() => z.parse(a, -3.4028234663852886e38 * 2)).toThrow(); // Exceeds min
});
test("z.float64", () => {
const a = z.float64();
expect(z.parse(a, 123.45)).toEqual(123.45);
expect(() => z.parse(a, "123.45")).toThrow();
expect(() => z.parse(a, false)).toThrow();
expect(() => z.parse(a, 1.7976931348623157e308 * 2)).toThrow(); // Exceeds max
expect(() => z.parse(a, -1.7976931348623157e308 * 2)).toThrow(); // Exceeds min
});
test("z.int32", () => {
const a = z.int32();
expect(z.parse(a, 123)).toEqual(123);
expect(() => z.parse(a, 123.45)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
expect(() => z.parse(a, false)).toThrow();
expect(() => z.parse(a, 2147483648)).toThrow(); // Exceeds max
expect(() => z.parse(a, -2147483649)).toThrow(); // Exceeds min
});
test("z.uint32", () => {
const a = z.uint32();
expect(z.parse(a, 123)).toEqual(123);
expect(() => z.parse(a, -123)).toThrow();
expect(() => z.parse(a, 123.45)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
expect(() => z.parse(a, false)).toThrow();
expect(() => z.parse(a, 4294967296)).toThrow(); // Exceeds max
expect(() => z.parse(a, -1)).toThrow(); // Below min
});
test("z.int64", () => {
const a = z.int64();
expect(z.parse(a, BigInt(123))).toEqual(BigInt(123));
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, 123.45)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
expect(() => z.parse(a, false)).toThrow();
expect(() => z.parse(a, BigInt("9223372036854775808"))).toThrow();
expect(() => z.parse(a, BigInt("-9223372036854775809"))).toThrow();
// expect(() => z.parse(a, BigInt("9223372036854775808"))).toThrow(); // Exceeds max
// expect(() => z.parse(a, BigInt("-9223372036854775809"))).toThrow(); // Exceeds min
});
test("z.uint64", () => {
const a = z.uint64();
expect(z.parse(a, BigInt(123))).toEqual(BigInt(123));
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, -123)).toThrow();
expect(() => z.parse(a, 123.45)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
expect(() => z.parse(a, false)).toThrow();
expect(() => z.parse(a, BigInt("18446744073709551616"))).toThrow(); // Exceeds max
expect(() => z.parse(a, BigInt("-1"))).toThrow(); // Below min
// expect(() => z.parse(a, BigInt("18446744073709551616"))).toThrow(); // Exceeds max
// expect(() => z.parse(a, BigInt("-1"))).toThrow(); // Below min
});

View File

@@ -0,0 +1,51 @@
/*! *****************************************************************************
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.
***************************************************************************** */
interface Int8ArrayConstructor {
new (): Int8Array<ArrayBuffer>;
}
interface Uint8ArrayConstructor {
new (): Uint8Array<ArrayBuffer>;
}
interface Uint8ClampedArrayConstructor {
new (): Uint8ClampedArray<ArrayBuffer>;
}
interface Int16ArrayConstructor {
new (): Int16Array<ArrayBuffer>;
}
interface Uint16ArrayConstructor {
new (): Uint16Array<ArrayBuffer>;
}
interface Int32ArrayConstructor {
new (): Int32Array<ArrayBuffer>;
}
interface Uint32ArrayConstructor {
new (): Uint32Array<ArrayBuffer>;
}
interface Float32ArrayConstructor {
new (): Float32Array<ArrayBuffer>;
}
interface Float64ArrayConstructor {
new (): Float64Array<ArrayBuffer>;
}

View File

@@ -0,0 +1,101 @@
/**
* @fileoverview Rule to disallow assignments to native objects or read-only global variables
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [{ exceptions: [] }],
docs: {
description:
"Disallow assignments to native objects or read-only global variables",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-global-assign",
},
schema: [
{
type: "object",
properties: {
exceptions: {
type: "array",
items: { type: "string" },
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
globalShouldNotBeModified:
"Read-only global '{{name}}' should not be modified.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const [{ exceptions }] = context.options;
/**
* Reports write references.
* @param {Reference} reference A reference to check.
* @param {number} index The index of the reference in the references.
* @param {Reference[]} references The array that the reference belongs to.
* @returns {void}
*/
function checkReference(reference, index, references) {
const identifier = reference.identifier;
if (
reference.init === false &&
reference.isWrite() &&
/*
* Destructuring assignments can have multiple default value,
* so possibly there are multiple writeable references for the same identifier.
*/
(index === 0 || references[index - 1].identifier !== identifier)
) {
context.report({
node: identifier,
messageId: "globalShouldNotBeModified",
data: {
name: identifier.name,
},
});
}
}
/**
* Reports write references if a given variable is read-only builtin.
* @param {Variable} variable A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
if (
variable.writeable === false &&
!exceptions.includes(variable.name)
) {
variable.references.forEach(checkReference);
}
}
return {
Program(node) {
const globalScope = sourceCode.getScope(node);
globalScope.variables.forEach(checkVariable);
},
};
},
};

View File

@@ -0,0 +1,15 @@
import type * as errors from "./errors.js";
export interface $ZodConfig {
/** Custom error map. Overrides `config().localeError`. */
customError?: errors.$ZodErrorMap | undefined;
/** Localized error map. Lowest priority. */
localeError?: errors.$ZodErrorMap | undefined;
}
export const globalConfig: $ZodConfig = {};
export function config(config?: Partial<$ZodConfig>): $ZodConfig {
if (config) Object.assign(globalConfig, config);
return globalConfig;
}

View File

@@ -0,0 +1,108 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.missing }}
{{# def.setupKeyword }}
{{# def.$data }}
{{ var $vSchema = 'schema' + $lvl; }}
{{## def.setupLoop:
{{? !$isData }}
var {{=$vSchema}} = validate.schema{{=$schemaPath}};
{{?}}
{{
var $i = 'i' + $lvl
, $propertyPath = 'schema' + $lvl + '[' + $i + ']'
, $missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
}
}}
#}}
{{## def.isRequiredOwnProperty:
Object.prototype.hasOwnProperty.call({{=$data}}, {{=$vSchema}}[{{=$i}}])
#}}
{{? !$isData }}
{{? $schema.length < it.opts.loopRequired &&
it.schema.properties && Object.keys(it.schema.properties).length }}
{{ var $required = []; }}
{{~ $schema:$property }}
{{ var $propertySch = it.schema.properties[$property]; }}
{{? !($propertySch && {{# def.nonEmptySchema:$propertySch}}) }}
{{ $required[$required.length] = $property; }}
{{?}}
{{~}}
{{??}}
{{ var $required = $schema; }}
{{?}}
{{?}}
{{? $isData || $required.length }}
{{
var $currentErrorPath = it.errorPath
, $loopRequired = $isData || $required.length >= it.opts.loopRequired
, $ownProperties = it.opts.ownProperties;
}}
{{? $breakOnError }}
var missing{{=$lvl}};
{{? $loopRequired }}
{{# def.setupLoop }}
var {{=$valid}} = true;
{{?$isData}}{{# def.check$dataIsArray }}{{?}}
for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) {
{{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined
{{? $ownProperties }}
&& {{# def.isRequiredOwnProperty }}
{{?}};
if (!{{=$valid}}) break;
}
{{? $isData }} } {{?}}
{{# def.checkError:'required' }}
else {
{{??}}
if ({{# def.checkMissingProperty:$required }}) {
{{# def.errorMissingProperty:'required' }}
} else {
{{?}}
{{??}}
{{? $loopRequired }}
{{# def.setupLoop }}
{{? $isData }}
if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) {
{{# def.addError:'required' }}
} else if ({{=$vSchema}} !== undefined) {
{{?}}
for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) {
if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined
{{? $ownProperties }}
|| !{{# def.isRequiredOwnProperty }}
{{?}}) {
{{# def.addError:'required' }}
}
}
{{? $isData }} } {{?}}
{{??}}
{{~ $required:$propertyKey }}
{{# def.allErrorsMissingProperty:'required' }}
{{~}}
{{?}}
{{?}}
{{ it.errorPath = $currentErrorPath; }}
{{?? $breakOnError }}
if (true) {
{{?}}

View File

@@ -0,0 +1,38 @@
"use strict";
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) return obj;
if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj };
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) return cache.get(obj);
var newObj = { __proto__: null };
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
else newObj[key] = obj[key];
}
}
newObj.default = obj;
if (cache) cache.set(obj, newObj);
return newObj;
}
exports._ = _interop_require_wildcard;

View File

@@ -0,0 +1,90 @@
/*! *****************************************************************************
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.
***************************************************************************** */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// src/cancellationToken/cancellationToken.ts
var fs = __toESM(require("fs"));
function pipeExists(name) {
return fs.existsSync(name);
}
function createCancellationToken(args) {
let cancellationPipeName;
for (let i = 0; i < args.length - 1; i++) {
if (args[i] === "--cancellationPipeName") {
cancellationPipeName = args[i + 1];
break;
}
}
if (!cancellationPipeName) {
return {
isCancellationRequested: () => false,
setRequest: (_requestId) => void 0,
resetRequest: (_requestId) => void 0
};
}
if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") {
const namePrefix = cancellationPipeName.slice(0, -1);
if (namePrefix.length === 0 || namePrefix.includes("*")) {
throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.");
}
let perRequestPipeName;
let currentRequestId;
return {
isCancellationRequested: () => perRequestPipeName !== void 0 && pipeExists(perRequestPipeName),
setRequest(requestId) {
currentRequestId = requestId;
perRequestPipeName = namePrefix + requestId;
},
resetRequest(requestId) {
if (currentRequestId !== requestId) {
throw new Error(`Mismatched request id, expected ${currentRequestId}, actual ${requestId}`);
}
perRequestPipeName = void 0;
}
};
} else {
return {
isCancellationRequested: () => pipeExists(cancellationPipeName),
setRequest: (_requestId) => void 0,
resetRequest: (_requestId) => void 0
};
}
}
module.exports = createCancellationToken;
//# sourceMappingURL=cancellationToken.js.map

View File

@@ -0,0 +1,12 @@
{
"type": "module",
"main": "index.cjs",
"module": "index.js",
"react-native": {
"./index.js": "./index.native.js"
},
"browser": {
"./index.js": "./index.browser.js",
"./index.cjs": "./index.browser.cjs"
}
}

View File

@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBig = exports.shrSL = exports.shrSH = exports.rotrSL = exports.rotrSH = exports.rotrBL = exports.rotrBH = exports.rotr32L = exports.rotr32H = exports.rotlSL = exports.rotlSH = exports.rotlBL = exports.rotlBH = exports.add5L = exports.add5H = exports.add4L = exports.add4H = exports.add3L = exports.add3H = void 0;
exports.add = add;
exports.fromBig = fromBig;
exports.split = split;
/**
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
* @todo re-check https://issues.chromium.org/issues/42212588
* @module
*/
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
exports.toBig = toBig;
// for Shift in [0, 32)
const shrSH = (h, _l, s) => h >>> s;
exports.shrSH = shrSH;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
exports.shrSL = shrSL;
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
exports.rotrSH = rotrSH;
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
exports.rotrSL = rotrSL;
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
exports.rotrBH = rotrBH;
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
exports.rotrBL = rotrBL;
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (_h, l) => l;
exports.rotr32H = rotr32H;
const rotr32L = (h, _l) => h;
exports.rotr32L = rotr32L;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
exports.rotlSH = rotlSH;
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
exports.rotlSL = rotlSL;
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
exports.rotlBH = rotlBH;
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
exports.rotlBL = rotlBL;
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
exports.add3L = add3L;
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
exports.add3H = add3H;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
exports.add4L = add4L;
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
exports.add4H = add4H;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
exports.add5L = add5L;
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
exports.add5H = add5H;
// prettier-ignore
const u64 = {
fromBig, split, toBig,
shrSH, shrSL,
rotrSH, rotrSL, rotrBH, rotrBL,
rotr32H, rotr32L,
rotlSH, rotlSL, rotlBH, rotlBL,
add, add3L, add3H, add4L, add4H, add5H, add5L,
};
exports.default = u64;
//# sourceMappingURL=_u64.js.map

View File

@@ -0,0 +1,58 @@
# isomorphic-ws
Isomorphic implementation of WebSocket.
It uses:
- [ws](https://github.com/websockets/ws) on Node
- [global.WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) in browsers
## Limitations
Before using this module you should know that
[`ws`](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket)
is not perfectly API compatible with
[WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket),
you should always test your code against both Node and browsers.
Some major differences:
- no `Server` implementation in browsers
## Usage
You need to install both this package and [ws](https://github.com/websockets/ws):
```
> npm i isomorphic-ws ws
```
Then just require this package:
```js
const WebSocket = require('isomorphic-ws')
const ws = new WebSocket('wss://echo.websocket.org/', {
origin: 'https://websocket.org'
});
ws.onopen = function open() {
console.log('connected');
ws.send(Date.now());
});
ws.onclose = function close() {
console.log('disconnected');
});
ws.onmessage = function incoming(data) {
console.log(`Roundtrip time: ${Date.now() - data} ms`);
setTimeout(function timeout() {
ws.send(Date.now());
}, 500);
});
```
## License
[MIT](LICENSE)

View File

@@ -0,0 +1,30 @@
import { type ClientOptions, type ClientSocketOptions, type ClientSpawnOptions } from "../options.ts";
import { TimingCollector, type TimingInfo } from "../timing.ts";
export type { ClientOptions, ClientSocketOptions, ClientSpawnOptions };
export declare class Client {
private channel;
private encoder;
private timing;
constructor(options: ClientOptions);
apiRequest<T>(method: string, params?: unknown): T;
apiRequestBinary(method: string, params?: unknown): Uint8Array | undefined;
echo(payload: string): string;
echoBinary(payload: Uint8Array): Uint8Array;
/**
* Returns a combined timing snapshot: client-measured round-trip and byte
* counts folded together with the server's own per-request processing time
* (fetched via a getServerTiming request) and estimated transport overhead.
*/
getTimingInfo(): TimingInfo;
resetTimingInfo(): void;
/**
* Returns the timing collector that per-node materialization is reported
* into, or undefined when timing collection is disabled. The returned
* collector is the same one folded into {@link getTimingInfo}, so
* materialization totals surface alongside request timings.
*/
getTimingCollector(): TimingCollector | undefined;
private recordTiming;
close(): void;
}
//# sourceMappingURL=client.d.ts.map

View File

@@ -0,0 +1,5 @@
"use strict";
// These types are internal to TS.
// They have been trimmed down to only include the relevant bits
// We use some special internal TS apis to help us do our parsing flexibly
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,108 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "caratteri", verb: "avere" },
file: { unit: "byte", verb: "avere" },
array: { unit: "elementi", verb: "avere" },
set: { unit: "elementi", verb: "avere" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "input",
email: "indirizzo email",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "data e ora ISO",
date: "data ISO",
time: "ora ISO",
duration: "durata ISO",
ipv4: "indirizzo IPv4",
ipv6: "indirizzo IPv6",
cidrv4: "intervallo IPv4",
cidrv6: "intervallo IPv6",
base64: "stringa codificata in base64",
base64url: "URL codificata in base64",
json_string: "stringa JSON",
e164: "numero E.164",
jwt: "JWT",
template_literal: "input",
};
const TypeDictionary = {
nan: "NaN",
number: "numero",
array: "vettore",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`;
}
return `Input non valido: atteso ${expected}, ricevuto ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`;
return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`;
return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
if (_issue.format === "ends_with")
return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Stringa non valida: deve includere "${_issue.includes}"`;
if (_issue.format === "regex")
return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
return `Input non valido: ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Numero non valido: deve essere un multiplo di ${issue.divisor}`;
case "unrecognized_keys":
return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Chiave non valida in ${issue.origin}`;
case "invalid_union":
return "Input non valido";
case "invalid_element":
return `Valore non valido in ${issue.origin}`;
default:
return `Input non valido`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_iterable_to_array.cjs",
"module": "../../esm/_iterable_to_array.js"
}

View File

@@ -0,0 +1,28 @@
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;

View File

@@ -0,0 +1,425 @@
function checkU32(n) {
// 0xff_ff_ff_ff
if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)
throw new Error('wrong u32 integer:' + n);
return n;
}
/** Checks if integer is in form of `1 << X` */
export function isPowerOfTwo(x) {
checkU32(x);
return (x & (x - 1)) === 0 && x !== 0;
}
export function nextPowerOfTwo(n) {
checkU32(n);
if (n <= 1)
return 1;
return (1 << (log2(n - 1) + 1)) >>> 0;
}
export function reverseBits(n, bits) {
checkU32(n);
let reversed = 0;
for (let i = 0; i < bits; i++, n >>>= 1)
reversed = (reversed << 1) | (n & 1);
return reversed;
}
/** Similar to `bitLen(x)-1` but much faster for small integers, like indices */
export function log2(n) {
checkU32(n);
return 31 - Math.clz32(n);
}
/**
* Moves lowest bit to highest position, which at first step splits
* array on even and odd indices, then it applied again to each part,
* which is core of fft
*/
export function bitReversalInplace(values) {
const n = values.length;
if (n < 2 || !isPowerOfTwo(n))
throw new Error('n must be a power of 2 and greater than 1. Got ' + n);
const bits = log2(n);
for (let i = 0; i < n; i++) {
const j = reverseBits(i, bits);
if (i < j) {
const tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
}
return values;
}
export function bitReversalPermutation(values) {
return bitReversalInplace(values.slice());
}
const _1n = /** @__PURE__ */ BigInt(1);
function findGenerator(field) {
let G = BigInt(2);
for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)
;
return G;
}
/** We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. */
export function rootsOfUnity(field, generator) {
// Factor field.ORDER-1 as oddFactor * 2^powerOfTwo
let oddFactor = field.ORDER - _1n;
let powerOfTwo = 0;
for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)
;
// Find non quadratic residue
let G = generator !== undefined ? BigInt(generator) : findGenerator(field);
// Powers of generator
const omegas = new Array(powerOfTwo + 1);
omegas[powerOfTwo] = field.pow(G, oddFactor);
for (let i = powerOfTwo; i > 0; i--)
omegas[i - 1] = field.sqr(omegas[i]);
// Compute all roots of unity for powers up to maxPower
const rootsCache = [];
const checkBits = (bits) => {
checkU32(bits);
if (bits > 31 || bits > powerOfTwo)
throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);
return bits;
};
const precomputeRoots = (maxPower) => {
checkBits(maxPower);
for (let power = maxPower; power >= 0; power--) {
if (rootsCache[power])
continue; // Skip if we've already computed roots for this power
const rootsAtPower = [];
for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))
rootsAtPower.push(cur);
rootsCache[power] = rootsAtPower;
}
return rootsCache[maxPower];
};
const brpCache = new Map();
const inverseCache = new Map();
// NOTE: we use bits instead of power, because power = 2**bits,
// but power is not neccesary isPowerOfTwo(power)!
return {
roots: (bits) => {
const b = checkBits(bits);
return precomputeRoots(b);
},
brp(bits) {
const b = checkBits(bits);
if (brpCache.has(b))
return brpCache.get(b);
else {
const res = bitReversalPermutation(this.roots(b));
brpCache.set(b, res);
return res;
}
},
inverse(bits) {
const b = checkBits(bits);
if (inverseCache.has(b))
return inverseCache.get(b);
else {
const res = field.invertBatch(this.roots(b));
inverseCache.set(b, res);
return res;
}
},
omega: (bits) => omegas[checkBits(bits)],
clear: () => {
rootsCache.splice(0, rootsCache.length);
brpCache.clear();
},
};
}
/**
* Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:
*
* - DIT (Decimation-in-Time): Bottom-Up (leaves -> root), Cool-Turkey
* - DIF (Decimation-in-Frequency): Top-Down (root -> leaves), GentlemanSande
*
* DIT takes brp input, returns natural output.
* DIF takes natural input, returns brp output.
*
* The output is actually identical. Time / frequence distinction is not meaningful
* for Polynomial multiplication in fields.
* Which means if protocol supports/needs brp output/inputs, then we can skip this step.
*
* Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega
* Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa
*/
export const FFTCore = (F, coreOpts) => {
const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
const bits = log2(N);
if (!isPowerOfTwo(N))
throw new Error('FFT: Polynomial size should be power of two');
const isDit = dit !== invertButterflies;
isDit;
return (values) => {
if (values.length !== N)
throw new Error('FFT: wrong Polynomial length');
if (dit && brp)
bitReversalInplace(values);
for (let i = 0, g = 1; i < bits - skipStages; i++) {
// For each stage s (sub-FFT length m = 2^s)
const s = dit ? i + 1 + skipStages : bits - i;
const m = 1 << s;
const m2 = m >> 1;
const stride = N >> s;
// Loop over each subarray of length m
for (let k = 0; k < N; k += m) {
// Loop over each butterfly within the subarray
for (let j = 0, grp = g++; j < m2; j++) {
const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;
const i0 = k + j;
const i1 = k + j + m2;
const omega = roots[rootPos];
const b = values[i1];
const a = values[i0];
// Inlining gives us 10% perf in kyber vs functions
if (isDit) {
const t = F.mul(b, omega); // Standard DIT butterfly
values[i0] = F.add(a, t);
values[i1] = F.sub(a, t);
}
else if (invertButterflies) {
values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)
values[i1] = F.mul(F.sub(b, a), omega);
}
else {
values[i0] = F.add(a, b); // Standard DIF butterfly
values[i1] = F.mul(F.sub(a, b), omega);
}
}
}
}
if (!dit && brp)
bitReversalInplace(values);
return values;
};
};
/**
* NTT aka FFT over finite field (NOT over complex numbers).
* Naming mirrors other libraries.
*/
export function FFT(roots, opts) {
const getLoop = (N, roots, brpInput = false, brpOutput = false) => {
if (brpInput && brpOutput) {
// we cannot optimize this case, but lets support it anyway
return (values) => FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));
}
if (brpInput)
return FFTCore(opts, { N, roots, dit: true, brp: false });
if (brpOutput)
return FFTCore(opts, { N, roots, dit: false, brp: false });
return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural
};
return {
direct(values, brpInput = false, brpOutput = false) {
const N = values.length;
if (!isPowerOfTwo(N))
throw new Error('FFT: Polynomial size should be power of two');
const bits = log2(N);
return getLoop(N, roots.roots(bits), brpInput, brpOutput)(values.slice());
},
inverse(values, brpInput = false, brpOutput = false) {
const N = values.length;
const bits = log2(N);
const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());
const ivm = opts.inv(BigInt(values.length)); // scale
// we can get brp output if we use dif instead of dit!
for (let i = 0; i < res.length; i++)
res[i] = opts.mul(res[i], ivm);
// Allows to re-use non-inverted roots, but is VERY fragile
// return [res[0]].concat(res.slice(1).reverse());
// inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)
return res;
},
};
}
export function poly(field, roots, create, fft, length) {
const F = field;
const _create = create ||
((len, elm) => new Array(len).fill(elm ?? F.ZERO));
const isPoly = (x) => Array.isArray(x) || ArrayBuffer.isView(x);
const checkLength = (...lst) => {
if (!lst.length)
return 0;
for (const i of lst)
if (!isPoly(i))
throw new Error('poly: not polynomial: ' + i);
const L = lst[0].length;
for (let i = 1; i < lst.length; i++)
if (lst[i].length !== L)
throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
if (length !== undefined && L !== length)
throw new Error(`poly: expected fixed length ${length}, got ${L}`);
return L;
};
function findOmegaIndex(x, n, brp = false) {
const bits = log2(n);
const omega = brp ? roots.brp(bits) : roots.roots(bits);
for (let i = 0; i < n; i++)
if (F.eql(x, omega[i]))
return i;
return -1;
}
// TODO: mutating versions for mlkem/mldsa
return {
roots,
create: _create,
length,
extend: (a, len) => {
checkLength(a);
const out = _create(len, F.ZERO);
for (let i = 0; i < a.length; i++)
out[i] = a[i];
return out;
},
degree: (a) => {
checkLength(a);
for (let i = a.length - 1; i >= 0; i--)
if (!F.is0(a[i]))
return i;
return -1;
},
add: (a, b) => {
const len = checkLength(a, b);
const out = _create(len);
for (let i = 0; i < len; i++)
out[i] = F.add(a[i], b[i]);
return out;
},
sub: (a, b) => {
const len = checkLength(a, b);
const out = _create(len);
for (let i = 0; i < len; i++)
out[i] = F.sub(a[i], b[i]);
return out;
},
dot: (a, b) => {
const len = checkLength(a, b);
const out = _create(len);
for (let i = 0; i < len; i++)
out[i] = F.mul(a[i], b[i]);
return out;
},
mul: (a, b) => {
if (isPoly(b)) {
const len = checkLength(a, b);
if (fft) {
const A = fft.direct(a, false, true);
const B = fft.direct(b, false, true);
for (let i = 0; i < A.length; i++)
A[i] = F.mul(A[i], B[i]);
return fft.inverse(A, true, false);
}
else {
// NOTE: this is quadratic and mostly for compat tests with FFT
const res = _create(len);
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
const k = (i + j) % len; // wrap mod length
res[k] = F.add(res[k], F.mul(a[i], b[j]));
}
}
return res;
}
}
else {
const out = _create(checkLength(a));
for (let i = 0; i < out.length; i++)
out[i] = F.mul(a[i], b);
return out;
}
},
convolve(a, b) {
const len = nextPowerOfTwo(a.length + b.length - 1);
return this.mul(this.extend(a, len), this.extend(b, len));
},
shift(p, factor) {
const out = _create(checkLength(p));
out[0] = p[0];
for (let i = 1, power = F.ONE; i < p.length; i++) {
power = F.mul(power, factor);
out[i] = F.mul(p[i], power);
}
return out;
},
clone: (a) => {
checkLength(a);
const out = _create(a.length);
for (let i = 0; i < a.length; i++)
out[i] = a[i];
return out;
},
eval: (a, basis) => {
checkLength(a);
let acc = F.ZERO;
for (let i = 0; i < a.length; i++)
acc = F.add(acc, F.mul(a[i], basis[i]));
return acc;
},
monomial: {
basis: (x, n) => {
const out = _create(n);
let pow = F.ONE;
for (let i = 0; i < n; i++) {
out[i] = pow;
pow = F.mul(pow, x);
}
return out;
},
eval: (a, x) => {
checkLength(a);
// Same as eval(a, monomialBasis(x, a.length)), but it is faster this way
let acc = F.ZERO;
for (let i = a.length - 1; i >= 0; i--)
acc = F.add(F.mul(acc, x), a[i]);
return acc;
},
},
lagrange: {
basis: (x, n, brp = false, weights) => {
const bits = log2(n);
const cache = weights || brp ? roots.brp(bits) : roots.roots(bits); // [ω⁰, ω¹, ..., ωⁿ⁻¹]
const out = _create(n);
// Fast Kronecker-δ shortcut
const idx = findOmegaIndex(x, n, brp);
if (idx !== -1) {
out[idx] = F.ONE;
return out;
}
const tm = F.pow(x, BigInt(n));
const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (xⁿ - 1)/n
const denom = _create(n);
for (let i = 0; i < n; i++)
denom[i] = F.sub(x, cache[i]);
const inv = F.invertBatch(denom);
for (let i = 0; i < n; i++)
out[i] = F.mul(c, F.mul(cache[i], inv[i]));
return out;
},
eval(a, x, brp = false) {
checkLength(a);
const idx = findOmegaIndex(x, a.length, brp);
if (idx !== -1)
return a[idx]; // fast path
const L = this.basis(x, a.length, brp); // Lᵢ(x)
let acc = F.ZERO;
for (let i = 0; i < a.length; i++)
if (!F.is0(a[i]))
acc = F.add(acc, F.mul(a[i], L[i]));
return acc;
},
},
vanishing(roots) {
checkLength(roots);
const out = _create(roots.length + 1, F.ZERO);
out[0] = F.ONE;
for (const r of roots) {
const neg = F.neg(r);
for (let j = out.length - 1; j > 0; j--)
out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
out[0] = F.mul(out[0], neg);
}
return out;
},
};
}
//# sourceMappingURL=fft.js.map

View File

@@ -0,0 +1,21 @@
/*! *****************************************************************************
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="es2016" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />

View File

@@ -0,0 +1,42 @@
'use strict'
class LRUCache {
constructor () {
this.max = 1000
this.map = new Map()
}
get (key) {
const value = this.map.get(key)
if (value === undefined) {
return undefined
} else {
// Remove the key from the map and add it to the end
this.map.delete(key)
this.map.set(key, value)
return value
}
}
delete (key) {
return this.map.delete(key)
}
set (key, value) {
const deleted = this.delete(key)
if (!deleted && value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value
this.delete(firstKey)
}
this.map.set(key, value)
}
return this
}
}
module.exports = LRUCache

View File

@@ -0,0 +1,282 @@
'use strict'
let { nanoid } = require('nanoid/non-secure')
let { isAbsolute, resolve } = require('path')
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
let { fileURLToPath, pathToFileURL } = require('url')
let CssSyntaxError = require('./css-syntax-error')
let PreviousMap = require('./previous-map')
let terminalHighlight = require('./terminal-highlight')
let lineToIndexCache = Symbol('lineToIndexCache')
let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
let pathAvailable = Boolean(resolve && isAbsolute)
function getLineToIndex(input) {
if (input[lineToIndexCache]) return input[lineToIndexCache]
let lines = input.css.split('\n')
let lineToIndex = new Array(lines.length)
let prevIndex = 0
for (let i = 0, l = lines.length; i < l; i++) {
lineToIndex[i] = prevIndex
prevIndex += lines[i].length + 1
}
input[lineToIndexCache] = lineToIndex
return lineToIndex
}
class Input {
get from() {
return this.file || this.id
}
constructor(css, opts = {}) {
if (
css === null ||
typeof css === 'undefined' ||
(typeof css === 'object' && !css.toString)
) {
throw new Error(`PostCSS received ${css} instead of CSS string`)
}
this.css = css.toString()
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.hasBOM = true
this.css = this.css.slice(1)
} else {
this.hasBOM = false
}
this.document = this.css
if (opts.document) this.document = opts.document.toString()
if (opts.from) {
if (
!pathAvailable ||
/^\w+:\/\//.test(opts.from) ||
isAbsolute(opts.from)
) {
this.file = opts.from
} else {
this.file = resolve(opts.from)
}
}
if (pathAvailable && sourceMapAvailable) {
let map = new PreviousMap(this.css, opts)
if (map.text) {
this.map = map
let file = map.consumer().file
if (!this.file && file) this.file = this.mapResolve(file)
}
}
if (!this.file) {
this.id = '<input css ' + nanoid(6) + '>'
}
if (this.map) this.map.file = this.from
}
error(message, line, column, opts = {}) {
let endColumn, endLine, endOffset, offset, result
if (line && typeof line === 'object') {
let start = line
let end = column
if (typeof start.offset === 'number') {
offset = start.offset
let pos = this.fromOffset(offset)
line = pos.line
column = pos.col
} else {
line = start.line
column = start.column
offset = this.fromLineAndColumn(line, column)
}
if (typeof end.offset === 'number') {
endOffset = end.offset
let pos = this.fromOffset(endOffset)
endLine = pos.line
endColumn = pos.col
} else {
endLine = end.line
endColumn = end.column
endOffset = this.fromLineAndColumn(end.line, end.column)
}
} else if (!column) {
offset = line
let pos = this.fromOffset(offset)
line = pos.line
column = pos.col
} else {
offset = this.fromLineAndColumn(line, column)
}
let origin = this.origin(line, column, endLine, endColumn)
if (origin) {
result = new CssSyntaxError(
message,
origin.endLine === undefined
? origin.line
: { column: origin.column, line: origin.line },
origin.endLine === undefined
? origin.column
: { column: origin.endColumn, line: origin.endLine },
origin.source,
origin.file,
opts.plugin
)
} else {
result = new CssSyntaxError(
message,
endLine === undefined ? line : { column, line },
endLine === undefined ? column : { column: endColumn, line: endLine },
this.css,
this.file,
opts.plugin
)
}
result.input = {
column,
endColumn,
endLine,
endOffset,
line,
offset,
source: this.css
}
if (this.file) {
if (pathToFileURL) {
result.input.url = pathToFileURL(this.file).toString()
}
result.input.file = this.file
}
return result
}
fromLineAndColumn(line, column) {
let lineToIndex = getLineToIndex(this)
let index = lineToIndex[line - 1]
return index + column - 1
}
fromOffset(offset) {
let lineToIndex = getLineToIndex(this)
let lastLine = lineToIndex[lineToIndex.length - 1]
let min = 0
if (offset >= lastLine) {
min = lineToIndex.length - 1
} else {
let max = lineToIndex.length - 2
let mid
while (min < max) {
mid = min + ((max - min) >> 1)
if (offset < lineToIndex[mid]) {
max = mid - 1
} else if (offset >= lineToIndex[mid + 1]) {
min = mid + 1
} else {
min = mid
break
}
}
}
return {
col: offset - lineToIndex[min] + 1,
line: min + 1
}
}
mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file
}
return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
}
origin(line, column, endLine, endColumn) {
if (!this.map) return false
let consumer = this.map.consumer()
let from = consumer.originalPositionFor({ column: column - 1, line })
if (!from.source) return false
let to
if (typeof endLine === 'number') {
let toPosition = consumer.originalPositionFor({
column: endColumn - 1,
line: endLine
})
// The source map may not have a mapping that covers the end position
// (`originalPositionFor()` then returns `null` for `line`/`column`
// instead of omitting them). Treat that the same as not requesting
// an end position at all, so `endLine`/`endColumn` stay a consistent
// `undefined` pair instead of a mix of `null` and a bogus number.
if (toPosition.source) to = toPosition
}
let fromUrl
if (isAbsolute(from.source)) {
fromUrl = pathToFileURL(from.source)
} else {
fromUrl = new URL(
from.source,
this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
)
}
let result = {
column: from.column + 1,
endColumn: to && to.column + 1,
endLine: to && to.line,
line: from.line,
url: fromUrl.toString()
}
if (fromUrl.protocol === 'file:') {
if (fileURLToPath) {
result.file = fileURLToPath(fromUrl)
} else {
/* c8 ignore next 2 */
throw new Error(`file: protocol is not available in this PostCSS build`)
}
}
let source = consumer.sourceContentFor(from.source)
if (source) result.source = source
return result
}
toJSON() {
let json = {}
for (let name of ['hasBOM', 'css', 'file', 'id']) {
if (this[name] != null) {
json[name] = this[name]
}
}
if (this.map) {
json.map = { ...this.map }
if (json.map.consumerCache) {
json.map.consumerCache = undefined
}
}
return json
}
}
module.exports = Input
Input.default = Input
if (terminalHighlight && terminalHighlight.registerInput) {
terminalHighlight.registerInput(Input)
}

View File

@@ -0,0 +1,87 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { util } from "../helpers/util.js";
test("nativeEnum test with consts", () => {
const Fruits: { Apple: "apple"; Banana: "banana" } = {
Apple: "apple",
Banana: "banana",
};
const fruitEnum = z.nativeEnum(Fruits);
type fruitEnum = z.infer<typeof fruitEnum>;
fruitEnum.parse("apple");
fruitEnum.parse("banana");
fruitEnum.parse(Fruits.Apple);
fruitEnum.parse(Fruits.Banana);
util.assertEqual<fruitEnum, "apple" | "banana">(true);
});
test("nativeEnum test with real enum", () => {
enum Fruits {
Apple = "apple",
Banana = "banana",
}
// @ts-ignore
const fruitEnum = z.nativeEnum(Fruits);
type fruitEnum = z.infer<typeof fruitEnum>;
fruitEnum.parse("apple");
fruitEnum.parse("banana");
fruitEnum.parse(Fruits.Apple);
fruitEnum.parse(Fruits.Banana);
util.assertIs<fruitEnum extends Fruits ? true : false>(true);
});
test("nativeEnum test with const with numeric keys", () => {
const FruitValues = {
Apple: 10,
Banana: 20,
// @ts-ignore
} as const;
const fruitEnum = z.nativeEnum(FruitValues);
type fruitEnum = z.infer<typeof fruitEnum>;
fruitEnum.parse(10);
fruitEnum.parse(20);
fruitEnum.parse(FruitValues.Apple);
fruitEnum.parse(FruitValues.Banana);
util.assertEqual<fruitEnum, 10 | 20>(true);
});
test("from enum", () => {
enum Fruits {
Cantaloupe = 0,
Apple = "apple",
Banana = "banana",
}
const FruitEnum = z.nativeEnum(Fruits as any);
type _FruitEnum = z.infer<typeof FruitEnum>;
FruitEnum.parse(Fruits.Cantaloupe);
FruitEnum.parse(Fruits.Apple);
FruitEnum.parse("apple");
FruitEnum.parse(0);
expect(() => FruitEnum.parse(1)).toThrow();
expect(() => FruitEnum.parse("Apple")).toThrow();
expect(() => FruitEnum.parse("Cantaloupe")).toThrow();
});
test("from const", () => {
const Greek = {
Alpha: "a",
Beta: "b",
Gamma: 3,
// @ts-ignore
} as const;
const GreekEnum = z.nativeEnum(Greek);
type _GreekEnum = z.infer<typeof GreekEnum>;
GreekEnum.parse("a");
GreekEnum.parse("b");
GreekEnum.parse(3);
expect(() => GreekEnum.parse("v")).toThrow();
expect(() => GreekEnum.parse("Alpha")).toThrow();
expect(() => GreekEnum.parse(2)).toThrow();
expect(GreekEnum.enum.Alpha).toEqual("a");
});

View File

@@ -0,0 +1,17 @@
import type { TSESTree } from '@typescript-eslint/utils';
import type { Key, MemberNode } from './types';
export interface ExtractedName {
key: Key;
codeName: string;
nameNode: TSESTree.Node;
}
/**
* Extracts the string name for a member.
* @returns `null` if the name cannot be extracted due to it being computed.
*/
export declare function extractNameForMember(node: MemberNode): ExtractedName | null;
/**
* Extracts the string property name for a member.
* @returns `null` if the name cannot be extracted due to it being a computed.
*/
export declare function extractNameForMemberExpression(node: TSESTree.MemberExpression): ExtractedName | null;

View File

@@ -0,0 +1,70 @@
import type * as errors from "./errors.js";
import type * as schemas from "./schemas.js";
import type { Class } from "./util.js";
type ZodTrait = {
_zod: {
def: any;
[k: string]: any;
};
};
export interface $constructor<T extends ZodTrait, D = T["_zod"]["def"]> {
new (def: D): T;
init(inst: T, def: D): asserts inst is T;
}
/** A special constant with type `never` */
export declare const NEVER: never;
export declare function $constructor<T extends ZodTrait, D = T["_zod"]["def"]>(name: string, initializer: (inst: T, def: D) => void, params?: {
Parent?: typeof Class;
}): $constructor<T, D>;
export declare const $brand: unique symbol;
export type $brand<T extends string | number | symbol = string | number | symbol> = {
[$brand]: {
[k in T]: true;
};
};
export type $ZodBranded<T extends schemas.SomeType, Brand extends string | number | symbol, Dir extends "in" | "out" | "inout" = "out"> = T & (Dir extends "inout" ? {
_zod: {
input: input<T> & $brand<Brand>;
output: output<T> & $brand<Brand>;
};
} : Dir extends "in" ? {
_zod: {
input: input<T> & $brand<Brand>;
};
} : {
_zod: {
output: output<T> & $brand<Brand>;
};
});
export type $ZodNarrow<T extends schemas.SomeType, Out> = T & {
_zod: {
output: Out;
};
};
export declare class $ZodAsyncError extends Error {
constructor();
}
export declare class $ZodEncodeError extends Error {
constructor(name: string);
}
export type input<T> = T extends {
_zod: {
input: any;
};
} ? T["_zod"]["input"] : unknown;
export type output<T> = T extends {
_zod: {
output: any;
};
} ? T["_zod"]["output"] : unknown;
export type { output as infer };
export interface $ZodConfig {
/** Custom error map. Overrides `config().localeError`. */
customError?: errors.$ZodErrorMap | undefined;
/** Localized error map. Lowest priority. */
localeError?: errors.$ZodErrorMap | undefined;
/** Disable JIT schema compilation. Useful in environments that disallow `eval`. */
jitless?: boolean | undefined;
}
export declare const globalConfig: $ZodConfig;
export declare function config(newConfig?: Partial<$ZodConfig>): $ZodConfig;