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,32 @@
import { W as WorkerGlobalState, a as WorkerSetupContext, B as BirpcOptions } from './chunks/worker.d.ZpHpO4yb.js';
import { T as Traces } from './chunks/traces.d.D2T_R8rx.js';
import { Awaitable } from '@vitest/utils';
import { ModuleRunner } from 'vite/module-runner';
import { R as RuntimeRPC } from './chunks/rpc.d.B_8sPU0w.js';
import '@vitest/runner';
import './chunks/config.d.A1h_Y6Jt.js';
import '@vitest/pretty-format';
import '@vitest/snapshot';
import '@vitest/utils/diff';
import './chunks/environment.d.CrsxCzP1.js';
/** @experimental */
declare function setupBaseEnvironment(context: WorkerSetupContext): Promise<() => Promise<void>>;
/** @experimental */
declare function runBaseTests(method: "run" | "collect", state: WorkerGlobalState, traces: Traces): Promise<void>;
type WorkerRpcOptions = Pick<BirpcOptions<RuntimeRPC>, "on" | "off" | "post" | "serialize" | "deserialize">;
interface VitestWorker extends WorkerRpcOptions {
runTests: (state: WorkerGlobalState, traces: Traces) => Awaitable<unknown>;
collectTests: (state: WorkerGlobalState, traces: Traces) => Awaitable<unknown>;
onModuleRunner?: (moduleRunner: ModuleRunner) => Awaitable<unknown>;
setup?: (context: WorkerSetupContext) => void | Promise<() => Promise<unknown>>;
}
interface Options extends VitestWorker {
teardown?: () => void;
}
/** @experimental */
declare function init(worker: Options): void;
export { init, runBaseTests, setupBaseEnvironment as setupEnvironment };

View File

@@ -0,0 +1,631 @@
import { expect, expectTypeOf, test } from "vitest";
import { z } from "zod/v4";
test("recursion with z.lazy", () => {
const data = {
name: "I",
subcategories: [
{
name: "A",
subcategories: [
{
name: "1",
subcategories: [
{
name: "a",
subcategories: [],
},
],
},
],
},
],
};
const Category = z.object({
name: z.string(),
get subcategories() {
return z.array(Category).optional().nullable();
},
});
type Category = z.infer<typeof Category>;
interface _Category {
name: string;
subcategories?: _Category[] | undefined | null;
}
expectTypeOf<Category>().toEqualTypeOf<_Category>();
Category.parse(data);
});
test("recursion involving union type", () => {
const data = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null,
},
},
},
};
const LL = z.object({
value: z.number(),
get next() {
return LL.nullable();
},
});
type LL = z.infer<typeof LL>;
type _LL = {
value: number;
next: _LL | null;
};
expectTypeOf<LL>().toEqualTypeOf<_LL>();
LL.parse(data);
});
test("mutual recursion - native", () => {
const Alazy = z.object({
val: z.number(),
get b() {
return Blazy;
},
});
const Blazy = z.object({
val: z.number(),
get a() {
return Alazy.optional();
},
});
const testData = {
val: 1,
b: {
val: 5,
a: {
val: 3,
b: {
val: 4,
a: {
val: 2,
b: {
val: 1,
},
},
},
},
},
};
type Alazy = z.infer<typeof Alazy>;
type Blazy = z.infer<typeof Blazy>;
interface _Alazy {
val: number;
b: _Blazy;
}
interface _Blazy {
val: number;
a?: _Alazy | undefined;
}
expectTypeOf<Alazy>().toEqualTypeOf<_Alazy>();
expectTypeOf<Blazy>().toEqualTypeOf<_Blazy>();
Alazy.parse(testData);
Blazy.parse(testData.b);
expect(() => Alazy.parse({ val: "asdf" })).toThrow();
});
test("pick and omit with getter", () => {
const Category = z.strictObject({
name: z.string(),
get subcategories() {
return z.array(Category);
},
});
type Category = z.infer<typeof Category>;
interface _Category {
name: string;
subcategories: _Category[];
}
expectTypeOf<Category>().toEqualTypeOf<_Category>();
// Shape should not surface `readonly` modifiers from getter-defined keys.
// object/strictObject/looseObject all pass shape through util.Writeable<T>.
type Shape = (typeof Category)["shape"];
expectTypeOf<Shape>().toEqualTypeOf<{ name: z.ZodString; subcategories: z.ZodArray<typeof Category> }>();
const PickedCategory = Category.pick({ name: true });
const OmittedCategory = Category.omit({ subcategories: true });
const picked = { name: "test" };
const omitted = { name: "test" };
PickedCategory.parse(picked);
OmittedCategory.parse(omitted);
expect(() => PickedCategory.parse({ name: "test", subcategories: [] })).toThrow();
expect(() => OmittedCategory.parse({ name: "test", subcategories: [] })).toThrow();
});
test("shape stays writeable through extend/safeExtend/partial/required", () => {
const Base = z.object({ name: z.string() });
const Extended = Base.extend({
get sub() {
return z.array(Extended);
},
});
type ExtendedShape = (typeof Extended)["shape"];
expectTypeOf<ExtendedShape>().toEqualTypeOf<{
name: z.ZodString;
sub: z.ZodArray<typeof Extended>;
}>();
const SafeExt = Base.safeExtend({ extra: z.string() } as const);
type SafeExtShape = (typeof SafeExt)["shape"];
expectTypeOf<SafeExtShape>().toEqualTypeOf<{
name: z.ZodString;
extra: z.ZodString;
}>();
const FromConst = Base.extend({ a: z.string(), b: z.number() } as const);
type FromConstShape = (typeof FromConst)["shape"];
expectTypeOf<FromConstShape>().toEqualTypeOf<{
name: z.ZodString;
a: z.ZodString;
b: z.ZodNumber;
}>();
const PartialExtended = Extended.partial();
type PartialShape = (typeof PartialExtended)["shape"];
expectTypeOf<PartialShape>().toEqualTypeOf<{
name: z.ZodOptional<z.ZodString>;
sub: z.ZodOptional<z.ZodArray<typeof Extended>>;
}>();
const RequiredExtended = Extended.required();
type RequiredShape = (typeof RequiredExtended)["shape"];
expectTypeOf<RequiredShape>().toEqualTypeOf<{
name: z.ZodNonOptional<z.ZodString>;
sub: z.ZodNonOptional<z.ZodArray<typeof Extended>>;
}>();
});
test("deferred self-recursion", () => {
const Feature = z.object({
title: z.string(),
get features(): z.ZodOptional<z.ZodArray<typeof Feature>> {
return z.optional(z.array(Feature)); //.optional();
},
});
// type Feature = z.infer<typeof Feature>;
const Output = z.object({
id: z.int(), //.nonnegative(),
name: z.string(),
get features(): z.ZodArray<typeof Feature> {
return Feature.array();
},
});
type Output = z.output<typeof Output>;
type _Feature = {
title: string;
features?: _Feature[] | undefined;
};
type _Output = {
id: number;
name: string;
features: _Feature[];
};
// expectTypeOf<Feature>().toEqualTypeOf<_Feature>();
expectTypeOf<Output>().toEqualTypeOf<_Output>();
});
test("deferred mutual recursion", () => {
const Slot = z.object({
slotCode: z.string(),
get blocks() {
return z.array(Block);
},
});
type Slot = z.infer<typeof Slot>;
const Block = z.object({
blockCode: z.string(),
get slots() {
return z.array(Slot).optional();
},
});
type Block = z.infer<typeof Block>;
const Page = z.object({
slots: z.array(Slot),
});
type Page = z.infer<typeof Page>;
type _Slot = {
slotCode: string;
blocks: _Block[];
};
type _Block = {
blockCode: string;
slots?: _Slot[] | undefined;
};
type _Page = {
slots: _Slot[];
};
expectTypeOf<Slot>().toEqualTypeOf<_Slot>();
expectTypeOf<Block>().toEqualTypeOf<_Block>();
expectTypeOf<Page>().toEqualTypeOf<_Page>();
});
test("mutual recursion with meta", () => {
const A = z
.object({
name: z.string(),
get b() {
return B;
},
})
.readonly()
.meta({ id: "A" })
.optional();
const B = z
.object({
name: z.string(),
get a() {
return A;
},
})
.readonly()
.meta({ id: "B" });
type A = z.infer<typeof A>;
type B = z.infer<typeof B>;
type _A =
| Readonly<{
name: string;
b: _B;
}>
| undefined;
// | undefined;
type _B = Readonly<{
name: string;
a?: _A;
}>;
expectTypeOf<A>().toEqualTypeOf<_A>();
expectTypeOf<B>().toEqualTypeOf<_B>();
});
test("intersection with recursive types", () => {
const A = z.discriminatedUnion("type", [
z.object({
type: z.literal("CONTAINER"),
}),
z.object({
type: z.literal("SCREEN"),
config: z.object({ x: z.number(), y: z.number() }),
}),
]);
// type A = z.infer<typeof A>;
const B = z.object({
get children() {
return z.array(C).optional();
},
});
// type B = z.infer<typeof B>;
const C = z.intersection(A, B);
type C = z.infer<typeof C>;
type _C = (
| {
type: "CONTAINER";
}
| {
type: "SCREEN";
config: {
x: number;
y: number;
};
}
) & {
children?: _C[] | undefined;
};
expectTypeOf<C>().toEqualTypeOf<_C>();
});
test("object utilities with recursive types", () => {
const NodeBase = z.object({
id: z.string(),
name: z.string(),
get children() {
return z.array(Node).optional();
},
});
// Test extend with new keys (extend throws when overwriting existing keys)
const NodeOne = NodeBase.extend({
name: z.literal("nodeOne"),
get children() {
return z.array(Node);
},
});
const NodeTwo = NodeBase.extend({
name: z.literal("nodeTwo"),
get children() {
return z.array(Node);
},
});
// Test pick
const PickedNode = NodeBase.pick({ id: true, name: true });
// Test omit
const OmittedNode = NodeBase.omit({ children: true });
// Test merge
const ExtraProps = {
metadata: z.string(),
get parent() {
return Node.optional();
},
};
const MergedNode = NodeBase.extend(ExtraProps);
// Test partial
const PartialNode = NodeBase.partial();
const PartialMaskedNode = NodeBase.partial({ name: true });
// Test required (assuming NodeBase has optional fields)
const OptionalNodeBase = z.object({
id: z.string().optional(),
name: z.string().optional(),
get children() {
return z.array(Node).optional();
},
});
const RequiredNode = OptionalNodeBase.required();
const RequiredMaskedNode = OptionalNodeBase.required({ id: true });
const Node = z.union([
NodeOne,
NodeTwo,
PickedNode,
OmittedNode,
MergedNode,
PartialNode,
PartialMaskedNode,
RequiredNode,
RequiredMaskedNode,
]);
});
test("tuple with recursive types", () => {
const TaskListNodeSchema = z.strictObject({
type: z.literal("taskList"),
get content() {
return z.array(z.tuple([TaskListNodeSchema, z.union([TaskListNodeSchema])])).min(1);
},
});
type TaskListNodeSchema = z.infer<typeof TaskListNodeSchema>;
type _TaskListNodeSchema = {
type: "taskList";
content: [_TaskListNodeSchema, _TaskListNodeSchema][];
};
expectTypeOf<TaskListNodeSchema>().toEqualTypeOf<_TaskListNodeSchema>();
});
test("recursion compatibility", () => {
// array
const A = z.object({
get array() {
return A.array();
},
get optional() {
return A.optional();
},
get nullable() {
return A.nullable();
},
get nonoptional() {
return A.nonoptional();
},
get readonly() {
return A.readonly();
},
get describe() {
return A.describe("A recursive type");
},
get meta() {
return A.meta({ description: "A recursive type" });
},
get pipe() {
return A.pipe(z.any());
},
get strict() {
return A.strict();
},
get tuple() {
return z.tuple([A, A]);
},
get object() {
return z
.object({
subcategories: A,
})
.strict()
.loose();
},
get union() {
return z.union([A, A]);
},
get intersection() {
return z.intersection(A, A);
},
get record() {
return z.record(z.string(), A);
},
get map() {
return z.map(z.string(), A);
},
get set() {
return z.set(A);
},
get lazy() {
return z.lazy(() => A);
},
get promise() {
return z.promise(A);
},
});
});
test("recursive object with .check()", () => {
const Category = z
.object({
id: z.string(),
name: z.string(),
get subcategories() {
return z.array(Category).optional();
},
})
.check((ctx) => {
// Check for duplicate IDs among direct subcategories
if (ctx.value.subcategories) {
const siblingIds = new Set<string>();
ctx.value.subcategories.forEach((sub, index) => {
if (siblingIds.has(sub.id)) {
ctx.issues.push({
code: "custom",
message: `Duplicate sibling ID found: ${sub.id}`,
path: ["subcategories", index, "id"],
input: ctx.value,
});
}
siblingIds.add(sub.id);
});
}
});
// Valid - siblings have unique IDs
const validData = {
id: "electronics",
name: "Electronics",
subcategories: [
{
id: "computers",
name: "Computers",
subcategories: [
{ id: "laptops", name: "Laptops" },
{ id: "desktops", name: "Desktops" },
],
},
{
id: "phones",
name: "Phones",
},
],
};
// Invalid - duplicate sibling IDs
const invalidData = {
id: "electronics",
name: "Electronics",
subcategories: [
{ id: "computers", name: "Computers" },
{ id: "phones", name: "Phones" },
{ id: "computers", name: "Computers Again" }, // Duplicate at index 2
],
};
expect(() => Category.parse(validData)).not.toThrow();
expect(() => Category.parse(invalidData)).toThrow();
});
// biome-ignore lint: sadf
export type RecursiveA = z.ZodUnion<
[
z.ZodObject<{
a: z.ZodDefault<RecursiveA>;
b: z.ZodPrefault<RecursiveA>;
c: z.ZodNonOptional<RecursiveA>;
d: z.ZodOptional<RecursiveA>;
e: z.ZodNullable<RecursiveA>;
g: z.ZodReadonly<RecursiveA>;
h: z.ZodPipe<RecursiveA, z.ZodString>;
i: z.ZodArray<RecursiveA>;
j: z.ZodSet<RecursiveA>;
k: z.ZodMap<RecursiveA, RecursiveA>;
l: z.ZodRecord<z.ZodString, RecursiveA>;
m: z.ZodUnion<[RecursiveA, RecursiveA]>;
n: z.ZodIntersection<RecursiveA, RecursiveA>;
o: z.ZodLazy<RecursiveA>;
p: z.ZodPromise<RecursiveA>;
q: z.ZodCatch<RecursiveA>;
r: z.ZodSuccess<RecursiveA>;
s: z.ZodTransform<RecursiveA, string>;
t: z.ZodTuple<[RecursiveA, RecursiveA]>;
u: z.ZodObject<{
a: RecursiveA;
}>;
}>,
]
>;
test("recursive type with `id` meta", () => {
const AType = z.object({
type: z.literal("a"),
name: z.string(),
});
const BType = z.object({
type: z.literal("b"),
name: z.string(),
});
const CType = z.object({
type: z.literal("c"),
name: z.string(),
});
const Schema = z.object({
type: z.literal("special").meta({ description: "Type" }),
config: z.object({
title: z.string().meta({ description: "Title" }),
get elements() {
return z.array(z.discriminatedUnion("type", [AType, BType, CType])).meta({
id: "SpecialElements",
title: "SpecialElements",
description: "Array of elements",
});
},
}),
});
Schema.parse({
type: "special",
config: {
title: "Special",
elements: [
{ type: "a", name: "John" },
{ type: "b", name: "Jane" },
{ type: "c", name: "Jim" },
],
},
});
});

View File

@@ -0,0 +1,166 @@
// https://www.postgresql.org/docs/current/protocol-message-formats.html
import BufferList from './buffer-list'
const buffers = {
readyForQuery: function () {
return new BufferList().add(Buffer.from('I')).join(true, 'Z')
},
authenticationOk: function () {
return new BufferList().addInt32(0).join(true, 'R')
},
authenticationCleartextPassword: function () {
return new BufferList().addInt32(3).join(true, 'R')
},
authenticationMD5Password: function () {
return new BufferList()
.addInt32(5)
.add(Buffer.from([1, 2, 3, 4]))
.join(true, 'R')
},
authenticationSASL: function () {
return new BufferList().addInt32(10).addCString('SCRAM-SHA-256').addCString('').join(true, 'R')
},
authenticationSASLContinue: function () {
return new BufferList().addInt32(11).addString('data').join(true, 'R')
},
authenticationSASLFinal: function () {
return new BufferList().addInt32(12).addString('data').join(true, 'R')
},
parameterStatus: function (name: string, value: string) {
return new BufferList().addCString(name).addCString(value).join(true, 'S')
},
backendKeyData: function (processID: number, secretKey: number) {
return new BufferList().addInt32(processID).addInt32(secretKey).join(true, 'K')
},
commandComplete: function (string: string) {
return new BufferList().addCString(string).join(true, 'C')
},
rowDescription: function (fields: any[]) {
fields = fields || []
const buf = new BufferList()
buf.addInt16(fields.length)
fields.forEach(function (field) {
buf
.addCString(field.name)
.addInt32(field.tableID || 0)
.addInt16(field.attributeNumber || 0)
.addInt32(field.dataTypeID || 0)
.addInt16(field.dataTypeSize || 0)
.addInt32(field.typeModifier || 0)
.addInt16(field.formatCode || 0)
})
return buf.join(true, 'T')
},
parameterDescription: function (dataTypeIDs: number[]) {
dataTypeIDs = dataTypeIDs || []
const buf = new BufferList()
buf.addInt16(dataTypeIDs.length)
dataTypeIDs.forEach(function (dataTypeID) {
buf.addInt32(dataTypeID)
})
return buf.join(true, 't')
},
dataRow: function (columns: any[]) {
columns = columns || []
const buf = new BufferList()
buf.addInt16(columns.length)
columns.forEach(function (col) {
if (col == null) {
buf.addInt32(-1)
} else {
const strBuf = Buffer.from(col, 'utf8')
buf.addInt32(strBuf.length)
buf.add(strBuf)
}
})
return buf.join(true, 'D')
},
error: function (fields: any) {
return buffers.errorOrNotice(fields).join(true, 'E')
},
notice: function (fields: any) {
return buffers.errorOrNotice(fields).join(true, 'N')
},
errorOrNotice: function (fields: any) {
fields = fields || []
const buf = new BufferList()
fields.forEach(function (field: any) {
buf.addChar(field.type)
buf.addCString(field.value)
})
return buf.add(Buffer.from([0])) // terminator
},
parseComplete: function () {
return new BufferList().join(true, '1')
},
bindComplete: function () {
return new BufferList().join(true, '2')
},
notification: function (id: number, channel: string, payload: string) {
return new BufferList().addInt32(id).addCString(channel).addCString(payload).join(true, 'A')
},
emptyQuery: function () {
return new BufferList().join(true, 'I')
},
portalSuspended: function () {
return new BufferList().join(true, 's')
},
closeComplete: function () {
return new BufferList().join(true, '3')
},
copyIn: function (cols: number) {
const list = new BufferList()
// text mode
.addByte(0)
// column count
.addInt16(cols)
for (let i = 0; i < cols; i++) {
list.addInt16(i)
}
return list.join(true, 'G')
},
copyOut: function (cols: number) {
const list = new BufferList()
// text mode
.addByte(0)
// column count
.addInt16(cols)
for (let i = 0; i < cols; i++) {
list.addInt16(i)
}
return list.join(true, 'H')
},
copyData: function (bytes: Buffer) {
return new BufferList().add(bytes).join(true, 'd')
},
copyDone: function () {
return new BufferList().join(true, 'c')
},
}
export default buffers

View File

@@ -0,0 +1,28 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es5" />
/// <reference lib="es2015.core" />
/// <reference lib="es2015.collection" />
/// <reference lib="es2015.iterable" />
/// <reference lib="es2015.generator" />
/// <reference lib="es2015.promise" />
/// <reference lib="es2015.proxy" />
/// <reference lib="es2015.reflect" />
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.symbol.wellknown" />

View File

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

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_ts_dispose_resources.js";

View File

@@ -0,0 +1,35 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// SEE https://typescript-eslint.io/users/configs
//
// For developers working in the typescript-eslint monorepo:
// You can regenerate it using `pnpm run generate-configs`
module.exports = {
extends: ['./configs/eslintrc/base', './configs/eslintrc/eslint-recommended'],
rules: {
'@typescript-eslint/ban-ts-comment': 'error',
'no-array-constructor': 'off',
'@typescript-eslint/no-array-constructor': 'error',
'@typescript-eslint/no-duplicate-enum-values': 'error',
'@typescript-eslint/no-empty-object-type': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-extra-non-null-assertion': 'error',
'@typescript-eslint/no-misused-new': 'error',
'@typescript-eslint/no-namespace': 'error',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'error',
'@typescript-eslint/no-require-imports': 'error',
'@typescript-eslint/no-this-alias': 'error',
'@typescript-eslint/no-unnecessary-type-constraint': 'error',
'@typescript-eslint/no-unsafe-declaration-merging': 'error',
'@typescript-eslint/no-unsafe-function-type': 'error',
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 'error',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-wrapper-object-types': 'error',
'@typescript-eslint/prefer-as-const': 'error',
'@typescript-eslint/prefer-namespace-keyword': 'error',
'@typescript-eslint/triple-slash-reference': 'error',
},
};

View File

@@ -0,0 +1,412 @@
"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.LRUCache = exports.LinkedMap = exports.Touch = void 0;
var Touch;
(function (Touch) {
Touch.None = 0;
Touch.First = 1;
Touch.AsOld = Touch.First;
Touch.Last = 2;
Touch.AsNew = Touch.Last;
})(Touch || (exports.Touch = Touch = {}));
class LinkedMap {
[Symbol.toStringTag] = 'LinkedMap';
_map;
_head;
_tail;
_size;
_state;
constructor() {
this._map = new Map();
this._head = undefined;
this._tail = undefined;
this._size = 0;
this._state = 0;
}
clear() {
this._map.clear();
this._head = undefined;
this._tail = undefined;
this._size = 0;
this._state++;
}
isEmpty() {
return !this._head && !this._tail;
}
get size() {
return this._size;
}
get first() {
return this._head?.value;
}
get last() {
return this._tail?.value;
}
before(key) {
const item = this._map.get(key);
return item ? item.previous?.value : undefined;
}
after(key) {
const item = this._map.get(key);
return item ? item.next?.value : undefined;
}
has(key) {
return this._map.has(key);
}
get(key, touch = Touch.None) {
const item = this._map.get(key);
if (!item) {
return undefined;
}
if (touch !== Touch.None) {
this.touch(item, touch);
}
return item.value;
}
set(key, value, touch = Touch.None) {
let item = this._map.get(key);
if (item) {
item.value = value;
if (touch !== Touch.None) {
this.touch(item, touch);
}
}
else {
item = { key, value, next: undefined, previous: undefined };
switch (touch) {
case Touch.None:
this.addItemLast(item);
break;
case Touch.First:
this.addItemFirst(item);
break;
case Touch.Last:
this.addItemLast(item);
break;
default:
this.addItemLast(item);
break;
}
this._map.set(key, item);
this._size++;
}
return this;
}
delete(key) {
return !!this.remove(key);
}
remove(key) {
const item = this._map.get(key);
if (!item) {
return undefined;
}
this._map.delete(key);
this.removeItem(item);
this._size--;
return item.value;
}
shift() {
if (!this._head && !this._tail) {
return undefined;
}
if (!this._head || !this._tail) {
throw new Error('Invalid list');
}
const item = this._head;
this._map.delete(item.key);
this.removeItem(item);
this._size--;
return item.value;
}
forEach(callbackfn, thisArg) {
const state = this._state;
let current = this._head;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
}
else {
callbackfn(current.value, current.key, this);
}
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
current = current.next;
}
}
keys() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: () => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: current.key, done: false };
current = current.next;
return result;
}
else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
values() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: () => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: current.value, done: false };
current = current.next;
return result;
}
else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
entries() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: () => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: [current.key, current.value], done: false };
current = current.next;
return result;
}
else {
return { value: undefined, done: true };
}
}
};
return iterator;
}
[Symbol.iterator]() {
return this.entries();
}
trimOld(newSize) {
if (newSize >= this.size) {
return;
}
if (newSize === 0) {
this.clear();
return;
}
let current = this._head;
let currentSize = this.size;
while (current && currentSize > newSize) {
this._map.delete(current.key);
current = current.next;
currentSize--;
}
this._head = current;
this._size = currentSize;
if (current) {
current.previous = undefined;
}
this._state++;
}
addItemFirst(item) {
// First time Insert
if (!this._head && !this._tail) {
this._tail = item;
}
else if (!this._head) {
throw new Error('Invalid list');
}
else {
item.next = this._head;
this._head.previous = item;
}
this._head = item;
this._state++;
}
addItemLast(item) {
// First time Insert
if (!this._head && !this._tail) {
this._head = item;
}
else if (!this._tail) {
throw new Error('Invalid list');
}
else {
item.previous = this._tail;
this._tail.next = item;
}
this._tail = item;
this._state++;
}
removeItem(item) {
if (item === this._head && item === this._tail) {
this._head = undefined;
this._tail = undefined;
}
else if (item === this._head) {
// This can only happened if size === 1 which is handle
// by the case above.
if (!item.next) {
throw new Error('Invalid list');
}
item.next.previous = undefined;
this._head = item.next;
}
else if (item === this._tail) {
// This can only happened if size === 1 which is handle
// by the case above.
if (!item.previous) {
throw new Error('Invalid list');
}
item.previous.next = undefined;
this._tail = item.previous;
}
else {
const next = item.next;
const previous = item.previous;
if (!next || !previous) {
throw new Error('Invalid list');
}
next.previous = previous;
previous.next = next;
}
item.next = undefined;
item.previous = undefined;
this._state++;
}
touch(item, touch) {
if (!this._head || !this._tail) {
throw new Error('Invalid list');
}
if ((touch !== Touch.First && touch !== Touch.Last)) {
return;
}
if (touch === Touch.First) {
if (item === this._head) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item
if (item === this._tail) {
// previous must be defined since item was not head but is tail
// So there are more than on item in the map
previous.next = undefined;
this._tail = previous;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next.previous = previous;
previous.next = next;
}
// Insert the node at head
item.previous = undefined;
item.next = this._head;
this._head.previous = item;
this._head = item;
this._state++;
}
else if (touch === Touch.Last) {
if (item === this._tail) {
return;
}
const next = item.next;
const previous = item.previous;
// Unlink the item.
if (item === this._head) {
// next must be defined since item was not tail but is head
// So there are more than on item in the map
next.previous = undefined;
this._head = next;
}
else {
// Both next and previous are not undefined since item was neither head nor tail.
next.previous = previous;
previous.next = next;
}
item.next = undefined;
item.previous = this._tail;
this._tail.next = item;
this._tail = item;
this._state++;
}
}
toJSON() {
const data = [];
this.forEach((value, key) => {
data.push([key, value]);
});
return data;
}
fromJSON(data) {
this.clear();
for (const [key, value] of data) {
this.set(key, value);
}
}
}
exports.LinkedMap = LinkedMap;
class LRUCache extends LinkedMap {
_limit;
_ratio;
constructor(limit, ratio = 1) {
super();
this._limit = limit;
this._ratio = Math.min(Math.max(0, ratio), 1);
}
get limit() {
return this._limit;
}
set limit(limit) {
this._limit = limit;
this.checkTrim();
}
get ratio() {
return this._ratio;
}
set ratio(ratio) {
this._ratio = Math.min(Math.max(0, ratio), 1);
this.checkTrim();
}
get(key, touch = Touch.AsNew) {
return super.get(key, touch);
}
peek(key) {
return super.get(key, Touch.None);
}
set(key, value) {
super.set(key, value, Touch.Last);
this.checkTrim();
return this;
}
checkTrim() {
if (this.size > this._limit) {
this.trimOld(Math.round(this._limit * this._ratio));
}
}
}
exports.LRUCache = LRUCache;

View File

@@ -0,0 +1,38 @@
{
"name": "estree-walker",
"description": "Traverse an ESTree-compliant AST",
"version": "3.0.3",
"private": false,
"author": "Rich Harris",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Rich-Harris/estree-walker"
},
"type": "module",
"module": "./src/index.js",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./types/index.d.ts",
"import": "./src/index.js"
}
},
"types": "types/index.d.ts",
"scripts": {
"prepublishOnly": "tsc && npm test",
"test": "uvu test"
},
"dependencies": {
"@types/estree": "^1.0.0"
},
"devDependencies": {
"typescript": "^4.9.0",
"uvu": "^0.5.1"
},
"files": [
"src",
"types",
"README.md"
]
}

View File

@@ -0,0 +1,357 @@
# pg-pool
[![Build Status](https://travis-ci.org/brianc/node-pg-pool.svg?branch=master)](https://travis-ci.org/brianc/node-pg-pool)
A connection pool for node-postgres
## install
```sh
npm i pg-pool pg
```
## use
### create
to use pg-pool you must first create an instance of a pool
```js
const Pool = require('pg-pool')
// by default the pool uses the same
// configuration as whatever `pg` version you have installed
const pool = new Pool()
// you can pass properties to the pool
// these properties are passed unchanged to both the node-postgres Client constructor
// and the pool constructor, allowing you to fully configure the behavior of both
const pool2 = new Pool({
database: 'postgres',
user: 'brianc',
password: 'secret!',
port: 5432,
ssl: true,
max: 20, // set pool max size to 20
idleTimeoutMillis: 1000, // close idle clients after 1 second
connectionTimeoutMillis: 1000, // return an error after 1 second if connection could not be established
maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion)
})
// you can supply a custom client constructor
// if you want to use the native postgres client
const NativeClient = require('pg').native.Client
const nativePool = new Pool({ Client: NativeClient })
// you can even pool pg-native clients directly
const PgNativeClient = require('pg-native')
const pgNativePool = new Pool({ Client: PgNativeClient })
```
##### Note:
The Pool constructor does not support passing a Database URL as the parameter. To use pg-pool on heroku, for example, you need to parse the URL into a config object. Here is an example of how to parse a Database URL.
```js
const Pool = require('pg-pool')
const url = require('url')
const params = url.parse(process.env.DATABASE_URL)
const auth = params.auth.split(':')
const config = {
user: auth[0],
password: auth[1],
host: params.hostname,
port: params.port,
database: params.pathname.split('/')[1],
ssl: true,
}
const pool = new Pool(config)
/*
Transforms, 'postgres://DBuser:secret@DBHost:#####/myDB', into
config = {
user: 'DBuser',
password: 'secret',
host: 'DBHost',
port: '#####',
database: 'myDB',
ssl: true
}
*/
```
### acquire clients with a promise
pg-pool supports a fully promise-based api for acquiring clients
```js
const pool = new Pool()
pool.connect().then((client) => {
client
.query('select $1::text as name', ['pg-pool'])
.then((res) => {
client.release()
console.log('hello from', res.rows[0].name)
})
.catch((e) => {
client.release()
console.error('query error', e.message, e.stack)
})
})
```
### plays nice with async/await
this ends up looking much nicer if you're using [co](https://github.com/tj/co) or async/await:
```js
// with async/await
;(async () => {
const pool = new Pool()
const client = await pool.connect()
try {
const result = await client.query('select $1::text as name', ['brianc'])
console.log('hello from', result.rows[0])
} finally {
client.release()
}
})().catch((e) => console.error(e.message, e.stack))
// with co
co(function* () {
const client = yield pool.connect()
try {
const result = yield client.query('select $1::text as name', ['brianc'])
console.log('hello from', result.rows[0])
} finally {
client.release()
}
}).catch((e) => console.error(e.message, e.stack))
```
### your new favorite helper method
because its so common to just run a query and return the client to the pool afterward pg-pool has this built-in:
```js
const pool = new Pool()
const time = await pool.query('SELECT NOW()')
const name = await pool.query('select $1::text as name', ['brianc'])
console.log(name.rows[0].name, 'says hello at', time.rows[0].now)
```
you can also use a callback here if you'd like:
```js
const pool = new Pool()
pool.query('SELECT $1::text as name', ['brianc'], function (err, res) {
console.log(res.rows[0].name) // brianc
})
```
**pro tip:** unless you need to run a transaction (which requires a single client for multiple queries) or you
have some other edge case like [streaming rows](https://github.com/brianc/node-pg-query-stream) or using a [cursor](https://github.com/brianc/node-pg-cursor)
you should almost always just use `pool.query`. Its easy, it does the right thing :tm:, and wont ever forget to return
clients back to the pool after the query is done.
### drop-in backwards compatible
pg-pool still and will always support the traditional callback api for acquiring a client. This is the exact API node-postgres has shipped with for years:
```js
const pool = new Pool()
pool.connect((err, client, done) => {
if (err) return done(err)
client.query('SELECT $1::text as name', ['pg-pool'], (err, res) => {
done()
if (err) {
return console.error('query error', err.message, err.stack)
}
console.log('hello from', res.rows[0].name)
})
})
```
### shut it down
When you are finished with the pool if all the clients are idle the pool will close them after `config.idleTimeoutMillis` and your app
will shutdown gracefully. If you don't want to wait for the timeout you can end the pool as follows:
```js
const pool = new Pool()
const client = await pool.connect()
console.log(await client.query('select now()'))
client.release()
await pool.end()
```
### a note on instances
The pool should be a **long-lived object** in your application. Generally you'll want to instantiate one pool when your app starts up and use the same instance of the pool throughout the lifetime of your application. If you are frequently creating a new pool within your code you likely don't have your pool initialization code in the correct place. Example:
```js
// assume this is a file in your program at ./your-app/lib/db.js
// correct usage: create the pool and let it live
// 'globally' here, controlling access to it through exported methods
const pool = new pg.Pool()
// this is the right way to export the query method
module.exports.query = (text, values) => {
console.log('query:', text, values)
return pool.query(text, values)
}
// this would be the WRONG way to export the connect method
module.exports.connect = () => {
// notice how we would be creating a pool instance here
// every time we called 'connect' to get a new client?
// that's a bad thing & results in creating an unbounded
// number of pools & therefore connections
const aPool = new pg.Pool()
return aPool.connect()
}
```
### events
Every instance of a `Pool` is an event emitter. These instances emit the following events:
#### error
Emitted whenever an idle client in the pool encounters an error. This is common when your PostgreSQL server shuts down, reboots, or a network partition otherwise causes it to become unavailable while your pool has connected clients.
Example:
```js
const Pool = require('pg-pool')
const pool = new Pool()
// attach an error handler to the pool for when a connected, idle client
// receives an error by being disconnected, etc
pool.on('error', function (error, client) {
// handle this in the same way you would treat process.on('uncaughtException')
// it is supplied the error as well as the idle client which received the error
})
```
#### connect
Fired whenever the pool creates a **new** `pg.Client` instance and successfully connects it to the backend.
Example:
```js
const Pool = require('pg-pool')
const pool = new Pool()
const count = 0
pool.on('connect', (client) => {
client.count = count++
})
pool
.connect()
.then((client) => {
return client
.query('SELECT $1::int AS "clientCount"', [client.count])
.then((res) => console.log(res.rows[0].clientCount)) // outputs 0
.then(() => client)
})
.then((client) => client.release())
```
#### acquire
Fired whenever a client is acquired from the pool
Example:
This allows you to count the number of clients which have ever been acquired from the pool.
```js
const Pool = require('pg-pool')
const pool = new Pool()
const acquireCount = 0
pool.on('acquire', function (client) {
acquireCount++
})
const connectCount = 0
pool.on('connect', function () {
connectCount++
})
for (let i = 0; i < 200; i++) {
pool.query('SELECT NOW()')
}
setTimeout(function () {
console.log('connect count:', connectCount) // output: connect count: 10
console.log('acquire count:', acquireCount) // output: acquire count: 200
}, 100)
```
### environment variables
pg-pool & node-postgres support some of the same environment variables as `psql` supports. The most common are:
```
PGDATABASE=my_db
PGUSER=username
PGPASSWORD="my awesome password"
PGPORT=5432
PGSSLMODE=require
```
Usually I will export these into my local environment via a `.env` file with environment settings or export them in `~/.bash_profile` or something similar. This way I get configurability which works with both the postgres suite of tools (`psql`, `pg_dump`, `pg_restore`) and node, I can vary the environment variables locally and in production, and it supports the concept of a [12-factor app](http://12factor.net/) out of the box.
## maxUses and read-replica autoscaling (e.g. AWS Aurora)
The maxUses config option can help an application instance rebalance load against a replica set that has been auto-scaled after the connection pool is already full of healthy connections.
The mechanism here is that a connection is considered "expended" after it has been acquired and released `maxUses` number of times. Depending on the load on your system, this means there will be an approximate time in which any given connection will live, thus creating a window for rebalancing.
Imagine a scenario where you have 10 app instances providing an API running against a replica cluster of 3 that are accessed via a round-robin DNS entry. Each instance runs a connection pool size of 20. With an ambient load of 50 requests per second, the connection pool will likely fill up in a few minutes with healthy connections.
If you have weekly bursts of traffic which peak at 1,000 requests per second, you might want to grow your replicas to 10 during this period. Without setting `maxUses`, the new replicas will not be adopted by the app servers without an intervention -- namely, restarting each in turn in order to build up new connection pools that are balanced against all the replicas. Adding additional app server instances will help to some extent because they will adopt all the replicas in an even way, but the initial app servers will continue to focus additional load on the original replicas.
This is where the `maxUses` configuration option comes into play. Setting `maxUses` to 7500 will ensure that over a period of 30 minutes or so the new replicas will be adopted as the pre-existing connections are closed and replaced with new ones, thus creating a window for eventual balance.
You'll want to test based on your own scenarios, but one way to make a first guess at `maxUses` is to identify an acceptable window for rebalancing and then solve for the value:
```
maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize
```
In the example above, assuming we acquire and release 1 connection per request and we are aiming for a 30 minute rebalancing window:
```
maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize
7200 = 1800 * 1000 / 10 / 25
```
## tests
To run tests clone the repo, `npm i` in the working dir, and then run `npm test`
## contributions
I love contributions. Please make sure they have tests, and submit a PR. If you're not sure if the issue is worth it or will be accepted it never hurts to open an issue to begin the conversation. If you're interested in keeping up with node-postgres releated stuff, you can follow me on twitter at [@briancarlson](https://twitter.com/briancarlson) - I generally announce any noteworthy updates there.
## license
The MIT License (MIT)
Copyright (c) 2016 Brian M. Carlson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_class_static_private_method_get.js";

View File

@@ -0,0 +1,897 @@
export interface Node {
start: number
end: number
type: string
range?: [number, number]
loc?: SourceLocation | null
}
export interface SourceLocation {
source?: string | null
start: Position
end: Position
}
export interface Position {
/** 1-based */
line: number
/** 0-based */
column: number
}
export interface Identifier extends Node {
type: "Identifier"
name: string
}
export interface Literal extends Node {
type: "Literal"
value?: string | boolean | null | number | RegExp | bigint
raw?: string
regex?: {
pattern: string
flags: string
}
bigint?: string
}
export interface Program extends Node {
type: "Program"
body: Array<Statement | ModuleDeclaration>
sourceType: "script" | "module"
}
export interface Function extends Node {
id?: Identifier | null
params: Array<Pattern>
body: BlockStatement | Expression
generator: boolean
expression: boolean
async: boolean
}
export interface ExpressionStatement extends Node {
type: "ExpressionStatement"
expression: Expression | Literal
directive?: string
}
export interface BlockStatement extends Node {
type: "BlockStatement"
body: Array<Statement>
}
export interface EmptyStatement extends Node {
type: "EmptyStatement"
}
export interface DebuggerStatement extends Node {
type: "DebuggerStatement"
}
export interface WithStatement extends Node {
type: "WithStatement"
object: Expression
body: Statement
}
export interface ReturnStatement extends Node {
type: "ReturnStatement"
argument?: Expression | null
}
export interface LabeledStatement extends Node {
type: "LabeledStatement"
label: Identifier
body: Statement
}
export interface BreakStatement extends Node {
type: "BreakStatement"
label?: Identifier | null
}
export interface ContinueStatement extends Node {
type: "ContinueStatement"
label?: Identifier | null
}
export interface IfStatement extends Node {
type: "IfStatement"
test: Expression
consequent: Statement
alternate?: Statement | null
}
export interface SwitchStatement extends Node {
type: "SwitchStatement"
discriminant: Expression
cases: Array<SwitchCase>
}
export interface SwitchCase extends Node {
type: "SwitchCase"
test?: Expression | null
consequent: Array<Statement>
}
export interface ThrowStatement extends Node {
type: "ThrowStatement"
argument: Expression
}
export interface TryStatement extends Node {
type: "TryStatement"
block: BlockStatement
handler?: CatchClause | null
finalizer?: BlockStatement | null
}
export interface CatchClause extends Node {
type: "CatchClause"
param?: Pattern | null
body: BlockStatement
}
export interface WhileStatement extends Node {
type: "WhileStatement"
test: Expression
body: Statement
}
export interface DoWhileStatement extends Node {
type: "DoWhileStatement"
body: Statement
test: Expression
}
export interface ForStatement extends Node {
type: "ForStatement"
init?: VariableDeclaration | Expression | null
test?: Expression | null
update?: Expression | null
body: Statement
}
export interface ForInStatement extends Node {
type: "ForInStatement"
left: VariableDeclaration | Pattern
right: Expression
body: Statement
}
export interface FunctionDeclaration extends Function {
type: "FunctionDeclaration"
id: Identifier
body: BlockStatement
}
export interface VariableDeclaration extends Node {
type: "VariableDeclaration"
declarations: Array<VariableDeclarator>
kind: "var" | "let" | "const" | "using" | "await using"
}
export interface VariableDeclarator extends Node {
type: "VariableDeclarator"
id: Pattern
init?: Expression | null
}
export interface ThisExpression extends Node {
type: "ThisExpression"
}
export interface ArrayExpression extends Node {
type: "ArrayExpression"
elements: Array<Expression | SpreadElement | null>
}
export interface ObjectExpression extends Node {
type: "ObjectExpression"
properties: Array<Property | SpreadElement>
}
export interface Property extends Node {
type: "Property"
key: Expression
value: Expression
kind: "init" | "get" | "set"
method: boolean
shorthand: boolean
computed: boolean
}
export interface FunctionExpression extends Function {
type: "FunctionExpression"
body: BlockStatement
}
export interface UnaryExpression extends Node {
type: "UnaryExpression"
operator: UnaryOperator
prefix: boolean
argument: Expression
}
export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"
export interface UpdateExpression extends Node {
type: "UpdateExpression"
operator: UpdateOperator
argument: Expression
prefix: boolean
}
export type UpdateOperator = "++" | "--"
export interface BinaryExpression extends Node {
type: "BinaryExpression"
operator: BinaryOperator
left: Expression | PrivateIdentifier
right: Expression
}
export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**"
export interface AssignmentExpression extends Node {
type: "AssignmentExpression"
operator: AssignmentOperator
left: Pattern
right: Expression
}
export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??="
export interface LogicalExpression extends Node {
type: "LogicalExpression"
operator: LogicalOperator
left: Expression
right: Expression
}
export type LogicalOperator = "||" | "&&" | "??"
export interface MemberExpression extends Node {
type: "MemberExpression"
object: Expression | Super
property: Expression | PrivateIdentifier
computed: boolean
optional: boolean
}
export interface ConditionalExpression extends Node {
type: "ConditionalExpression"
test: Expression
alternate: Expression
consequent: Expression
}
export interface CallExpression extends Node {
type: "CallExpression"
callee: Expression | Super
arguments: Array<Expression | SpreadElement>
optional: boolean
}
export interface NewExpression extends Node {
type: "NewExpression"
callee: Expression
arguments: Array<Expression | SpreadElement>
}
export interface SequenceExpression extends Node {
type: "SequenceExpression"
expressions: Array<Expression>
}
export interface ForOfStatement extends Node {
type: "ForOfStatement"
left: VariableDeclaration | Pattern
right: Expression
body: Statement
await: boolean
}
export interface Super extends Node {
type: "Super"
}
export interface SpreadElement extends Node {
type: "SpreadElement"
argument: Expression
}
export interface ArrowFunctionExpression extends Function {
type: "ArrowFunctionExpression"
}
export interface YieldExpression extends Node {
type: "YieldExpression"
argument?: Expression | null
delegate: boolean
}
export interface TemplateLiteral extends Node {
type: "TemplateLiteral"
quasis: Array<TemplateElement>
expressions: Array<Expression>
}
export interface TaggedTemplateExpression extends Node {
type: "TaggedTemplateExpression"
tag: Expression
quasi: TemplateLiteral
}
export interface TemplateElement extends Node {
type: "TemplateElement"
tail: boolean
value: {
cooked?: string | null
raw: string
}
}
export interface AssignmentProperty extends Node {
type: "Property"
key: Expression
value: Pattern
kind: "init"
method: false
shorthand: boolean
computed: boolean
}
export interface ObjectPattern extends Node {
type: "ObjectPattern"
properties: Array<AssignmentProperty | RestElement>
}
export interface ArrayPattern extends Node {
type: "ArrayPattern"
elements: Array<Pattern | null>
}
export interface RestElement extends Node {
type: "RestElement"
argument: Pattern
}
export interface AssignmentPattern extends Node {
type: "AssignmentPattern"
left: Pattern
right: Expression
}
export interface Class extends Node {
id?: Identifier | null
superClass?: Expression | null
body: ClassBody
}
export interface ClassBody extends Node {
type: "ClassBody"
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>
}
export interface MethodDefinition extends Node {
type: "MethodDefinition"
key: Expression | PrivateIdentifier
value: FunctionExpression
kind: "constructor" | "method" | "get" | "set"
computed: boolean
static: boolean
}
export interface ClassDeclaration extends Class {
type: "ClassDeclaration"
id: Identifier
}
export interface ClassExpression extends Class {
type: "ClassExpression"
}
export interface MetaProperty extends Node {
type: "MetaProperty"
meta: Identifier
property: Identifier
}
export interface ImportDeclaration extends Node {
type: "ImportDeclaration"
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>
source: Literal
attributes: Array<ImportAttribute>
}
export interface ImportSpecifier extends Node {
type: "ImportSpecifier"
imported: Identifier | Literal
local: Identifier
}
export interface ImportDefaultSpecifier extends Node {
type: "ImportDefaultSpecifier"
local: Identifier
}
export interface ImportNamespaceSpecifier extends Node {
type: "ImportNamespaceSpecifier"
local: Identifier
}
export interface ImportAttribute extends Node {
type: "ImportAttribute"
key: Identifier | Literal
value: Literal
}
export interface ExportNamedDeclaration extends Node {
type: "ExportNamedDeclaration"
declaration?: Declaration | null
specifiers: Array<ExportSpecifier>
source?: Literal | null
attributes: Array<ImportAttribute>
}
export interface ExportSpecifier extends Node {
type: "ExportSpecifier"
exported: Identifier | Literal
local: Identifier | Literal
}
export interface AnonymousFunctionDeclaration extends Function {
type: "FunctionDeclaration"
id: null
body: BlockStatement
}
export interface AnonymousClassDeclaration extends Class {
type: "ClassDeclaration"
id: null
}
export interface ExportDefaultDeclaration extends Node {
type: "ExportDefaultDeclaration"
declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression
}
export interface ExportAllDeclaration extends Node {
type: "ExportAllDeclaration"
source: Literal
exported?: Identifier | Literal | null
attributes: Array<ImportAttribute>
}
export interface AwaitExpression extends Node {
type: "AwaitExpression"
argument: Expression
}
export interface ChainExpression extends Node {
type: "ChainExpression"
expression: MemberExpression | CallExpression
}
export interface ImportExpression extends Node {
type: "ImportExpression"
source: Expression
options: Expression | null
}
export interface ParenthesizedExpression extends Node {
type: "ParenthesizedExpression"
expression: Expression
}
export interface PropertyDefinition extends Node {
type: "PropertyDefinition"
key: Expression | PrivateIdentifier
value?: Expression | null
computed: boolean
static: boolean
}
export interface PrivateIdentifier extends Node {
type: "PrivateIdentifier"
name: string
}
export interface StaticBlock extends Node {
type: "StaticBlock"
body: Array<Statement>
}
export type Statement =
| ExpressionStatement
| BlockStatement
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| Declaration
export type Declaration =
| FunctionDeclaration
| VariableDeclaration
| ClassDeclaration
export type Expression =
| Identifier
| Literal
| ThisExpression
| ArrayExpression
| ObjectExpression
| FunctionExpression
| UnaryExpression
| UpdateExpression
| BinaryExpression
| AssignmentExpression
| LogicalExpression
| MemberExpression
| ConditionalExpression
| CallExpression
| NewExpression
| SequenceExpression
| ArrowFunctionExpression
| YieldExpression
| TemplateLiteral
| TaggedTemplateExpression
| ClassExpression
| MetaProperty
| AwaitExpression
| ChainExpression
| ImportExpression
| ParenthesizedExpression
export type Pattern =
| Identifier
| MemberExpression
| ObjectPattern
| ArrayPattern
| RestElement
| AssignmentPattern
export type ModuleDeclaration =
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration
/**
* This interface is only used for defining {@link AnyNode}.
* It exists so that it can be extended by plugins:
*
* @example
* ```typescript
* declare module 'acorn' {
* interface NodeTypes {
* pluginName: FirstNode | SecondNode | ThirdNode | ... | LastNode
* }
* }
* ```
*/
interface NodeTypes {
core: Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportAttribute | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock | VariableDeclarator
}
export type AnyNode = NodeTypes[keyof NodeTypes]
export function parse(input: string, options: Options): Program
export function parseExpressionAt(input: string, pos: number, options: Options): Expression
export function tokenizer(input: string, options: Options): {
getToken(): Token
[Symbol.iterator](): Iterator<Token>
}
export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026 | "latest"
export interface Options {
/**
* `ecmaVersion` indicates the ECMAScript version to parse. Can be a
* number, either in year (`2022`) or plain version number (`6`) form,
* or `"latest"` (the latest the library supports). This influences
* support for strict mode, the set of reserved words, and support for
* new syntax features.
*/
ecmaVersion: ecmaVersion
/**
* `sourceType` indicates the mode the code should be parsed in.
* Can be either `"script"`, `"module"` or `"commonjs"`. This influences global
* strict mode and parsing of `import` and `export` declarations.
*/
sourceType?: "script" | "module" | "commonjs"
/**
* When set to true, enable strict parsing mode even if `sourceType`
* is `"script"`.
*/
strict?: boolean
/**
* a callback that will be called when a semicolon is automatically inserted.
* @param lastTokEnd the position of the comma as an offset
* @param lastTokEndLoc location if {@link locations} is enabled
*/
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
/**
* similar to `onInsertedSemicolon`, but for trailing commas
* @param lastTokEnd the position of the comma as an offset
* @param lastTokEndLoc location if `locations` is enabled
*/
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
/**
* By default, reserved words are only enforced if ecmaVersion >= 5.
* Set `allowReserved` to a boolean value to explicitly turn this on
* an off. When this option has the value "never", reserved words
* and keywords can also not be used as property names.
*/
allowReserved?: boolean | "never"
/**
* When enabled, a return at the top level is not considered an error.
*/
allowReturnOutsideFunction?: boolean
/**
* When enabled, import/export statements are not constrained to
* appearing at the top of the program, and an import.meta expression
* in a script isn't considered an error.
*/
allowImportExportEverywhere?: boolean
/**
* By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022.
* When enabled, await identifiers are allowed to appear at the top-level scope,
* but they are still not allowed in non-async functions.
*/
allowAwaitOutsideFunction?: boolean
/**
* When enabled, super identifiers are not constrained to
* appearing in methods and do not raise an error when they appear elsewhere.
*/
allowSuperOutsideMethod?: boolean
/**
* When enabled, hashbang directive in the beginning of file is
* allowed and treated as a line comment. Enabled by default when
* {@link ecmaVersion} >= 2023.
*/
allowHashBang?: boolean
/**
* By default, the parser will verify that private properties are
* only used in places where they are valid and have been declared.
* Set this to false to turn such checks off.
*/
checkPrivateFields?: boolean
/**
* When `locations` is on, `loc` properties holding objects with
* `start` and `end` properties as {@link Position} objects will be attached to the
* nodes.
*/
locations?: boolean
/**
* Pass an optional `{line, column}` object to use for the start of
* the parse. This is mostly useful when using `parseExpressionAt`
* with `locations: true`, to prevent the parser from having to
* determine the line position at the start position.
*/
startLocation?: {line: number, column: number}
/**
* a callback that will cause Acorn to call that export function with object in the same
* format as tokens returned from `tokenizer().getToken()`. Note
* that you are not allowed to call the parser from the
* callback—that will corrupt its internal state.
*/
onToken?: ((token: Token) => void) | Token[]
/**
* This takes a export function or an array.
*
* When a export function is passed, Acorn will call that export function with `(block, text, start,
* end)` parameters whenever a comment is skipped. `block` is a
* boolean indicating whether this is a block (`/* *\/`) comment,
* `text` is the content of the comment, and `start` and `end` are
* character offsets that denote the start and end of the comment.
* When the {@link locations} option is on, two more parameters are
* passed, the full locations of {@link Position} export type of the start and
* end of the comments.
*
* When a array is passed, each found comment of {@link Comment} export type is pushed to the array.
*
* Note that you are not allowed to call the
* parser from the callback—that will corrupt its internal state.
*/
onComment?: ((
isBlock: boolean, text: string, start: number, end: number, startLoc?: Position,
endLoc?: Position
) => void) | Comment[]
/**
* Nodes have their start and end characters offsets recorded in
* `start` and `end` properties (directly on the node, rather than
* the `loc` object, which holds line/column data. To also add a
* [semi-standardized][range] `range` property holding a `[start,
* end]` array with the same numbers, set the `ranges` option to
* `true`.
*/
ranges?: boolean
/**
* It is possible to parse multiple files into a single AST by
* passing the tree produced by parsing the first file as
* `program` option in subsequent parses. This will add the
* toplevel forms of the parsed file to the `Program` (top) node
* of an existing parse tree.
*/
program?: Node
/**
* When {@link locations} is on, you can pass this to record the source
* file in every node's `loc` object.
*/
sourceFile?: string
/**
* This value, if given, is stored in every node, whether {@link locations} is on or off.
*/
directSourceFile?: string
/**
* When enabled, parenthesized expressions are represented by
* (non-standard) ParenthesizedExpression nodes
*/
preserveParens?: boolean
}
export class Parser {
options: Options
input: string
protected constructor(options: Options, input: string, startPos?: number)
parse(): Program
static parse(input: string, options: Options): Program
static parseExpressionAt(input: string, pos: number, options: Options): Expression
static tokenizer(input: string, options: Options): {
getToken(): Token
[Symbol.iterator](): Iterator<Token>
}
static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser
}
export const defaultOptions: Options
export function getLineInfo(input: string, offset: number): Position
export class TokenType {
label: string
keyword: string | undefined
}
export const tokTypes: {
num: TokenType
regexp: TokenType
string: TokenType
name: TokenType
privateId: TokenType
eof: TokenType
bracketL: TokenType
bracketR: TokenType
braceL: TokenType
braceR: TokenType
parenL: TokenType
parenR: TokenType
comma: TokenType
semi: TokenType
colon: TokenType
dot: TokenType
question: TokenType
questionDot: TokenType
arrow: TokenType
template: TokenType
invalidTemplate: TokenType
ellipsis: TokenType
backQuote: TokenType
dollarBraceL: TokenType
eq: TokenType
assign: TokenType
incDec: TokenType
prefix: TokenType
logicalOR: TokenType
logicalAND: TokenType
bitwiseOR: TokenType
bitwiseXOR: TokenType
bitwiseAND: TokenType
equality: TokenType
relational: TokenType
bitShift: TokenType
plusMin: TokenType
modulo: TokenType
star: TokenType
slash: TokenType
starstar: TokenType
coalesce: TokenType
_break: TokenType
_case: TokenType
_catch: TokenType
_continue: TokenType
_debugger: TokenType
_default: TokenType
_do: TokenType
_else: TokenType
_finally: TokenType
_for: TokenType
_function: TokenType
_if: TokenType
_return: TokenType
_switch: TokenType
_throw: TokenType
_try: TokenType
_var: TokenType
_const: TokenType
_while: TokenType
_with: TokenType
_new: TokenType
_this: TokenType
_super: TokenType
_class: TokenType
_extends: TokenType
_export: TokenType
_import: TokenType
_null: TokenType
_true: TokenType
_false: TokenType
_in: TokenType
_instanceof: TokenType
_typeof: TokenType
_void: TokenType
_delete: TokenType
}
export interface Comment {
type: "Line" | "Block"
value: string
start: number
end: number
loc?: SourceLocation
range?: [number, number]
}
export class Token {
type: TokenType
start: number
end: number
loc?: SourceLocation
range?: [number, number]
}
export const version: string

View File

@@ -0,0 +1,136 @@
"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.default = default_1;
const util = __importStar(require("../core/util.cjs"));
const error = () => {
const Sizable = {
string: { unit: "stafi", verb: "að hafa" },
file: { unit: "bæti", verb: "að hafa" },
array: { unit: "hluti", verb: "að hafa" },
set: { unit: "hluti", verb: "að hafa" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "gildi",
email: "netfang",
url: "vefslóð",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO dagsetning og tími",
date: "ISO dagsetning",
time: "ISO tími",
duration: "ISO tímalengd",
ipv4: "IPv4 address",
ipv6: "IPv6 address",
cidrv4: "IPv4 range",
cidrv6: "IPv6 range",
base64: "base64-encoded strengur",
base64url: "base64url-encoded strengur",
json_string: "JSON strengur",
e164: "E.164 tölugildi",
jwt: "JWT",
template_literal: "gildi",
};
const TypeDictionary = {
nan: "NaN",
number: "númer",
array: "fylki",
};
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 `Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue.expected}`;
}
return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Rangt gildi: gert ráð fyrir ${util.stringifyPrimitive(issue.values[0])}`;
return `Ógilt val: má vera eitt af eftirfarandi ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? "hluti"}`;
return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} sé ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Of lítið: gert er ráð fyrir að ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`;
}
return `Of lítið: gert er ráð fyrir að ${issue.origin} sé ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `Ógildur strengur: verður að byrja á "${_issue.prefix}"`;
}
if (_issue.format === "ends_with")
return `Ógildur strengur: verður að enda á "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Ógildur strengur: verður að innihalda "${_issue.includes}"`;
if (_issue.format === "regex")
return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;
return `Rangt ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Röng tala: verður að vera margfeldi af ${issue.divisor}`;
case "unrecognized_keys":
return `Óþekkt ${issue.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Rangur lykill í ${issue.origin}`;
case "invalid_union":
return "Rangt gildi";
case "invalid_element":
return `Rangt gildi í ${issue.origin}`;
default:
return `Rangt gildi`;
}
};
};
function default_1() {
return {
localeError: error(),
};
}
module.exports = exports.default;

View File

@@ -0,0 +1,200 @@
"use strict";
/**********************************************
* DO NOT MODIFY THIS FILE MANUALLY *
* *
* THIS FILE HAS BEEN COPIED FROM ast-spec. *
* ANY CHANGES WILL BE LOST ON THE NEXT BUILD *
* *
* MAKE CHANGES TO ast-spec AND THEN RUN *
* pnpm run build *
**********************************************/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0;
var AST_NODE_TYPES;
(function (AST_NODE_TYPES) {
AST_NODE_TYPES["AccessorProperty"] = "AccessorProperty";
AST_NODE_TYPES["ArrayExpression"] = "ArrayExpression";
AST_NODE_TYPES["ArrayPattern"] = "ArrayPattern";
AST_NODE_TYPES["ArrowFunctionExpression"] = "ArrowFunctionExpression";
AST_NODE_TYPES["AssignmentExpression"] = "AssignmentExpression";
AST_NODE_TYPES["AssignmentPattern"] = "AssignmentPattern";
AST_NODE_TYPES["AwaitExpression"] = "AwaitExpression";
AST_NODE_TYPES["BinaryExpression"] = "BinaryExpression";
AST_NODE_TYPES["BlockStatement"] = "BlockStatement";
AST_NODE_TYPES["BreakStatement"] = "BreakStatement";
AST_NODE_TYPES["CallExpression"] = "CallExpression";
AST_NODE_TYPES["CatchClause"] = "CatchClause";
AST_NODE_TYPES["ChainExpression"] = "ChainExpression";
AST_NODE_TYPES["ClassBody"] = "ClassBody";
AST_NODE_TYPES["ClassDeclaration"] = "ClassDeclaration";
AST_NODE_TYPES["ClassExpression"] = "ClassExpression";
AST_NODE_TYPES["ConditionalExpression"] = "ConditionalExpression";
AST_NODE_TYPES["ContinueStatement"] = "ContinueStatement";
AST_NODE_TYPES["DebuggerStatement"] = "DebuggerStatement";
AST_NODE_TYPES["Decorator"] = "Decorator";
AST_NODE_TYPES["DoWhileStatement"] = "DoWhileStatement";
AST_NODE_TYPES["EmptyStatement"] = "EmptyStatement";
AST_NODE_TYPES["ExportAllDeclaration"] = "ExportAllDeclaration";
AST_NODE_TYPES["ExportDefaultDeclaration"] = "ExportDefaultDeclaration";
AST_NODE_TYPES["ExportNamedDeclaration"] = "ExportNamedDeclaration";
AST_NODE_TYPES["ExportSpecifier"] = "ExportSpecifier";
AST_NODE_TYPES["ExpressionStatement"] = "ExpressionStatement";
AST_NODE_TYPES["ForInStatement"] = "ForInStatement";
AST_NODE_TYPES["ForOfStatement"] = "ForOfStatement";
AST_NODE_TYPES["ForStatement"] = "ForStatement";
AST_NODE_TYPES["FunctionDeclaration"] = "FunctionDeclaration";
AST_NODE_TYPES["FunctionExpression"] = "FunctionExpression";
AST_NODE_TYPES["Identifier"] = "Identifier";
AST_NODE_TYPES["IfStatement"] = "IfStatement";
AST_NODE_TYPES["ImportAttribute"] = "ImportAttribute";
AST_NODE_TYPES["ImportDeclaration"] = "ImportDeclaration";
AST_NODE_TYPES["ImportDefaultSpecifier"] = "ImportDefaultSpecifier";
AST_NODE_TYPES["ImportExpression"] = "ImportExpression";
AST_NODE_TYPES["ImportNamespaceSpecifier"] = "ImportNamespaceSpecifier";
AST_NODE_TYPES["ImportSpecifier"] = "ImportSpecifier";
AST_NODE_TYPES["JSXAttribute"] = "JSXAttribute";
AST_NODE_TYPES["JSXClosingElement"] = "JSXClosingElement";
AST_NODE_TYPES["JSXClosingFragment"] = "JSXClosingFragment";
AST_NODE_TYPES["JSXElement"] = "JSXElement";
AST_NODE_TYPES["JSXEmptyExpression"] = "JSXEmptyExpression";
AST_NODE_TYPES["JSXExpressionContainer"] = "JSXExpressionContainer";
AST_NODE_TYPES["JSXFragment"] = "JSXFragment";
AST_NODE_TYPES["JSXIdentifier"] = "JSXIdentifier";
AST_NODE_TYPES["JSXMemberExpression"] = "JSXMemberExpression";
AST_NODE_TYPES["JSXNamespacedName"] = "JSXNamespacedName";
AST_NODE_TYPES["JSXOpeningElement"] = "JSXOpeningElement";
AST_NODE_TYPES["JSXOpeningFragment"] = "JSXOpeningFragment";
AST_NODE_TYPES["JSXSpreadAttribute"] = "JSXSpreadAttribute";
AST_NODE_TYPES["JSXSpreadChild"] = "JSXSpreadChild";
AST_NODE_TYPES["JSXText"] = "JSXText";
AST_NODE_TYPES["LabeledStatement"] = "LabeledStatement";
AST_NODE_TYPES["Literal"] = "Literal";
AST_NODE_TYPES["LogicalExpression"] = "LogicalExpression";
AST_NODE_TYPES["MemberExpression"] = "MemberExpression";
AST_NODE_TYPES["MetaProperty"] = "MetaProperty";
AST_NODE_TYPES["MethodDefinition"] = "MethodDefinition";
AST_NODE_TYPES["NewExpression"] = "NewExpression";
AST_NODE_TYPES["ObjectExpression"] = "ObjectExpression";
AST_NODE_TYPES["ObjectPattern"] = "ObjectPattern";
AST_NODE_TYPES["PrivateIdentifier"] = "PrivateIdentifier";
AST_NODE_TYPES["Program"] = "Program";
AST_NODE_TYPES["Property"] = "Property";
AST_NODE_TYPES["PropertyDefinition"] = "PropertyDefinition";
AST_NODE_TYPES["RestElement"] = "RestElement";
AST_NODE_TYPES["ReturnStatement"] = "ReturnStatement";
AST_NODE_TYPES["SequenceExpression"] = "SequenceExpression";
AST_NODE_TYPES["SpreadElement"] = "SpreadElement";
AST_NODE_TYPES["StaticBlock"] = "StaticBlock";
AST_NODE_TYPES["Super"] = "Super";
AST_NODE_TYPES["SwitchCase"] = "SwitchCase";
AST_NODE_TYPES["SwitchStatement"] = "SwitchStatement";
AST_NODE_TYPES["TaggedTemplateExpression"] = "TaggedTemplateExpression";
AST_NODE_TYPES["TemplateElement"] = "TemplateElement";
AST_NODE_TYPES["TemplateLiteral"] = "TemplateLiteral";
AST_NODE_TYPES["ThisExpression"] = "ThisExpression";
AST_NODE_TYPES["ThrowStatement"] = "ThrowStatement";
AST_NODE_TYPES["TryStatement"] = "TryStatement";
AST_NODE_TYPES["UnaryExpression"] = "UnaryExpression";
AST_NODE_TYPES["UpdateExpression"] = "UpdateExpression";
AST_NODE_TYPES["VariableDeclaration"] = "VariableDeclaration";
AST_NODE_TYPES["VariableDeclarator"] = "VariableDeclarator";
AST_NODE_TYPES["WhileStatement"] = "WhileStatement";
AST_NODE_TYPES["WithStatement"] = "WithStatement";
AST_NODE_TYPES["YieldExpression"] = "YieldExpression";
AST_NODE_TYPES["TSAbstractAccessorProperty"] = "TSAbstractAccessorProperty";
AST_NODE_TYPES["TSAbstractKeyword"] = "TSAbstractKeyword";
AST_NODE_TYPES["TSAbstractMethodDefinition"] = "TSAbstractMethodDefinition";
AST_NODE_TYPES["TSAbstractPropertyDefinition"] = "TSAbstractPropertyDefinition";
AST_NODE_TYPES["TSAnyKeyword"] = "TSAnyKeyword";
AST_NODE_TYPES["TSArrayType"] = "TSArrayType";
AST_NODE_TYPES["TSAsExpression"] = "TSAsExpression";
AST_NODE_TYPES["TSAsyncKeyword"] = "TSAsyncKeyword";
AST_NODE_TYPES["TSBigIntKeyword"] = "TSBigIntKeyword";
AST_NODE_TYPES["TSBooleanKeyword"] = "TSBooleanKeyword";
AST_NODE_TYPES["TSCallSignatureDeclaration"] = "TSCallSignatureDeclaration";
AST_NODE_TYPES["TSClassImplements"] = "TSClassImplements";
AST_NODE_TYPES["TSConditionalType"] = "TSConditionalType";
AST_NODE_TYPES["TSConstructorType"] = "TSConstructorType";
AST_NODE_TYPES["TSConstructSignatureDeclaration"] = "TSConstructSignatureDeclaration";
AST_NODE_TYPES["TSDeclareFunction"] = "TSDeclareFunction";
AST_NODE_TYPES["TSDeclareKeyword"] = "TSDeclareKeyword";
AST_NODE_TYPES["TSEmptyBodyFunctionExpression"] = "TSEmptyBodyFunctionExpression";
AST_NODE_TYPES["TSEnumBody"] = "TSEnumBody";
AST_NODE_TYPES["TSEnumDeclaration"] = "TSEnumDeclaration";
AST_NODE_TYPES["TSEnumMember"] = "TSEnumMember";
AST_NODE_TYPES["TSExportAssignment"] = "TSExportAssignment";
AST_NODE_TYPES["TSExportKeyword"] = "TSExportKeyword";
AST_NODE_TYPES["TSExternalModuleReference"] = "TSExternalModuleReference";
AST_NODE_TYPES["TSFunctionType"] = "TSFunctionType";
AST_NODE_TYPES["TSImportEqualsDeclaration"] = "TSImportEqualsDeclaration";
AST_NODE_TYPES["TSImportType"] = "TSImportType";
AST_NODE_TYPES["TSIndexedAccessType"] = "TSIndexedAccessType";
AST_NODE_TYPES["TSIndexSignature"] = "TSIndexSignature";
AST_NODE_TYPES["TSInferType"] = "TSInferType";
AST_NODE_TYPES["TSInstantiationExpression"] = "TSInstantiationExpression";
AST_NODE_TYPES["TSInterfaceBody"] = "TSInterfaceBody";
AST_NODE_TYPES["TSInterfaceDeclaration"] = "TSInterfaceDeclaration";
AST_NODE_TYPES["TSInterfaceHeritage"] = "TSInterfaceHeritage";
AST_NODE_TYPES["TSIntersectionType"] = "TSIntersectionType";
AST_NODE_TYPES["TSIntrinsicKeyword"] = "TSIntrinsicKeyword";
AST_NODE_TYPES["TSLiteralType"] = "TSLiteralType";
AST_NODE_TYPES["TSMappedType"] = "TSMappedType";
AST_NODE_TYPES["TSMethodSignature"] = "TSMethodSignature";
AST_NODE_TYPES["TSModuleBlock"] = "TSModuleBlock";
AST_NODE_TYPES["TSModuleDeclaration"] = "TSModuleDeclaration";
AST_NODE_TYPES["TSNamedTupleMember"] = "TSNamedTupleMember";
AST_NODE_TYPES["TSNamespaceExportDeclaration"] = "TSNamespaceExportDeclaration";
AST_NODE_TYPES["TSNeverKeyword"] = "TSNeverKeyword";
AST_NODE_TYPES["TSNonNullExpression"] = "TSNonNullExpression";
AST_NODE_TYPES["TSNullKeyword"] = "TSNullKeyword";
AST_NODE_TYPES["TSNumberKeyword"] = "TSNumberKeyword";
AST_NODE_TYPES["TSObjectKeyword"] = "TSObjectKeyword";
AST_NODE_TYPES["TSOptionalType"] = "TSOptionalType";
AST_NODE_TYPES["TSParameterProperty"] = "TSParameterProperty";
AST_NODE_TYPES["TSPrivateKeyword"] = "TSPrivateKeyword";
AST_NODE_TYPES["TSPropertySignature"] = "TSPropertySignature";
AST_NODE_TYPES["TSProtectedKeyword"] = "TSProtectedKeyword";
AST_NODE_TYPES["TSPublicKeyword"] = "TSPublicKeyword";
AST_NODE_TYPES["TSQualifiedName"] = "TSQualifiedName";
AST_NODE_TYPES["TSReadonlyKeyword"] = "TSReadonlyKeyword";
AST_NODE_TYPES["TSRestType"] = "TSRestType";
AST_NODE_TYPES["TSSatisfiesExpression"] = "TSSatisfiesExpression";
AST_NODE_TYPES["TSStaticKeyword"] = "TSStaticKeyword";
AST_NODE_TYPES["TSStringKeyword"] = "TSStringKeyword";
AST_NODE_TYPES["TSSymbolKeyword"] = "TSSymbolKeyword";
AST_NODE_TYPES["TSTemplateLiteralType"] = "TSTemplateLiteralType";
AST_NODE_TYPES["TSThisType"] = "TSThisType";
AST_NODE_TYPES["TSTupleType"] = "TSTupleType";
AST_NODE_TYPES["TSTypeAliasDeclaration"] = "TSTypeAliasDeclaration";
AST_NODE_TYPES["TSTypeAnnotation"] = "TSTypeAnnotation";
AST_NODE_TYPES["TSTypeAssertion"] = "TSTypeAssertion";
AST_NODE_TYPES["TSTypeLiteral"] = "TSTypeLiteral";
AST_NODE_TYPES["TSTypeOperator"] = "TSTypeOperator";
AST_NODE_TYPES["TSTypeParameter"] = "TSTypeParameter";
AST_NODE_TYPES["TSTypeParameterDeclaration"] = "TSTypeParameterDeclaration";
AST_NODE_TYPES["TSTypeParameterInstantiation"] = "TSTypeParameterInstantiation";
AST_NODE_TYPES["TSTypePredicate"] = "TSTypePredicate";
AST_NODE_TYPES["TSTypeQuery"] = "TSTypeQuery";
AST_NODE_TYPES["TSTypeReference"] = "TSTypeReference";
AST_NODE_TYPES["TSUndefinedKeyword"] = "TSUndefinedKeyword";
AST_NODE_TYPES["TSUnionType"] = "TSUnionType";
AST_NODE_TYPES["TSUnknownKeyword"] = "TSUnknownKeyword";
AST_NODE_TYPES["TSVoidKeyword"] = "TSVoidKeyword";
})(AST_NODE_TYPES || (exports.AST_NODE_TYPES = AST_NODE_TYPES = {}));
var AST_TOKEN_TYPES;
(function (AST_TOKEN_TYPES) {
AST_TOKEN_TYPES["Boolean"] = "Boolean";
AST_TOKEN_TYPES["Identifier"] = "Identifier";
AST_TOKEN_TYPES["JSXIdentifier"] = "JSXIdentifier";
AST_TOKEN_TYPES["PrivateIdentifier"] = "PrivateIdentifier";
AST_TOKEN_TYPES["JSXText"] = "JSXText";
AST_TOKEN_TYPES["Keyword"] = "Keyword";
AST_TOKEN_TYPES["Null"] = "Null";
AST_TOKEN_TYPES["Numeric"] = "Numeric";
AST_TOKEN_TYPES["Punctuator"] = "Punctuator";
AST_TOKEN_TYPES["RegularExpression"] = "RegularExpression";
AST_TOKEN_TYPES["String"] = "String";
AST_TOKEN_TYPES["Template"] = "Template";
AST_TOKEN_TYPES["Block"] = "Block";
AST_TOKEN_TYPES["Line"] = "Line";
})(AST_TOKEN_TYPES || (exports.AST_TOKEN_TYPES = AST_TOKEN_TYPES = {}));

View File

@@ -0,0 +1,8 @@
import type { TSESTree } from '@typescript-eslint/types';
import { DefinitionBase } from './DefinitionBase';
import { DefinitionType } from './DefinitionType';
export declare class VariableDefinition extends DefinitionBase<DefinitionType.Variable, TSESTree.VariableDeclarator, TSESTree.VariableDeclaration, TSESTree.Identifier> {
readonly isTypeDefinition = false;
readonly isVariableDefinition = true;
constructor(name: TSESTree.Identifier, node: VariableDefinition['node'], decl: TSESTree.VariableDeclaration);
}

View File

@@ -0,0 +1,75 @@
"use strict";
function _using_ctx() {
var _disposeSuppressedError = typeof SuppressedError === "function"
// eslint-disable-next-line no-undef
? SuppressedError
: (function(error, suppressed) {
var err = new Error();
err.name = "SuppressedError";
err.suppressed = suppressed;
err.error = error;
return err;
}),
empty = {},
stack = [];
function using(isAwait, value) {
if (value != null) {
if (Object(value) !== value) {
throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
}
// core-js-pure uses Symbol.for for polyfilling well-known symbols
if (isAwait) {
var dispose = value[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
}
if (dispose == null) {
dispose = value[Symbol.dispose || Symbol.for("Symbol.dispose")];
}
if (typeof dispose !== "function") {
throw new TypeError(`Property [Symbol.dispose] is not a function.`);
}
stack.push({ v: value, d: dispose, a: isAwait });
} else if (isAwait) {
// provide the nullish `value` as `d` for minification gain
stack.push({ d: value, a: isAwait });
}
return value;
}
return {
// error
e: empty,
// using
u: using.bind(null, false),
// await using
a: using.bind(null, true),
// dispose
d: function() {
var error = this.e;
function next() {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
while ((resource = stack.pop())) {
try {
var resource, disposalResult = resource.d && resource.d.call(resource.v);
if (resource.a) {
return Promise.resolve(disposalResult).then(next, err);
}
} catch (e) {
return err(e);
}
}
if (error !== empty) throw error;
}
function err(e) {
error = error !== empty ? new _disposeSuppressedError(e, error) : e;
return next();
}
return next();
}
};
}
exports._ = _using_ctx;