diff --git a/tools/ui/node_modules/minipass/dist/commonjs/package.json b/tools/ui/node_modules/minipass/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/tools/ui/node_modules/minipass/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/tools/ui/node_modules/minipass/dist/esm/index.d.ts b/tools/ui/node_modules/minipass/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e75b578a6e30945efd5c647008798c8758a53ca --- /dev/null +++ b/tools/ui/node_modules/minipass/dist/esm/index.d.ts @@ -0,0 +1,545 @@ +import { EventEmitter } from 'node:events'; +import { StringDecoder } from 'node:string_decoder'; +/** + * Same as StringDecoder, but exposing the `lastNeed` flag on the type + */ +type SD = StringDecoder & { + lastNeed: boolean; +}; +export type { SD, Pipe, PipeProxyErrors }; +/** + * Return true if the argument is a Minipass stream, Node stream, or something + * else that Minipass can interact with. + */ +export declare const isStream: (s: any) => s is Minipass | NodeJS.ReadStream | NodeJS.WriteStream | (EventEmitter & { + end(): any; + write(chunk: any, ...args: any[]): any; +}) | (EventEmitter & { + pause(): any; + resume(): any; + pipe(...destArgs: any[]): any; +}) | (NodeJS.ReadStream & { + fd: number; +}) | (NodeJS.WriteStream & { + fd: number; +}); +/** + * Return true if the argument is a valid {@link Minipass.Readable} + */ +export declare const isReadable: (s: any) => s is Minipass.Readable; +/** + * Return true if the argument is a valid {@link Minipass.Writable} + */ +export declare const isWritable: (s: any) => s is Minipass.Readable; +declare const EOF: unique symbol; +declare const MAYBE_EMIT_END: unique symbol; +declare const EMITTED_END: unique symbol; +declare const EMITTING_END: unique symbol; +declare const EMITTED_ERROR: unique symbol; +declare const CLOSED: unique symbol; +declare const READ: unique symbol; +declare const FLUSH: unique symbol; +declare const FLUSHCHUNK: unique symbol; +declare const ENCODING: unique symbol; +declare const DECODER: unique symbol; +declare const FLOWING: unique symbol; +declare const PAUSED: unique symbol; +declare const RESUME: unique symbol; +declare const BUFFER: unique symbol; +declare const PIPES: unique symbol; +declare const BUFFERLENGTH: unique symbol; +declare const BUFFERPUSH: unique symbol; +declare const BUFFERSHIFT: unique symbol; +declare const OBJECTMODE: unique symbol; +declare const DESTROYED: unique symbol; +declare const ERROR: unique symbol; +declare const EMITDATA: unique symbol; +declare const EMITEND: unique symbol; +declare const EMITEND2: unique symbol; +declare const ASYNC: unique symbol; +declare const ABORT: unique symbol; +declare const ABORTED: unique symbol; +declare const SIGNAL: unique symbol; +declare const DATALISTENERS: unique symbol; +declare const DISCARDED: unique symbol; +/** + * Options that may be passed to stream.pipe() + */ +export interface PipeOptions { + /** + * end the destination stream when the source stream ends + */ + end?: boolean; + /** + * proxy errors from the source stream to the destination stream + */ + proxyErrors?: boolean; +} +/** + * Internal class representing a pipe to a destination stream. + * + * @internal + */ +declare class Pipe { + src: Minipass; + dest: Minipass; + opts: PipeOptions; + ondrain: () => any; + constructor(src: Minipass, dest: Minipass.Writable, opts: PipeOptions); + unpipe(): void; + proxyErrors(_er: any): void; + end(): void; +} +/** + * Internal class representing a pipe to a destination stream where + * errors are proxied. + * + * @internal + */ +declare class PipeProxyErrors extends Pipe { + unpipe(): void; + constructor(src: Minipass, dest: Minipass.Writable, opts: PipeOptions); +} +export declare namespace Minipass { + /** + * Encoding used to create a stream that outputs strings rather than + * Buffer objects. + */ + export type Encoding = BufferEncoding | 'buffer' | null; + /** + * Any stream that Minipass can pipe into + */ + export type Writable = Minipass | NodeJS.WriteStream | (NodeJS.WriteStream & { + fd: number; + }) | (EventEmitter & { + end(): any; + write(chunk: any, ...args: any[]): any; + }); + /** + * Any stream that can be read from + */ + export type Readable = Minipass | NodeJS.ReadStream | (NodeJS.ReadStream & { + fd: number; + }) | (EventEmitter & { + pause(): any; + resume(): any; + pipe(...destArgs: any[]): any; + }); + /** + * Utility type that can be iterated sync or async + */ + export type DualIterable = Iterable & AsyncIterable; + type EventArguments = Record; + /** + * The listing of events that a Minipass class can emit. + * Extend this when extending the Minipass class, and pass as + * the third template argument. The key is the name of the event, + * and the value is the argument list. + * + * Any undeclared events will still be allowed, but the handler will get + * arguments as `unknown[]`. + */ + export interface Events extends EventArguments { + readable: []; + data: [chunk: RType]; + error: [er: unknown]; + abort: [reason: unknown]; + drain: []; + resume: []; + end: []; + finish: []; + prefinish: []; + close: []; + [DESTROYED]: [er?: unknown]; + [ERROR]: [er: unknown]; + } + /** + * String or buffer-like data that can be joined and sliced + */ + export type ContiguousData = Buffer | ArrayBufferLike | ArrayBufferView | string; + export type BufferOrString = Buffer | string; + /** + * Options passed to the Minipass constructor. + */ + export type SharedOptions = { + /** + * Defer all data emission and other events until the end of the + * current tick, similar to Node core streams + */ + async?: boolean; + /** + * A signal which will abort the stream + */ + signal?: AbortSignal; + /** + * Output string encoding. Set to `null` or `'buffer'` (or omit) to + * emit Buffer objects rather than strings. + * + * Conflicts with `objectMode` + */ + encoding?: BufferEncoding | null | 'buffer'; + /** + * Output data exactly as it was written, supporting non-buffer/string + * data (such as arbitrary objects, falsey values, etc.) + * + * Conflicts with `encoding` + */ + objectMode?: boolean; + }; + /** + * Options for a string encoded output + */ + export type EncodingOptions = SharedOptions & { + encoding: BufferEncoding; + objectMode?: false; + }; + /** + * Options for contiguous data buffer output + */ + export type BufferOptions = SharedOptions & { + encoding?: null | 'buffer'; + objectMode?: false; + }; + /** + * Options for objectMode arbitrary output + */ + export type ObjectModeOptions = SharedOptions & { + objectMode: true; + encoding?: null; + }; + /** + * Utility type to determine allowed options based on read type + */ + export type Options = ObjectModeOptions | (T extends string ? EncodingOptions : T extends Buffer ? BufferOptions : SharedOptions); + export {}; +} +/** + * Main export, the Minipass class + * + * `RType` is the type of data emitted, defaults to Buffer + * + * `WType` is the type of data to be written, if RType is buffer or string, + * then any {@link Minipass.ContiguousData} is allowed. + * + * `Events` is the set of event handler signatures that this object + * will emit, see {@link Minipass.Events} + */ +export declare class Minipass = Minipass.Events> extends EventEmitter implements Minipass.DualIterable { + [FLOWING]: boolean; + [PAUSED]: boolean; + [PIPES]: Pipe[]; + [BUFFER]: RType[]; + [OBJECTMODE]: boolean; + [ENCODING]: BufferEncoding | null; + [ASYNC]: boolean; + [DECODER]: SD | null; + [EOF]: boolean; + [EMITTED_END]: boolean; + [EMITTING_END]: boolean; + [CLOSED]: boolean; + [EMITTED_ERROR]: unknown; + [BUFFERLENGTH]: number; + [DESTROYED]: boolean; + [SIGNAL]?: AbortSignal; + [ABORTED]: boolean; + [DATALISTENERS]: number; + [DISCARDED]: boolean; + /** + * true if the stream can be written + */ + writable: boolean; + /** + * true if the stream can be read + */ + readable: boolean; + /** + * If `RType` is Buffer, then options do not need to be provided. + * Otherwise, an options object must be provided to specify either + * {@link Minipass.SharedOptions.objectMode} or + * {@link Minipass.SharedOptions.encoding}, as appropriate. + */ + constructor(...args: [Minipass.ObjectModeOptions] | (RType extends Buffer ? [] | [Minipass.Options] : [Minipass.Options])); + /** + * The amount of data stored in the buffer waiting to be read. + * + * For Buffer strings, this will be the total byte length. + * For string encoding streams, this will be the string character length, + * according to JavaScript's `string.length` logic. + * For objectMode streams, this is a count of the items waiting to be + * emitted. + */ + get bufferLength(): number; + /** + * The `BufferEncoding` currently in use, or `null` + */ + get encoding(): BufferEncoding | null; + /** + * @deprecated - This is a read only property + */ + set encoding(_enc: BufferEncoding | null); + /** + * @deprecated - Encoding may only be set at instantiation time + */ + setEncoding(_enc: Minipass.Encoding): void; + /** + * True if this is an objectMode stream + */ + get objectMode(): boolean; + /** + * @deprecated - This is a read-only property + */ + set objectMode(_om: boolean); + /** + * true if this is an async stream + */ + get ['async'](): boolean; + /** + * Set to true to make this stream async. + * + * Once set, it cannot be unset, as this would potentially cause incorrect + * behavior. Ie, a sync stream can be made async, but an async stream + * cannot be safely made sync. + */ + set ['async'](a: boolean); + [ABORT](): void; + /** + * True if the stream has been aborted. + */ + get aborted(): boolean; + /** + * No-op setter. Stream aborted status is set via the AbortSignal provided + * in the constructor options. + */ + set aborted(_: boolean); + /** + * Write data into the stream + * + * If the chunk written is a string, and encoding is not specified, then + * `utf8` will be assumed. If the stream encoding matches the encoding of + * a written string, and the state of the string decoder allows it, then + * the string will be passed through to either the output or the internal + * buffer without any processing. Otherwise, it will be turned into a + * Buffer object for processing into the desired encoding. + * + * If provided, `cb` function is called immediately before return for + * sync streams, or on next tick for async streams, because for this + * base class, a chunk is considered "processed" once it is accepted + * and either emitted or buffered. That is, the callback does not indicate + * that the chunk has been eventually emitted, though of course child + * classes can override this function to do whatever processing is required + * and call `super.write(...)` only once processing is completed. + */ + write(chunk: WType, cb?: () => void): boolean; + write(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): boolean; + /** + * Low-level explicit read method. + * + * In objectMode, the argument is ignored, and one item is returned if + * available. + * + * `n` is the number of bytes (or in the case of encoding streams, + * characters) to consume. If `n` is not provided, then the entire buffer + * is returned, or `null` is returned if no data is available. + * + * If `n` is greater that the amount of data in the internal buffer, + * then `null` is returned. + */ + read(n?: number | null): RType | null; + [READ](n: number | null, chunk: RType): RType; + /** + * End the stream, optionally providing a final write. + * + * See {@link Minipass#write} for argument descriptions + */ + end(cb?: () => void): this; + end(chunk: WType, cb?: () => void): this; + end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this; + [RESUME](): void; + /** + * Resume the stream if it is currently in a paused state + * + * If called when there are no pipe destinations or `data` event listeners, + * this will place the stream in a "discarded" state, where all data will + * be thrown away. The discarded state is removed if a pipe destination or + * data handler is added, if pause() is called, or if any synchronous or + * asynchronous iteration is started. + */ + resume(): void; + /** + * Pause the stream + */ + pause(): void; + /** + * true if the stream has been forcibly destroyed + */ + get destroyed(): boolean; + /** + * true if the stream is currently in a flowing state, meaning that + * any writes will be immediately emitted. + */ + get flowing(): boolean; + /** + * true if the stream is currently in a paused state + */ + get paused(): boolean; + [BUFFERPUSH](chunk: RType): void; + [BUFFERSHIFT](): RType; + [FLUSH](noDrain?: boolean): void; + [FLUSHCHUNK](chunk: RType): boolean; + /** + * Pipe all data emitted by this stream into the destination provided. + * + * Triggers the flow of data. + */ + pipe(dest: W, opts?: PipeOptions): W; + /** + * Fully unhook a piped destination stream. + * + * If the destination stream was the only consumer of this stream (ie, + * there are no other piped destinations or `'data'` event listeners) + * then the flow of data will stop until there is another consumer or + * {@link Minipass#resume} is explicitly called. + */ + unpipe(dest: W): void; + /** + * Alias for {@link Minipass#on} + */ + addListener(ev: Event, handler: (...args: Events[Event]) => any): this; + /** + * Mostly identical to `EventEmitter.on`, with the following + * behavior differences to prevent data loss and unnecessary hangs: + * + * - Adding a 'data' event handler will trigger the flow of data + * + * - Adding a 'readable' event handler when there is data waiting to be read + * will cause 'readable' to be emitted immediately. + * + * - Adding an 'endish' event handler ('end', 'finish', etc.) which has + * already passed will cause the event to be emitted immediately and all + * handlers removed. + * + * - Adding an 'error' event handler after an error has been emitted will + * cause the event to be re-emitted immediately with the error previously + * raised. + */ + on(ev: Event, handler: (...args: Events[Event]) => any): this; + /** + * Alias for {@link Minipass#off} + */ + removeListener(ev: Event, handler: (...args: Events[Event]) => any): this; + /** + * Mostly identical to `EventEmitter.off` + * + * If a 'data' event handler is removed, and it was the last consumer + * (ie, there are no pipe destinations or other 'data' event listeners), + * then the flow of data will stop until there is another consumer or + * {@link Minipass#resume} is explicitly called. + */ + off(ev: Event, handler: (...args: Events[Event]) => any): this; + /** + * Mostly identical to `EventEmitter.removeAllListeners` + * + * If all 'data' event handlers are removed, and they were the last consumer + * (ie, there are no pipe destinations), then the flow of data will stop + * until there is another consumer or {@link Minipass#resume} is explicitly + * called. + */ + removeAllListeners(ev?: Event): this; + /** + * true if the 'end' event has been emitted + */ + get emittedEnd(): boolean; + [MAYBE_EMIT_END](): void; + /** + * Mostly identical to `EventEmitter.emit`, with the following + * behavior differences to prevent data loss and unnecessary hangs: + * + * If the stream has been destroyed, and the event is something other + * than 'close' or 'error', then `false` is returned and no handlers + * are called. + * + * If the event is 'end', and has already been emitted, then the event + * is ignored. If the stream is in a paused or non-flowing state, then + * the event will be deferred until data flow resumes. If the stream is + * async, then handlers will be called on the next tick rather than + * immediately. + * + * If the event is 'close', and 'end' has not yet been emitted, then + * the event will be deferred until after 'end' is emitted. + * + * If the event is 'error', and an AbortSignal was provided for the stream, + * and there are no listeners, then the event is ignored, matching the + * behavior of node core streams in the presense of an AbortSignal. + * + * If the event is 'finish' or 'prefinish', then all listeners will be + * removed after emitting the event, to prevent double-firing. + */ + emit(ev: Event, ...args: Events[Event]): boolean; + [EMITDATA](data: RType): boolean; + [EMITEND](): boolean; + [EMITEND2](): boolean; + /** + * Return a Promise that resolves to an array of all emitted data once + * the stream ends. + */ + collect(): Promise; + /** + * Return a Promise that resolves to the concatenation of all emitted data + * once the stream ends. + * + * Not allowed on objectMode streams. + */ + concat(): Promise; + /** + * Return a void Promise that resolves once the stream ends. + */ + promise(): Promise; + /** + * Asynchronous `for await of` iteration. + * + * This will continue emitting all chunks until the stream terminates. + */ + [Symbol.asyncIterator](): AsyncGenerator; + /** + * Synchronous `for of` iteration. + * + * The iteration will terminate when the internal buffer runs out, even + * if the stream has not yet terminated. + */ + [Symbol.iterator](): Generator; + /** + * Destroy a stream, preventing it from being used for any further purpose. + * + * If the stream has a `close()` method, then it will be called on + * destruction. + * + * After destruction, any attempt to write data, read data, or emit most + * events will be ignored. + * + * If an error argument is provided, then it will be emitted in an + * 'error' event. + */ + destroy(er?: unknown): this; + /** + * Alias for {@link isStream} + * + * Former export location, maintained for backwards compatibility. + * + * @deprecated + */ + static get isStream(): (s: any) => s is Minipass | NodeJS.ReadStream | NodeJS.WriteStream | (EventEmitter & { + end(): any; + write(chunk: any, ...args: any[]): any; + }) | (EventEmitter & { + pause(): any; + resume(): any; + pipe(...destArgs: any[]): any; + }) | (NodeJS.ReadStream & { + fd: number; + }) | (NodeJS.WriteStream & { + fd: number; + }); +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/minipass/dist/esm/index.d.ts.map b/tools/ui/node_modules/minipass/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..7bce611bb6e42e8ac462d0c592f313639c7ca721 --- /dev/null +++ b/tools/ui/node_modules/minipass/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAE1C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD;;GAEG;AACH,KAAK,EAAE,GAAG,aAAa,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAA;AAE/C,YAAY,EAAE,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,CAAA;AAEzC;;;GAGG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;;;EAQH,CAAA;AAElB;;GAEG;AACH,eAAO,MAAM,UAAU,oCAM2C,CAAA;AAElE;;GAEG;AACH,eAAO,MAAM,UAAU,oCAK6B,CAAA;AAEpD,QAAA,MAAM,GAAG,eAAgB,CAAA;AACzB,QAAA,MAAM,cAAc,eAAyB,CAAA;AAC7C,QAAA,MAAM,WAAW,eAAuB,CAAA;AACxC,QAAA,MAAM,YAAY,eAAwB,CAAA;AAC1C,QAAA,MAAM,aAAa,eAAyB,CAAA;AAC5C,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,IAAI,eAAiB,CAAA;AAC3B,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MAAM,UAAU,eAAuB,CAAA;AACvC,QAAA,MAAM,QAAQ,eAAqB,CAAA;AACnC,QAAA,MAAM,OAAO,eAAoB,CAAA;AACjC,QAAA,MAAM,OAAO,eAAoB,CAAA;AACjC,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MAAM,YAAY,eAAyB,CAAA;AAC3C,QAAA,MAAM,UAAU,eAAuB,CAAA;AACvC,QAAA,MAAM,WAAW,eAAwB,CAAA;AACzC,QAAA,MAAM,UAAU,eAAuB,CAAA;AAEvC,QAAA,MAAM,SAAS,eAAsB,CAAA;AAErC,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MAAM,QAAQ,eAAqB,CAAA;AACnC,QAAA,MAAM,OAAO,eAAoB,CAAA;AACjC,QAAA,MAAM,QAAQ,eAAqB,CAAA;AACnC,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MAAM,OAAO,eAAoB,CAAA;AACjC,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,aAAa,eAA0B,CAAA;AAC7C,QAAA,MAAM,SAAS,eAAsB,CAAA;AAuBrC;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,GAAG,CAAC,EAAE,OAAO,CAAA;IACb;;OAEG;IACH,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB;AAED;;;;GAIG;AACH,cAAM,IAAI,CAAC,CAAC,SAAS,OAAO;IAC1B,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAA;IAChB,IAAI,EAAE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAC,CAAA;IACtB,IAAI,EAAE,WAAW,CAAA;IACjB,OAAO,EAAE,MAAM,GAAG,CAAA;IAClB,YACE,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,QAAQ,CAAC,QAAQ,EACvB,IAAI,EAAE,WAAW,EAOlB;IACD,MAAM,SAEL;IAGD,WAAW,CAAC,GAAG,EAAE,GAAG,QAAI;IAExB,GAAG,SAGF;CACF;AAED;;;;;GAKG;AACH,cAAM,eAAe,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IACtC,MAAM,SAGL;IACD,YACE,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,QAAQ,CAAC,QAAQ,EACvB,IAAI,EAAE,WAAW,EAKlB;CACF;AAED,yBAAiB,QAAQ,CAAC,CAAC;IACzB;;;OAGG;IACH,MAAM,MAAM,QAAQ,GAAG,cAAc,GAAG,QAAQ,GAAG,IAAI,CAAA;IAEvD;;OAEG;IACH,MAAM,MAAM,QAAQ,GAChB,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GACvB,MAAM,CAAC,WAAW,GAClB,CAAC,MAAM,CAAC,WAAW,GAAG;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,GACrC,CAAC,YAAY,GAAG;QACd,GAAG,IAAI,GAAG,CAAA;QACV,KAAK,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAA;KACvC,CAAC,CAAA;IAEN;;OAEG;IACH,MAAM,MAAM,QAAQ,GAChB,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GACvB,MAAM,CAAC,UAAU,GACjB,CAAC,MAAM,CAAC,UAAU,GAAG;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,GACpC,CAAC,YAAY,GAAG;QACd,KAAK,IAAI,GAAG,CAAA;QACZ,MAAM,IAAI,GAAG,CAAA;QACb,IAAI,CAAC,GAAG,QAAQ,EAAE,GAAG,EAAE,GAAG,GAAG,CAAA;KAC9B,CAAC,CAAA;IAEN;;OAEG;IACH,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,CAAA;IAE5D,KAAK,cAAc,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,OAAO,EAAE,CAAC,CAAA;IAExD;;;;;;;;OAQG;IACH,MAAM,WAAW,MAAM,CAAC,KAAK,SAAS,GAAG,GAAG,MAAM,CAChD,SAAQ,cAAc;QACtB,QAAQ,EAAE,EAAE,CAAA;QACZ,IAAI,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QACpB,KAAK,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;QACpB,KAAK,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QACxB,KAAK,EAAE,EAAE,CAAA;QACT,MAAM,EAAE,EAAE,CAAA;QACV,GAAG,EAAE,EAAE,CAAA;QACP,MAAM,EAAE,EAAE,CAAA;QACV,SAAS,EAAE,EAAE,CAAA;QACb,KAAK,EAAE,EAAE,CAAA;QACT,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,CAAA;QAC3B,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;KACvB;IAED;;OAEG;IACH,MAAM,MAAM,cAAc,GACtB,MAAM,GACN,eAAe,GACf,eAAe,GACf,MAAM,CAAA;IACV,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,MAAM,CAAA;IAE5C;;OAEG;IACH,MAAM,MAAM,aAAa,GAAG;QAC1B;;;WAGG;QACH,KAAK,CAAC,EAAE,OAAO,CAAA;QACf;;WAEG;QACH,MAAM,CAAC,EAAE,WAAW,CAAA;QACpB;;;;;WAKG;QACH,QAAQ,CAAC,EAAE,cAAc,GAAG,IAAI,GAAG,QAAQ,CAAA;QAC3C;;;;;WAKG;QACH,UAAU,CAAC,EAAE,OAAO,CAAA;KACrB,CAAA;IAED;;OAEG;IACH,MAAM,MAAM,eAAe,GAAG,aAAa,GAAG;QAC5C,QAAQ,EAAE,cAAc,CAAA;QACxB,UAAU,CAAC,EAAE,KAAK,CAAA;KACnB,CAAA;IAED;;OAEG;IACH,MAAM,MAAM,aAAa,GAAG,aAAa,GAAG;QAC1C,QAAQ,CAAC,EAAE,IAAI,GAAG,QAAQ,CAAA;QAC1B,UAAU,CAAC,EAAE,KAAK,CAAA;KACnB,CAAA;IAED;;OAEG;IACH,MAAM,MAAM,iBAAiB,GAAG,aAAa,GAAG;QAC9C,UAAU,EAAE,IAAI,CAAA;QAChB,QAAQ,CAAC,EAAE,IAAI,CAAA;KAChB,CAAA;IAED;;OAEG;IACH,MAAM,MAAM,OAAO,CAAC,CAAC,IACjB,iBAAiB,GACjB,CAAC,CAAC,SAAS,MAAM,GACb,eAAe,GACf,CAAC,SAAS,MAAM,GAChB,aAAa,GACb,aAAa,CAAC,CAAA;;CACvB;AAWD;;;;;;;;;;GAUG;AACH,qBAAa,QAAQ,CACjB,KAAK,SAAS,OAAO,GAAG,MAAM,EAC9B,KAAK,SAAS,OAAO,GAAG,KAAK,SAAS,QAAQ,CAAC,cAAc,GACzD,QAAQ,CAAC,cAAc,GACvB,KAAK,EACT,MAAM,SAAS,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAEhE,SAAQ,YACR,YAAW,QAAQ,CAAC,YAAY,CAAC,KAAK,CAAC;IAEvC,CAAC,OAAO,CAAC,EAAE,OAAO,CAAS;IAC3B,CAAC,MAAM,CAAC,EAAE,OAAO,CAAS;IAC1B,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAM;IAC5B,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAM;IACvB,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IACtB,CAAC,QAAQ,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;IAClC,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACjB,CAAC,OAAO,CAAC,EAAE,EAAE,GAAG,IAAI,CAAC;IACrB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAS;IACvB,CAAC,WAAW,CAAC,EAAE,OAAO,CAAS;IAC/B,CAAC,YAAY,CAAC,EAAE,OAAO,CAAS;IAChC,CAAC,MAAM,CAAC,EAAE,OAAO,CAAS;IAC1B,CAAC,aAAa,CAAC,EAAE,OAAO,CAAQ;IAChC,CAAC,YAAY,CAAC,EAAE,MAAM,CAAK;IAC3B,CAAC,SAAS,CAAC,EAAE,OAAO,CAAS;IAC7B,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,CAAC;IACvB,CAAC,OAAO,CAAC,EAAE,OAAO,CAAS;IAC3B,CAAC,aAAa,CAAC,EAAE,MAAM,CAAK;IAC5B,CAAC,SAAS,CAAC,EAAE,OAAO,CAAQ;IAE5B;;OAEG;IACH,QAAQ,EAAE,OAAO,CAAO;IACxB;;OAEG;IACH,QAAQ,EAAE,OAAO,CAAO;IAExB;;;;;OAKG;IACH,YACE,GAAG,IAAI,EACH,CAAC,QAAQ,CAAC,iBAAiB,CAAC,GAC5B,CAAC,KAAK,SAAS,MAAM,GACjB,EAAE,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAC9B,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EA2CnC;IAED;;;;;;;;OAQG;IACH,IAAI,YAAY,WAEf;IAED;;OAEG;IACH,IAAI,QAAQ,0BAEX;IAED;;OAEG;IACH,IAAI,QAAQ,CAAC,IAAI,uBAAA,EAEhB;IAED;;OAEG;IACH,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,QAAQ,QAElC;IAED;;OAEG;IACH,IAAI,UAAU,YAEb;IAED;;OAEG;IACH,IAAI,UAAU,CAAC,GAAG,SAAA,EAEjB;IAED;;OAEG;IACH,IAAI,CAAC,OAAO,CAAC,IAAI,OAAO,CAEvB;IACD;;;;;;OAMG;IACH,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAEvB;IAGD,CAAC,KAAK,CAAC,SAIN;IAED;;OAEG;IACH,IAAI,OAAO,YAEV;IACD;;;OAGG;IACH,IAAI,OAAO,CAAC,CAAC,SAAA,EAAI;IAEjB;;;;;;;;;;;;;;;;;OAiBG;IACH,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAA;IAC7C,KAAK,CACH,KAAK,EAAE,KAAK,EACZ,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,EAC5B,EAAE,CAAC,EAAE,MAAM,IAAI,GACd,OAAO,CAAA;IA0GV;;;;;;;;;;;;OAYG;IACH,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,CA+BpC;IAED,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,SAqBpC;IAED;;;;OAIG;IACH,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAA;IAC1B,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAA;IACxC,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI,CAAA;IA4BtE,CAAC,MAAM,CAAC,SAYP;IAED;;;;;;;;OAQG;IACH,MAAM,SAEL;IAED;;OAEG;IACH,KAAK,SAIJ;IAED;;OAEG;IACH,IAAI,SAAS,YAEZ;IAED;;;OAGG;IACH,IAAI,OAAO,YAEV;IAED;;OAEG;IACH,IAAI,MAAM,YAET;IAED,CAAC,UAAU,CAAC,CAAC,KAAK,EAAE,KAAK,QAIxB;IAED,CAAC,WAAW,CAAC,IAAI,KAAK,CAOrB;IAED,CAAC,KAAK,CAAC,CAAC,OAAO,GAAE,OAAe,QAO/B;IAED,CAAC,UAAU,CAAC,CAAC,KAAK,EAAE,KAAK,WAGxB;IAED;;;;OAIG;IACH,IAAI,CAAC,CAAC,SAAS,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,CAAC,CA0BhE;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,CAAC,SAAS,QAAQ,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,QAW1C;IAED;;OAEG;IACH,WAAW,CAAC,KAAK,SAAS,MAAM,MAAM,EACpC,EAAE,EAAE,KAAK,EACT,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,GAAG,GACvC,IAAI,CAEN;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,EAAE,CAAC,KAAK,SAAS,MAAM,MAAM,EAC3B,EAAE,EAAE,KAAK,EACT,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,GAAG,GACvC,IAAI,CAsBN;IAED;;OAEG;IACH,cAAc,CAAC,KAAK,SAAS,MAAM,MAAM,EACvC,EAAE,EAAE,KAAK,EACT,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,GAAG,QAGzC;IAED;;;;;;;OAOG;IACH,GAAG,CAAC,KAAK,SAAS,MAAM,MAAM,EAC5B,EAAE,EAAE,KAAK,EACT,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,GAAG,QAoBzC;IAED;;;;;;;OAOG;IACH,kBAAkB,CAAC,KAAK,SAAS,MAAM,MAAM,EAAE,EAAE,CAAC,EAAE,KAAK,QASxD;IAED;;OAEG;IACH,IAAI,UAAU,YAEb;IAED,CAAC,cAAc,CAAC,SAef;IAED;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAI,CAAC,KAAK,SAAS,MAAM,MAAM,EAC7B,EAAE,EAAE,KAAK,EACT,GAAG,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,GACrB,OAAO,CAgDT;IAED,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,KAAK,WAOrB;IAED,CAAC,OAAO,CAAC,YAQR;IAED,CAAC,QAAQ,CAAC,YAiBT;IAED;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,KAAK,EAAE,GAAG;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAezD;IAED;;;;;OAKG;IACG,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC,CAU7B;IAED;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAM7B;IAED;;;;OAIG;IACH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CA4D1D;IAED;;;;;OAKG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CAiChD;IAED;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAE,CAAC,EAAE,OAAO,QAwBnB;IAED;;;;;;OAMG;IACH,MAAM,KAAK,QAAQ;;;;;;;;;;;OAElB;CACF","sourcesContent":["const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n src: Minipass\n dest: Minipass\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable = Iterable & AsyncIterable\n\n type EventArguments = Record\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events = Minipass.Events\n >\n extends EventEmitter\n implements Minipass.DualIterable\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options]\n : [Minipass.Options])\n ) {\n const options: Minipass.Options = (args[0] ||\n {}) as Minipass.Options\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe(this as Minipass, dest, opts)\n : new PipeProxyErrors(this as Minipass, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise {\n return new Promise((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n [Symbol.asyncDispose]: async () => {},\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n [Symbol.dispose]: () => {},\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/minipass/dist/esm/index.js b/tools/ui/node_modules/minipass/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5df55461e3d491bc3aa37ef28e274f3beacfd6ad --- /dev/null +++ b/tools/ui/node_modules/minipass/dist/esm/index.js @@ -0,0 +1,1020 @@ +const proc = typeof process === 'object' && process + ? process + : { + stdout: null, + stderr: null, + }; +import { EventEmitter } from 'node:events'; +import Stream from 'node:stream'; +import { StringDecoder } from 'node:string_decoder'; +/** + * Return true if the argument is a Minipass stream, Node stream, or something + * else that Minipass can interact with. + */ +export const isStream = (s) => !!s && + typeof s === 'object' && + (s instanceof Minipass || + s instanceof Stream || + isReadable(s) || + isWritable(s)); +/** + * Return true if the argument is a valid {@link Minipass.Readable} + */ +export const isReadable = (s) => !!s && + typeof s === 'object' && + s instanceof EventEmitter && + typeof s.pipe === 'function' && + // node core Writable streams have a pipe() method, but it throws + s.pipe !== Stream.Writable.prototype.pipe; +/** + * Return true if the argument is a valid {@link Minipass.Writable} + */ +export const isWritable = (s) => !!s && + typeof s === 'object' && + s instanceof EventEmitter && + typeof s.write === 'function' && + typeof s.end === 'function'; +const EOF = Symbol('EOF'); +const MAYBE_EMIT_END = Symbol('maybeEmitEnd'); +const EMITTED_END = Symbol('emittedEnd'); +const EMITTING_END = Symbol('emittingEnd'); +const EMITTED_ERROR = Symbol('emittedError'); +const CLOSED = Symbol('closed'); +const READ = Symbol('read'); +const FLUSH = Symbol('flush'); +const FLUSHCHUNK = Symbol('flushChunk'); +const ENCODING = Symbol('encoding'); +const DECODER = Symbol('decoder'); +const FLOWING = Symbol('flowing'); +const PAUSED = Symbol('paused'); +const RESUME = Symbol('resume'); +const BUFFER = Symbol('buffer'); +const PIPES = Symbol('pipes'); +const BUFFERLENGTH = Symbol('bufferLength'); +const BUFFERPUSH = Symbol('bufferPush'); +const BUFFERSHIFT = Symbol('bufferShift'); +const OBJECTMODE = Symbol('objectMode'); +// internal event when stream is destroyed +const DESTROYED = Symbol('destroyed'); +// internal event when stream has an error +const ERROR = Symbol('error'); +const EMITDATA = Symbol('emitData'); +const EMITEND = Symbol('emitEnd'); +const EMITEND2 = Symbol('emitEnd2'); +const ASYNC = Symbol('async'); +const ABORT = Symbol('abort'); +const ABORTED = Symbol('aborted'); +const SIGNAL = Symbol('signal'); +const DATALISTENERS = Symbol('dataListeners'); +const DISCARDED = Symbol('discarded'); +const defer = (fn) => Promise.resolve().then(fn); +const nodefer = (fn) => fn(); +const isEndish = (ev) => ev === 'end' || ev === 'finish' || ev === 'prefinish'; +const isArrayBufferLike = (b) => b instanceof ArrayBuffer || + (!!b && + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0); +const isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b); +/** + * Internal class representing a pipe to a destination stream. + * + * @internal + */ +class Pipe { + src; + dest; + opts; + ondrain; + constructor(src, dest, opts) { + this.src = src; + this.dest = dest; + this.opts = opts; + this.ondrain = () => src[RESUME](); + this.dest.on('drain', this.ondrain); + } + unpipe() { + this.dest.removeListener('drain', this.ondrain); + } + // only here for the prototype + /* c8 ignore start */ + proxyErrors(_er) { } + /* c8 ignore stop */ + end() { + this.unpipe(); + if (this.opts.end) + this.dest.end(); + } +} +/** + * Internal class representing a pipe to a destination stream where + * errors are proxied. + * + * @internal + */ +class PipeProxyErrors extends Pipe { + unpipe() { + this.src.removeListener('error', this.proxyErrors); + super.unpipe(); + } + constructor(src, dest, opts) { + super(src, dest, opts); + this.proxyErrors = (er) => this.dest.emit('error', er); + src.on('error', this.proxyErrors); + } +} +const isObjectModeOptions = (o) => !!o.objectMode; +const isEncodingOptions = (o) => !o.objectMode && !!o.encoding && o.encoding !== 'buffer'; +/** + * Main export, the Minipass class + * + * `RType` is the type of data emitted, defaults to Buffer + * + * `WType` is the type of data to be written, if RType is buffer or string, + * then any {@link Minipass.ContiguousData} is allowed. + * + * `Events` is the set of event handler signatures that this object + * will emit, see {@link Minipass.Events} + */ +export class Minipass extends EventEmitter { + [FLOWING] = false; + [PAUSED] = false; + [PIPES] = []; + [BUFFER] = []; + [OBJECTMODE]; + [ENCODING]; + [ASYNC]; + [DECODER]; + [EOF] = false; + [EMITTED_END] = false; + [EMITTING_END] = false; + [CLOSED] = false; + [EMITTED_ERROR] = null; + [BUFFERLENGTH] = 0; + [DESTROYED] = false; + [SIGNAL]; + [ABORTED] = false; + [DATALISTENERS] = 0; + [DISCARDED] = false; + /** + * true if the stream can be written + */ + writable = true; + /** + * true if the stream can be read + */ + readable = true; + /** + * If `RType` is Buffer, then options do not need to be provided. + * Otherwise, an options object must be provided to specify either + * {@link Minipass.SharedOptions.objectMode} or + * {@link Minipass.SharedOptions.encoding}, as appropriate. + */ + constructor(...args) { + const options = (args[0] || + {}); + super(); + if (options.objectMode && typeof options.encoding === 'string') { + throw new TypeError('Encoding and objectMode may not be used together'); + } + if (isObjectModeOptions(options)) { + this[OBJECTMODE] = true; + this[ENCODING] = null; + } + else if (isEncodingOptions(options)) { + this[ENCODING] = options.encoding; + this[OBJECTMODE] = false; + } + else { + this[OBJECTMODE] = false; + this[ENCODING] = null; + } + this[ASYNC] = !!options.async; + this[DECODER] = this[ENCODING] + ? new StringDecoder(this[ENCODING]) + : null; + //@ts-ignore - private option for debugging and testing + if (options && options.debugExposeBuffer === true) { + Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] }); + } + //@ts-ignore - private option for debugging and testing + if (options && options.debugExposePipes === true) { + Object.defineProperty(this, 'pipes', { get: () => this[PIPES] }); + } + const { signal } = options; + if (signal) { + this[SIGNAL] = signal; + if (signal.aborted) { + this[ABORT](); + } + else { + signal.addEventListener('abort', () => this[ABORT]()); + } + } + } + /** + * The amount of data stored in the buffer waiting to be read. + * + * For Buffer strings, this will be the total byte length. + * For string encoding streams, this will be the string character length, + * according to JavaScript's `string.length` logic. + * For objectMode streams, this is a count of the items waiting to be + * emitted. + */ + get bufferLength() { + return this[BUFFERLENGTH]; + } + /** + * The `BufferEncoding` currently in use, or `null` + */ + get encoding() { + return this[ENCODING]; + } + /** + * @deprecated - This is a read only property + */ + set encoding(_enc) { + throw new Error('Encoding must be set at instantiation time'); + } + /** + * @deprecated - Encoding may only be set at instantiation time + */ + setEncoding(_enc) { + throw new Error('Encoding must be set at instantiation time'); + } + /** + * True if this is an objectMode stream + */ + get objectMode() { + return this[OBJECTMODE]; + } + /** + * @deprecated - This is a read-only property + */ + set objectMode(_om) { + throw new Error('objectMode must be set at instantiation time'); + } + /** + * true if this is an async stream + */ + get ['async']() { + return this[ASYNC]; + } + /** + * Set to true to make this stream async. + * + * Once set, it cannot be unset, as this would potentially cause incorrect + * behavior. Ie, a sync stream can be made async, but an async stream + * cannot be safely made sync. + */ + set ['async'](a) { + this[ASYNC] = this[ASYNC] || !!a; + } + // drop everything and get out of the flow completely + [ABORT]() { + this[ABORTED] = true; + this.emit('abort', this[SIGNAL]?.reason); + this.destroy(this[SIGNAL]?.reason); + } + /** + * True if the stream has been aborted. + */ + get aborted() { + return this[ABORTED]; + } + /** + * No-op setter. Stream aborted status is set via the AbortSignal provided + * in the constructor options. + */ + set aborted(_) { } + write(chunk, encoding, cb) { + if (this[ABORTED]) + return false; + if (this[EOF]) + throw new Error('write after end'); + if (this[DESTROYED]) { + this.emit('error', Object.assign(new Error('Cannot call write after a stream was destroyed'), { code: 'ERR_STREAM_DESTROYED' })); + return true; + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = 'utf8'; + } + if (!encoding) + encoding = 'utf8'; + const fn = this[ASYNC] ? defer : nodefer; + // convert array buffers and typed array views into buffers + // at some point in the future, we may want to do the opposite! + // leave strings and buffers as-is + // anything is only allowed if in object mode, so throw + if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { + if (isArrayBufferView(chunk)) { + //@ts-ignore - sinful unsafe type changing + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength); + } + else if (isArrayBufferLike(chunk)) { + //@ts-ignore - sinful unsafe type changing + chunk = Buffer.from(chunk); + } + else if (typeof chunk !== 'string') { + throw new Error('Non-contiguous data written to non-objectMode stream'); + } + } + // handle object mode up front, since it's simpler + // this yields better performance, fewer checks later. + if (this[OBJECTMODE]) { + // maybe impossible? + /* c8 ignore start */ + if (this[FLOWING] && this[BUFFERLENGTH] !== 0) + this[FLUSH](true); + /* c8 ignore stop */ + if (this[FLOWING]) + this.emit('data', chunk); + else + this[BUFFERPUSH](chunk); + if (this[BUFFERLENGTH] !== 0) + this.emit('readable'); + if (cb) + fn(cb); + return this[FLOWING]; + } + // at this point the chunk is a buffer or string + // don't buffer it up or send it to the decoder + if (!chunk.length) { + if (this[BUFFERLENGTH] !== 0) + this.emit('readable'); + if (cb) + fn(cb); + return this[FLOWING]; + } + // fast-path writing strings of same encoding to a stream with + // an empty buffer, skipping the buffer/decoder dance + if (typeof chunk === 'string' && + // unless it is a string already ready for us to use + !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) { + //@ts-ignore - sinful unsafe type change + chunk = Buffer.from(chunk, encoding); + } + if (Buffer.isBuffer(chunk) && this[ENCODING]) { + //@ts-ignore - sinful unsafe type change + chunk = this[DECODER].write(chunk); + } + // Note: flushing CAN potentially switch us into not-flowing mode + if (this[FLOWING] && this[BUFFERLENGTH] !== 0) + this[FLUSH](true); + if (this[FLOWING]) + this.emit('data', chunk); + else + this[BUFFERPUSH](chunk); + if (this[BUFFERLENGTH] !== 0) + this.emit('readable'); + if (cb) + fn(cb); + return this[FLOWING]; + } + /** + * Low-level explicit read method. + * + * In objectMode, the argument is ignored, and one item is returned if + * available. + * + * `n` is the number of bytes (or in the case of encoding streams, + * characters) to consume. If `n` is not provided, then the entire buffer + * is returned, or `null` is returned if no data is available. + * + * If `n` is greater that the amount of data in the internal buffer, + * then `null` is returned. + */ + read(n) { + if (this[DESTROYED]) + return null; + this[DISCARDED] = false; + if (this[BUFFERLENGTH] === 0 || + n === 0 || + (n && n > this[BUFFERLENGTH])) { + this[MAYBE_EMIT_END](); + return null; + } + if (this[OBJECTMODE]) + n = null; + if (this[BUFFER].length > 1 && !this[OBJECTMODE]) { + // not object mode, so if we have an encoding, then RType is string + // otherwise, must be Buffer + this[BUFFER] = [ + (this[ENCODING] + ? this[BUFFER].join('') + : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])), + ]; + } + const ret = this[READ](n || null, this[BUFFER][0]); + this[MAYBE_EMIT_END](); + return ret; + } + [READ](n, chunk) { + if (this[OBJECTMODE]) + this[BUFFERSHIFT](); + else { + const c = chunk; + if (n === c.length || n === null) + this[BUFFERSHIFT](); + else if (typeof c === 'string') { + this[BUFFER][0] = c.slice(n); + chunk = c.slice(0, n); + this[BUFFERLENGTH] -= n; + } + else { + this[BUFFER][0] = c.subarray(n); + chunk = c.subarray(0, n); + this[BUFFERLENGTH] -= n; + } + } + this.emit('data', chunk); + if (!this[BUFFER].length && !this[EOF]) + this.emit('drain'); + return chunk; + } + end(chunk, encoding, cb) { + if (typeof chunk === 'function') { + cb = chunk; + chunk = undefined; + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = 'utf8'; + } + if (chunk !== undefined) + this.write(chunk, encoding); + if (cb) + this.once('end', cb); + this[EOF] = true; + this.writable = false; + // if we haven't written anything, then go ahead and emit, + // even if we're not reading. + // we'll re-emit if a new 'end' listener is added anyway. + // This makes MP more suitable to write-only use cases. + if (this[FLOWING] || !this[PAUSED]) + this[MAYBE_EMIT_END](); + return this; + } + // don't let the internal resume be overwritten + [RESUME]() { + if (this[DESTROYED]) + return; + if (!this[DATALISTENERS] && !this[PIPES].length) { + this[DISCARDED] = true; + } + this[PAUSED] = false; + this[FLOWING] = true; + this.emit('resume'); + if (this[BUFFER].length) + this[FLUSH](); + else if (this[EOF]) + this[MAYBE_EMIT_END](); + else + this.emit('drain'); + } + /** + * Resume the stream if it is currently in a paused state + * + * If called when there are no pipe destinations or `data` event listeners, + * this will place the stream in a "discarded" state, where all data will + * be thrown away. The discarded state is removed if a pipe destination or + * data handler is added, if pause() is called, or if any synchronous or + * asynchronous iteration is started. + */ + resume() { + return this[RESUME](); + } + /** + * Pause the stream + */ + pause() { + this[FLOWING] = false; + this[PAUSED] = true; + this[DISCARDED] = false; + } + /** + * true if the stream has been forcibly destroyed + */ + get destroyed() { + return this[DESTROYED]; + } + /** + * true if the stream is currently in a flowing state, meaning that + * any writes will be immediately emitted. + */ + get flowing() { + return this[FLOWING]; + } + /** + * true if the stream is currently in a paused state + */ + get paused() { + return this[PAUSED]; + } + [BUFFERPUSH](chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1; + else + this[BUFFERLENGTH] += chunk.length; + this[BUFFER].push(chunk); + } + [BUFFERSHIFT]() { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1; + else + this[BUFFERLENGTH] -= this[BUFFER][0].length; + return this[BUFFER].shift(); + } + [FLUSH](noDrain = false) { + do { } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && + this[BUFFER].length); + if (!noDrain && !this[BUFFER].length && !this[EOF]) + this.emit('drain'); + } + [FLUSHCHUNK](chunk) { + this.emit('data', chunk); + return this[FLOWING]; + } + /** + * Pipe all data emitted by this stream into the destination provided. + * + * Triggers the flow of data. + */ + pipe(dest, opts) { + if (this[DESTROYED]) + return dest; + this[DISCARDED] = false; + const ended = this[EMITTED_END]; + opts = opts || {}; + if (dest === proc.stdout || dest === proc.stderr) + opts.end = false; + else + opts.end = opts.end !== false; + opts.proxyErrors = !!opts.proxyErrors; + // piping an ended stream ends immediately + if (ended) { + if (opts.end) + dest.end(); + } + else { + // "as" here just ignores the WType, which pipes don't care about, + // since they're only consuming from us, and writing to the dest + this[PIPES].push(!opts.proxyErrors + ? new Pipe(this, dest, opts) + : new PipeProxyErrors(this, dest, opts)); + if (this[ASYNC]) + defer(() => this[RESUME]()); + else + this[RESUME](); + } + return dest; + } + /** + * Fully unhook a piped destination stream. + * + * If the destination stream was the only consumer of this stream (ie, + * there are no other piped destinations or `'data'` event listeners) + * then the flow of data will stop until there is another consumer or + * {@link Minipass#resume} is explicitly called. + */ + unpipe(dest) { + const p = this[PIPES].find(p => p.dest === dest); + if (p) { + if (this[PIPES].length === 1) { + if (this[FLOWING] && this[DATALISTENERS] === 0) { + this[FLOWING] = false; + } + this[PIPES] = []; + } + else + this[PIPES].splice(this[PIPES].indexOf(p), 1); + p.unpipe(); + } + } + /** + * Alias for {@link Minipass#on} + */ + addListener(ev, handler) { + return this.on(ev, handler); + } + /** + * Mostly identical to `EventEmitter.on`, with the following + * behavior differences to prevent data loss and unnecessary hangs: + * + * - Adding a 'data' event handler will trigger the flow of data + * + * - Adding a 'readable' event handler when there is data waiting to be read + * will cause 'readable' to be emitted immediately. + * + * - Adding an 'endish' event handler ('end', 'finish', etc.) which has + * already passed will cause the event to be emitted immediately and all + * handlers removed. + * + * - Adding an 'error' event handler after an error has been emitted will + * cause the event to be re-emitted immediately with the error previously + * raised. + */ + on(ev, handler) { + const ret = super.on(ev, handler); + if (ev === 'data') { + this[DISCARDED] = false; + this[DATALISTENERS]++; + if (!this[PIPES].length && !this[FLOWING]) { + this[RESUME](); + } + } + else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) { + super.emit('readable'); + } + else if (isEndish(ev) && this[EMITTED_END]) { + super.emit(ev); + this.removeAllListeners(ev); + } + else if (ev === 'error' && this[EMITTED_ERROR]) { + const h = handler; + if (this[ASYNC]) + defer(() => h.call(this, this[EMITTED_ERROR])); + else + h.call(this, this[EMITTED_ERROR]); + } + return ret; + } + /** + * Alias for {@link Minipass#off} + */ + removeListener(ev, handler) { + return this.off(ev, handler); + } + /** + * Mostly identical to `EventEmitter.off` + * + * If a 'data' event handler is removed, and it was the last consumer + * (ie, there are no pipe destinations or other 'data' event listeners), + * then the flow of data will stop until there is another consumer or + * {@link Minipass#resume} is explicitly called. + */ + off(ev, handler) { + const ret = super.off(ev, handler); + // if we previously had listeners, and now we don't, and we don't + // have any pipes, then stop the flow, unless it's been explicitly + // put in a discarded flowing state via stream.resume(). + if (ev === 'data') { + this[DATALISTENERS] = this.listeners('data').length; + if (this[DATALISTENERS] === 0 && + !this[DISCARDED] && + !this[PIPES].length) { + this[FLOWING] = false; + } + } + return ret; + } + /** + * Mostly identical to `EventEmitter.removeAllListeners` + * + * If all 'data' event handlers are removed, and they were the last consumer + * (ie, there are no pipe destinations), then the flow of data will stop + * until there is another consumer or {@link Minipass#resume} is explicitly + * called. + */ + removeAllListeners(ev) { + const ret = super.removeAllListeners(ev); + if (ev === 'data' || ev === undefined) { + this[DATALISTENERS] = 0; + if (!this[DISCARDED] && !this[PIPES].length) { + this[FLOWING] = false; + } + } + return ret; + } + /** + * true if the 'end' event has been emitted + */ + get emittedEnd() { + return this[EMITTED_END]; + } + [MAYBE_EMIT_END]() { + if (!this[EMITTING_END] && + !this[EMITTED_END] && + !this[DESTROYED] && + this[BUFFER].length === 0 && + this[EOF]) { + this[EMITTING_END] = true; + this.emit('end'); + this.emit('prefinish'); + this.emit('finish'); + if (this[CLOSED]) + this.emit('close'); + this[EMITTING_END] = false; + } + } + /** + * Mostly identical to `EventEmitter.emit`, with the following + * behavior differences to prevent data loss and unnecessary hangs: + * + * If the stream has been destroyed, and the event is something other + * than 'close' or 'error', then `false` is returned and no handlers + * are called. + * + * If the event is 'end', and has already been emitted, then the event + * is ignored. If the stream is in a paused or non-flowing state, then + * the event will be deferred until data flow resumes. If the stream is + * async, then handlers will be called on the next tick rather than + * immediately. + * + * If the event is 'close', and 'end' has not yet been emitted, then + * the event will be deferred until after 'end' is emitted. + * + * If the event is 'error', and an AbortSignal was provided for the stream, + * and there are no listeners, then the event is ignored, matching the + * behavior of node core streams in the presense of an AbortSignal. + * + * If the event is 'finish' or 'prefinish', then all listeners will be + * removed after emitting the event, to prevent double-firing. + */ + emit(ev, ...args) { + const data = args[0]; + // error and close are only events allowed after calling destroy() + if (ev !== 'error' && + ev !== 'close' && + ev !== DESTROYED && + this[DESTROYED]) { + return false; + } + else if (ev === 'data') { + return !this[OBJECTMODE] && !data + ? false + : this[ASYNC] + ? (defer(() => this[EMITDATA](data)), true) + : this[EMITDATA](data); + } + else if (ev === 'end') { + return this[EMITEND](); + } + else if (ev === 'close') { + this[CLOSED] = true; + // don't emit close before 'end' and 'finish' + if (!this[EMITTED_END] && !this[DESTROYED]) + return false; + const ret = super.emit('close'); + this.removeAllListeners('close'); + return ret; + } + else if (ev === 'error') { + this[EMITTED_ERROR] = data; + super.emit(ERROR, data); + const ret = !this[SIGNAL] || this.listeners('error').length + ? super.emit('error', data) + : false; + this[MAYBE_EMIT_END](); + return ret; + } + else if (ev === 'resume') { + const ret = super.emit('resume'); + this[MAYBE_EMIT_END](); + return ret; + } + else if (ev === 'finish' || ev === 'prefinish') { + const ret = super.emit(ev); + this.removeAllListeners(ev); + return ret; + } + // Some other unknown event + const ret = super.emit(ev, ...args); + this[MAYBE_EMIT_END](); + return ret; + } + [EMITDATA](data) { + for (const p of this[PIPES]) { + if (p.dest.write(data) === false) + this.pause(); + } + const ret = this[DISCARDED] ? false : super.emit('data', data); + this[MAYBE_EMIT_END](); + return ret; + } + [EMITEND]() { + if (this[EMITTED_END]) + return false; + this[EMITTED_END] = true; + this.readable = false; + return this[ASYNC] + ? (defer(() => this[EMITEND2]()), true) + : this[EMITEND2](); + } + [EMITEND2]() { + if (this[DECODER]) { + const data = this[DECODER].end(); + if (data) { + for (const p of this[PIPES]) { + p.dest.write(data); + } + if (!this[DISCARDED]) + super.emit('data', data); + } + } + for (const p of this[PIPES]) { + p.end(); + } + const ret = super.emit('end'); + this.removeAllListeners('end'); + return ret; + } + /** + * Return a Promise that resolves to an array of all emitted data once + * the stream ends. + */ + async collect() { + const buf = Object.assign([], { + dataLength: 0, + }); + if (!this[OBJECTMODE]) + buf.dataLength = 0; + // set the promise first, in case an error is raised + // by triggering the flow here. + const p = this.promise(); + this.on('data', c => { + buf.push(c); + if (!this[OBJECTMODE]) + buf.dataLength += c.length; + }); + await p; + return buf; + } + /** + * Return a Promise that resolves to the concatenation of all emitted data + * once the stream ends. + * + * Not allowed on objectMode streams. + */ + async concat() { + if (this[OBJECTMODE]) { + throw new Error('cannot concat in objectMode'); + } + const buf = await this.collect(); + return (this[ENCODING] + ? buf.join('') + : Buffer.concat(buf, buf.dataLength)); + } + /** + * Return a void Promise that resolves once the stream ends. + */ + async promise() { + return new Promise((resolve, reject) => { + this.on(DESTROYED, () => reject(new Error('stream destroyed'))); + this.on('error', er => reject(er)); + this.on('end', () => resolve()); + }); + } + /** + * Asynchronous `for await of` iteration. + * + * This will continue emitting all chunks until the stream terminates. + */ + [Symbol.asyncIterator]() { + // set this up front, in case the consumer doesn't call next() + // right away. + this[DISCARDED] = false; + let stopped = false; + const stop = async () => { + this.pause(); + stopped = true; + return { value: undefined, done: true }; + }; + const next = () => { + if (stopped) + return stop(); + const res = this.read(); + if (res !== null) + return Promise.resolve({ done: false, value: res }); + if (this[EOF]) + return stop(); + let resolve; + let reject; + const onerr = (er) => { + this.off('data', ondata); + this.off('end', onend); + this.off(DESTROYED, ondestroy); + stop(); + reject(er); + }; + const ondata = (value) => { + this.off('error', onerr); + this.off('end', onend); + this.off(DESTROYED, ondestroy); + this.pause(); + resolve({ value, done: !!this[EOF] }); + }; + const onend = () => { + this.off('error', onerr); + this.off('data', ondata); + this.off(DESTROYED, ondestroy); + stop(); + resolve({ done: true, value: undefined }); + }; + const ondestroy = () => onerr(new Error('stream destroyed')); + return new Promise((res, rej) => { + reject = rej; + resolve = res; + this.once(DESTROYED, ondestroy); + this.once('error', onerr); + this.once('end', onend); + this.once('data', ondata); + }); + }; + return { + next, + throw: stop, + return: stop, + [Symbol.asyncIterator]() { + return this; + }, + [Symbol.asyncDispose]: async () => { }, + }; + } + /** + * Synchronous `for of` iteration. + * + * The iteration will terminate when the internal buffer runs out, even + * if the stream has not yet terminated. + */ + [Symbol.iterator]() { + // set this up front, in case the consumer doesn't call next() + // right away. + this[DISCARDED] = false; + let stopped = false; + const stop = () => { + this.pause(); + this.off(ERROR, stop); + this.off(DESTROYED, stop); + this.off('end', stop); + stopped = true; + return { done: true, value: undefined }; + }; + const next = () => { + if (stopped) + return stop(); + const value = this.read(); + return value === null ? stop() : { done: false, value }; + }; + this.once('end', stop); + this.once(ERROR, stop); + this.once(DESTROYED, stop); + return { + next, + throw: stop, + return: stop, + [Symbol.iterator]() { + return this; + }, + [Symbol.dispose]: () => { }, + }; + } + /** + * Destroy a stream, preventing it from being used for any further purpose. + * + * If the stream has a `close()` method, then it will be called on + * destruction. + * + * After destruction, any attempt to write data, read data, or emit most + * events will be ignored. + * + * If an error argument is provided, then it will be emitted in an + * 'error' event. + */ + destroy(er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er); + else + this.emit(DESTROYED); + return this; + } + this[DESTROYED] = true; + this[DISCARDED] = true; + // throw away all buffered data, it's never coming out + this[BUFFER].length = 0; + this[BUFFERLENGTH] = 0; + const wc = this; + if (typeof wc.close === 'function' && !this[CLOSED]) + wc.close(); + if (er) + this.emit('error', er); + // if no error to emit, still reject pending promises + else + this.emit(DESTROYED); + return this; + } + /** + * Alias for {@link isStream} + * + * Former export location, maintained for backwards compatibility. + * + * @deprecated + */ + static get isStream() { + return isStream; + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/minipass/dist/esm/index.js.map b/tools/ui/node_modules/minipass/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4d87920cd1b08929301aff5ebbf28ac6e6e34e73 --- /dev/null +++ b/tools/ui/node_modules/minipass/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO;IACpC,CAAC,CAAC,OAAO;IACT,CAAC,CAAC;QACE,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,IAAI;KACb,CAAA;AACP,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AASnD;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAM,EACsC,EAAE,CAC9C,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,CAAC,CAAC,YAAY,QAAQ;QACpB,CAAC,YAAY,MAAM;QACnB,UAAU,CAAC,CAAC,CAAC;QACb,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;AAElB;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,CAAM,EAA0B,EAAE,CAC3D,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,CAAC,YAAY,YAAY;IACzB,OAAQ,CAAuB,CAAC,IAAI,KAAK,UAAU;IACnD,iEAAiE;IAChE,CAAuB,CAAC,IAAI,KAAK,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAA;AAElE;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,CAAM,EAA0B,EAAE,CAC3D,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,QAAQ;IACrB,CAAC,YAAY,YAAY;IACzB,OAAQ,CAAuB,CAAC,KAAK,KAAK,UAAU;IACpD,OAAQ,CAAuB,CAAC,GAAG,KAAK,UAAU,CAAA;AAEpD,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;AACzB,MAAM,cAAc,GAAG,MAAM,CAAC,cAAc,CAAC,CAAA;AAC7C,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;AACxC,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AAC1C,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAA;AAC5C,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAC/B,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA;AAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;AACvC,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAA;AACnC,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AACjC,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AACjC,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAC/B,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAC/B,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,YAAY,GAAG,MAAM,CAAC,cAAc,CAAC,CAAA;AAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;AACvC,MAAM,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AACzC,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAA;AACvC,0CAA0C;AAC1C,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,CAAA;AACrC,0CAA0C;AAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAA;AACnC,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AACjC,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,CAAA;AACnC,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;AAC7B,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,CAAA;AACjC,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;AAC/B,MAAM,aAAa,GAAG,MAAM,CAAC,eAAe,CAAC,CAAA;AAC7C,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,CAAA;AAErC,MAAM,KAAK,GAAG,CAAC,EAAwB,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;AACtE,MAAM,OAAO,GAAG,CAAC,EAAwB,EAAE,EAAE,CAAC,EAAE,EAAE,CAAA;AAMlD,MAAM,QAAQ,GAAG,CAAC,EAAO,EAAqB,EAAE,CAC9C,EAAE,KAAK,KAAK,IAAI,EAAE,KAAK,QAAQ,IAAI,EAAE,KAAK,WAAW,CAAA;AAEvD,MAAM,iBAAiB,GAAG,CAAC,CAAM,EAAwB,EAAE,CACzD,CAAC,YAAY,WAAW;IACxB,CAAC,CAAC,CAAC,CAAC;QACF,OAAO,CAAC,KAAK,QAAQ;QACrB,CAAC,CAAC,WAAW;QACb,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,aAAa;QACpC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,CAAA;AAEtB,MAAM,iBAAiB,GAAG,CAAC,CAAM,EAAwB,EAAE,CACzD,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;AAgB9C;;;;GAIG;AACH,MAAM,IAAI;IACR,GAAG,CAAa;IAChB,IAAI,CAAkB;IACtB,IAAI,CAAa;IACjB,OAAO,CAAW;IAClB,YACE,GAAgB,EAChB,IAAuB,EACvB,IAAiB,EACjB;QACA,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,IAAwB,CAAA;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAA;QAClC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACpC;IACD,MAAM,GAAG;QACP,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CAChD;IACD,8BAA8B;IAC9B,qBAAqB;IACrB,WAAW,CAAC,GAAQ,EAAE,EAAC,CAAC;IACxB,oBAAoB;IACpB,GAAG,GAAG;QACJ,IAAI,CAAC,MAAM,EAAE,CAAA;QACb,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG;YAAE,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAA;IAAA,CACnC;CACF;AAED;;;;;GAKG;AACH,MAAM,eAAmB,SAAQ,IAAO;IACtC,MAAM,GAAG;QACP,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,CAAA;QAClD,KAAK,CAAC,MAAM,EAAE,CAAA;IAAA,CACf;IACD,YACE,GAAgB,EAChB,IAAuB,EACvB,IAAiB,EACjB;QACA,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;QACtB,IAAI,CAAC,WAAW,GAAG,CAAC,EAAS,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;QAC7D,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,CAAA;IAAA,CAClC;CACF;AA6ID,MAAM,mBAAmB,GAAG,CAC1B,CAAyB,EACQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAA;AAEpD,MAAM,iBAAiB,GAAG,CACxB,CAAyB,EACM,EAAE,CACjC,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAA;AAE1D;;;;;;;;;;GAUG;AACH,MAAM,OAAO,QAOX,SAAQ,YAAY;IAGpB,CAAC,OAAO,CAAC,GAAY,KAAK,CAAC;IAC3B,CAAC,MAAM,CAAC,GAAY,KAAK,CAAC;IAC1B,CAAC,KAAK,CAAC,GAAkB,EAAE,CAAC;IAC5B,CAAC,MAAM,CAAC,GAAY,EAAE,CAAC;IACvB,CAAC,UAAU,CAAC,CAAU;IACtB,CAAC,QAAQ,CAAC,CAAwB;IAClC,CAAC,KAAK,CAAC,CAAU;IACjB,CAAC,OAAO,CAAC,CAAY;IACrB,CAAC,GAAG,CAAC,GAAY,KAAK,CAAC;IACvB,CAAC,WAAW,CAAC,GAAY,KAAK,CAAC;IAC/B,CAAC,YAAY,CAAC,GAAY,KAAK,CAAC;IAChC,CAAC,MAAM,CAAC,GAAY,KAAK,CAAC;IAC1B,CAAC,aAAa,CAAC,GAAY,IAAI,CAAC;IAChC,CAAC,YAAY,CAAC,GAAW,CAAC,CAAC;IAC3B,CAAC,SAAS,CAAC,GAAY,KAAK,CAAC;IAC7B,CAAC,MAAM,CAAC,CAAe;IACvB,CAAC,OAAO,CAAC,GAAY,KAAK,CAAC;IAC3B,CAAC,aAAa,CAAC,GAAW,CAAC,CAAC;IAC5B,CAAC,SAAS,CAAC,GAAY,KAAK,CAAA;IAE5B;;OAEG;IACH,QAAQ,GAAY,IAAI,CAAA;IACxB;;OAEG;IACH,QAAQ,GAAY,IAAI,CAAA;IAExB;;;;;OAKG;IACH,YACE,GAAG,IAI+B,EAClC;QACA,MAAM,OAAO,GAA4B,CAAC,IAAI,CAAC,CAAC,CAAC;YAC/C,EAAE,CAA4B,CAAA;QAChC,KAAK,EAAE,CAAA;QACP,IAAI,OAAO,CAAC,UAAU,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC/D,MAAM,IAAI,SAAS,CACjB,kDAAkD,CACnD,CAAA;QACH,CAAC;QACD,IAAI,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;YACjC,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAA;YACvB,IAAI,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAA;QACvB,CAAC;aAAM,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;YACtC,IAAI,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAA;YACjC,IAAI,CAAC,UAAU,CAAC,GAAG,KAAK,CAAA;QAC1B,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,UAAU,CAAC,GAAG,KAAK,CAAA;YACxB,IAAI,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAA;QACvB,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,CAAA;QAC7B,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC;YAC5B,CAAC,CAAE,IAAI,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAQ;YAC3C,CAAC,CAAC,IAAI,CAAA;QAER,uDAAuD;QACvD,IAAI,OAAO,IAAI,OAAO,CAAC,iBAAiB,KAAK,IAAI,EAAE,CAAC;YAClD,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,QAAQ,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;QACpE,CAAC;QACD,uDAAuD;QACvD,IAAI,OAAO,IAAI,OAAO,CAAC,gBAAgB,KAAK,IAAI,EAAE,CAAC;YACjD,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QAClE,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAA;QAC1B,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,MAAM,CAAC,GAAG,MAAM,CAAA;YACrB,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;gBACnB,IAAI,CAAC,KAAK,CAAC,EAAE,CAAA;YACf,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;YACvD,CAAC;QACH,CAAC;IAAA,CACF;IAED;;;;;;;;OAQG;IACH,IAAI,YAAY,GAAG;QACjB,OAAO,IAAI,CAAC,YAAY,CAAC,CAAA;IAAA,CAC1B;IAED;;OAEG;IACH,IAAI,QAAQ,GAAG;QACb,OAAO,IAAI,CAAC,QAAQ,CAAC,CAAA;IAAA,CACtB;IAED;;OAEG;IACH,IAAI,QAAQ,CAAC,IAAI,EAAE;QACjB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAA;IAAA,CAC9D;IAED;;OAEG;IACH,WAAW,CAAC,IAAuB,EAAE;QACnC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAA;IAAA,CAC9D;IAED;;OAEG;IACH,IAAI,UAAU,GAAG;QACf,OAAO,IAAI,CAAC,UAAU,CAAC,CAAA;IAAA,CACxB;IAED;;OAEG;IACH,IAAI,UAAU,CAAC,GAAG,EAAE;QAClB,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAA;IAAA,CAChE;IAED;;OAEG;IACH,IAAI,CAAC,OAAO,CAAC,GAAY;QACvB,OAAO,IAAI,CAAC,KAAK,CAAC,CAAA;IAAA,CACnB;IACD;;;;;;OAMG;IACH,IAAI,CAAC,OAAO,CAAC,CAAC,CAAU,EAAE;QACxB,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IAAA,CACjC;IAED,qDAAqD;IACrD,CAAC,KAAK,CAAC,GAAG;QACR,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAA;QACxC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAA;IAAA,CACnC;IAED;;OAEG;IACH,IAAI,OAAO,GAAG;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACrB;IACD;;;OAGG;IACH,IAAI,OAAO,CAAC,CAAC,EAAE,EAAC,CAAC;IA0BjB,KAAK,CACH,KAAY,EACZ,QAA2C,EAC3C,EAAe,EACN;QACT,IAAI,IAAI,CAAC,OAAO,CAAC;YAAE,OAAO,KAAK,CAAA;QAC/B,IAAI,IAAI,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QAEjD,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YACpB,IAAI,CAAC,IAAI,CACP,OAAO,EACP,MAAM,CAAC,MAAM,CACX,IAAI,KAAK,CAAC,gDAAgD,CAAC,EAC3D,EAAE,IAAI,EAAE,sBAAsB,EAAE,CACjC,CACF,CAAA;YACD,OAAO,IAAI,CAAA;QACb,CAAC;QAED,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;YACnC,EAAE,GAAG,QAAQ,CAAA;YACb,QAAQ,GAAG,MAAM,CAAA;QACnB,CAAC;QAED,IAAI,CAAC,QAAQ;YAAE,QAAQ,GAAG,MAAM,CAAA;QAEhC,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAA;QAExC,2DAA2D;QAC3D,+DAA+D;QAC/D,kCAAkC;QAClC,uDAAuD;QACvD,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACjD,IAAI,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC7B,0CAA0C;gBAC1C,KAAK,GAAG,MAAM,CAAC,IAAI,CACjB,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,UAAU,CACjB,CAAA;YACH,CAAC;iBAAM,IAAI,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC;gBACpC,0CAA0C;gBAC1C,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YAC5B,CAAC;iBAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBACrC,MAAM,IAAI,KAAK,CACb,sDAAsD,CACvD,CAAA;YACH,CAAC;QACH,CAAC;QAED,kDAAkD;QAClD,sDAAsD;QACtD,IAAI,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YACrB,oBAAoB;YACpB,qBAAqB;YACrB,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;gBAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAA;YAChE,oBAAoB;YAEpB,IAAI,IAAI,CAAC,OAAO,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAyB,CAAC,CAAA;;gBAC1D,IAAI,CAAC,UAAU,CAAC,CAAC,KAAyB,CAAC,CAAA;YAEhD,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;YAEnD,IAAI,EAAE;gBAAE,EAAE,CAAC,EAAE,CAAC,CAAA;YAEd,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;QACtB,CAAC;QAED,gDAAgD;QAChD,+CAA+C;QAC/C,IAAI,CAAE,KAAiC,CAAC,MAAM,EAAE,CAAC;YAC/C,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;YACnD,IAAI,EAAE;gBAAE,EAAE,CAAC,EAAE,CAAC,CAAA;YACd,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;QACtB,CAAC;QAED,8DAA8D;QAC9D,qDAAqD;QACrD,IACE,OAAO,KAAK,KAAK,QAAQ;YACzB,oDAAoD;YACpD,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,EAC1D,CAAC;YACD,wCAAwC;YACxC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QACtC,CAAC;QAED,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7C,wCAAwC;YACxC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACpC,CAAC;QAED,iEAAiE;QACjE,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;YAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAA;QAEhE,IAAI,IAAI,CAAC,OAAO,CAAC;YAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAyB,CAAC,CAAA;;YAC1D,IAAI,CAAC,UAAU,CAAC,CAAC,KAAyB,CAAC,CAAA;QAEhD,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;YAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;QAEnD,IAAI,EAAE;YAAE,EAAE,CAAC,EAAE,CAAC,CAAA;QAEd,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACrB;IAED;;;;;;;;;;;;OAYG;IACH,IAAI,CAAC,CAAiB,EAAgB;QACpC,IAAI,IAAI,CAAC,SAAS,CAAC;YAAE,OAAO,IAAI,CAAA;QAChC,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAA;QAEvB,IACE,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;YACxB,CAAC,KAAK,CAAC;YACP,CAAC,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,EAC7B,CAAC;YACD,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;YACtB,OAAO,IAAI,CAAA;QACb,CAAC;QAED,IAAI,IAAI,CAAC,UAAU,CAAC;YAAE,CAAC,GAAG,IAAI,CAAA;QAE9B,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YACjD,mEAAmE;YACnE,4BAA4B;YAC5B,IAAI,CAAC,MAAM,CAAC,GAAG;gBACb,CAAC,IAAI,CAAC,QAAQ,CAAC;oBACb,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;oBACvB,CAAC,CAAC,MAAM,CAAC,MAAM,CACX,IAAI,CAAC,MAAM,CAAa,EACxB,IAAI,CAAC,YAAY,CAAC,CACnB,CAAU;aAChB,CAAA;QACH,CAAC;QAED,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAU,CAAC,CAAA;QAC3D,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;QACtB,OAAO,GAAG,CAAA;IAAA,CACX;IAED,CAAC,IAAI,CAAC,CAAC,CAAgB,EAAE,KAAY,EAAE;QACrC,IAAI,IAAI,CAAC,UAAU,CAAC;YAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAA;aACpC,CAAC;YACJ,MAAM,CAAC,GAAG,KAAgC,CAAA;YAC1C,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,IAAI;gBAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAA;iBAChD,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE,CAAC;gBAC/B,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAU,CAAA;gBACrC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAU,CAAA;gBAC9B,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAA;YACzB,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAU,CAAA;gBACxC,KAAK,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAU,CAAA;gBACjC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAA;YACzB,CAAC;QACH,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QAExB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;YAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAE1D,OAAO,KAAK,CAAA;IAAA,CACb;IAUD,GAAG,CACD,KAA4B,EAC5B,QAA2C,EAC3C,EAAe,EACT;QACN,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;YAChC,EAAE,GAAG,KAAmB,CAAA;YACxB,KAAK,GAAG,SAAS,CAAA;QACnB,CAAC;QACD,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;YACnC,EAAE,GAAG,QAAQ,CAAA;YACb,QAAQ,GAAG,MAAM,CAAA;QACnB,CAAC;QACD,IAAI,KAAK,KAAK,SAAS;YAAE,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;QACpD,IAAI,EAAE;YAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;QAC5B,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAA;QAErB,0DAA0D;QAC1D,6BAA6B;QAC7B,yDAAyD;QACzD,uDAAuD;QACvD,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;QAC1D,OAAO,IAAI,CAAA;IAAA,CACZ;IAED,+CAA+C;IAC/C,CAAC,MAAM,CAAC,GAAG;QACT,IAAI,IAAI,CAAC,SAAS,CAAC;YAAE,OAAM;QAE3B,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC;YAChD,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAA;QACxB,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,GAAG,KAAK,CAAA;QACpB,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAA;QACpB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACnB,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM;YAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAA;aACjC,IAAI,IAAI,CAAC,GAAG,CAAC;YAAE,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;;YACrC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACxB;IAED;;;;;;;;OAQG;IACH,MAAM,GAAG;QACP,OAAO,IAAI,CAAC,MAAM,CAAC,EAAE,CAAA;IAAA,CACtB;IAED;;OAEG;IACH,KAAK,GAAG;QACN,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,CAAA;QACrB,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;QACnB,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAA;IAAA,CACxB;IAED;;OAEG;IACH,IAAI,SAAS,GAAG;QACd,OAAO,IAAI,CAAC,SAAS,CAAC,CAAA;IAAA,CACvB;IAED;;;OAGG;IACH,IAAI,OAAO,GAAG;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACrB;IAED;;OAEG;IACH,IAAI,MAAM,GAAG;QACX,OAAO,IAAI,CAAC,MAAM,CAAC,CAAA;IAAA,CACpB;IAED,CAAC,UAAU,CAAC,CAAC,KAAY,EAAE;QACzB,IAAI,IAAI,CAAC,UAAU,CAAC;YAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAA;;YACxC,IAAI,CAAC,YAAY,CAAC,IAAK,KAAiC,CAAC,MAAM,CAAA;QACpE,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IAAA,CACzB;IAED,CAAC,WAAW,CAAC,GAAU;QACrB,IAAI,IAAI,CAAC,UAAU,CAAC;YAAE,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAA;;YAE3C,IAAI,CAAC,YAAY,CAAC,IAChB,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CACf,CAAC,MAAM,CAAA;QACV,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAW,CAAA;IAAA,CACrC;IAED,CAAC,KAAK,CAAC,CAAC,OAAO,GAAY,KAAK,EAAE;QAChC,GAAG,CAAC,CAAA,CAAC,QACH,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YACrC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,EACpB;QAED,IAAI,CAAC,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;YAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACvE;IAED,CAAC,UAAU,CAAC,CAAC,KAAY,EAAE;QACzB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;QACxB,OAAO,IAAI,CAAC,OAAO,CAAC,CAAA;IAAA,CACrB;IAED;;;;OAIG;IACH,IAAI,CAA8B,IAAO,EAAE,IAAkB,EAAK;QAChE,IAAI,IAAI,CAAC,SAAS,CAAC;YAAE,OAAO,IAAI,CAAA;QAChC,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAA;QAEvB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,CAAA;QAC/B,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QACjB,IAAI,IAAI,KAAK,IAAI,CAAC,MAAM,IAAI,IAAI,KAAK,IAAI,CAAC,MAAM;YAAE,IAAI,CAAC,GAAG,GAAG,KAAK,CAAA;;YAC7D,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,KAAK,KAAK,CAAA;QAClC,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAA;QAErC,0CAA0C;QAC1C,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,IAAI,CAAC,GAAG;gBAAE,IAAI,CAAC,GAAG,EAAE,CAAA;QAC1B,CAAC;aAAM,CAAC;YACN,kEAAkE;YAClE,gEAAgE;YAChE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CACd,CAAC,IAAI,CAAC,WAAW;gBACf,CAAC,CAAC,IAAI,IAAI,CAAQ,IAAuB,EAAE,IAAI,EAAE,IAAI,CAAC;gBACtD,CAAC,CAAC,IAAI,eAAe,CAAQ,IAAuB,EAAE,IAAI,EAAE,IAAI,CAAC,CACpE,CAAA;YACD,IAAI,IAAI,CAAC,KAAK,CAAC;gBAAE,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;;gBACvC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAA;QACrB,CAAC;QAED,OAAO,IAAI,CAAA;IAAA,CACZ;IAED;;;;;;;OAOG;IACH,MAAM,CAA8B,IAAO,EAAE;QAC3C,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAA;QAChD,IAAI,CAAC,EAAE,CAAC;YACN,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC7B,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC/C,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,CAAA;gBACvB,CAAC;gBACD,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAA;YAClB,CAAC;;gBAAM,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;YACpD,CAAC,CAAC,MAAM,EAAE,CAAA;QACZ,CAAC;IAAA,CACF;IAED;;OAEG;IACH,WAAW,CACT,EAAS,EACT,OAAwC,EAClC;QACN,OAAO,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;IAAA,CAC5B;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,EAAE,CACA,EAAS,EACT,OAAwC,EAClC;QACN,MAAM,GAAG,GAAG,KAAK,CAAC,EAAE,CAClB,EAAqB,EACrB,OAA+B,CAChC,CAAA;QACD,IAAI,EAAE,KAAK,MAAM,EAAE,CAAC;YAClB,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAA;YACvB,IAAI,CAAC,aAAa,CAAC,EAAE,CAAA;YACrB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC1C,IAAI,CAAC,MAAM,CAAC,EAAE,CAAA;YAChB,CAAC;QACH,CAAC;aAAM,IAAI,EAAE,KAAK,UAAU,IAAI,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;YACzD,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;QACxB,CAAC;aAAM,IAAI,QAAQ,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YAC7C,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YACd,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAA;QAC7B,CAAC;aAAM,IAAI,EAAE,KAAK,OAAO,IAAI,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;YACjD,MAAM,CAAC,GAAG,OAAyC,CAAA;YACnD,IAAI,IAAI,CAAC,KAAK,CAAC;gBAAE,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;;gBAC1D,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAA;QACxC,CAAC;QACD,OAAO,GAAG,CAAA;IAAA,CACX;IAED;;OAEG;IACH,cAAc,CACZ,EAAS,EACT,OAAwC,EACxC;QACA,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;IAAA,CAC7B;IAED;;;;;;;OAOG;IACH,GAAG,CACD,EAAS,EACT,OAAwC,EACxC;QACA,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CACnB,EAAqB,EACrB,OAA+B,CAChC,CAAA;QACD,iEAAiE;QACjE,kEAAkE;QAClE,wDAAwD;QACxD,IAAI,EAAE,KAAK,MAAM,EAAE,CAAC;YAClB,IAAI,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,MAAM,CAAA;YACnD,IACE,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC;gBACzB,CAAC,IAAI,CAAC,SAAS,CAAC;gBAChB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,EACnB,CAAC;gBACD,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,CAAA;YACvB,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAA;IAAA,CACX;IAED;;;;;;;OAOG;IACH,kBAAkB,CAA6B,EAAU,EAAE;QACzD,MAAM,GAAG,GAAG,KAAK,CAAC,kBAAkB,CAAC,EAAiC,CAAC,CAAA;QACvE,IAAI,EAAE,KAAK,MAAM,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;YACtC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAA;YACvB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC;gBAC5C,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,CAAA;YACvB,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAA;IAAA,CACX;IAED;;OAEG;IACH,IAAI,UAAU,GAAG;QACf,OAAO,IAAI,CAAC,WAAW,CAAC,CAAA;IAAA,CACzB;IAED,CAAC,cAAc,CAAC,GAAG;QACjB,IACE,CAAC,IAAI,CAAC,YAAY,CAAC;YACnB,CAAC,IAAI,CAAC,WAAW,CAAC;YAClB,CAAC,IAAI,CAAC,SAAS,CAAC;YAChB,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC;YACzB,IAAI,CAAC,GAAG,CAAC,EACT,CAAC;YACD,IAAI,CAAC,YAAY,CAAC,GAAG,IAAI,CAAA;YACzB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;YAChB,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;YACtB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YACnB,IAAI,IAAI,CAAC,MAAM,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YACpC,IAAI,CAAC,YAAY,CAAC,GAAG,KAAK,CAAA;QAC5B,CAAC;IAAA,CACF;IAED;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAI,CACF,EAAS,EACT,GAAG,IAAmB,EACb;QACT,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;QACpB,kEAAkE;QAClE,IACE,EAAE,KAAK,OAAO;YACd,EAAE,KAAK,OAAO;YACd,EAAE,KAAK,SAAS;YAChB,IAAI,CAAC,SAAS,CAAC,EACf,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;aAAM,IAAI,EAAE,KAAK,MAAM,EAAE,CAAC;YACzB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI;gBAC/B,CAAC,CAAC,KAAK;gBACP,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC;oBACb,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAa,CAAC,CAAC,EAAE,IAAI,CAAC;oBACpD,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAa,CAAC,CAAA;QACnC,CAAC;aAAM,IAAI,EAAE,KAAK,KAAK,EAAE,CAAC;YACxB,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACxB,CAAC;aAAM,IAAI,EAAE,KAAK,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAA;YACnB,6CAA6C;YAC7C,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC;gBAAE,OAAO,KAAK,CAAA;YACxD,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAC/B,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAA;YAChC,OAAO,GAAG,CAAA;QACZ,CAAC;aAAM,IAAI,EAAE,KAAK,OAAO,EAAE,CAAC;YAC1B,IAAI,CAAC,aAAa,CAAC,GAAG,IAAI,CAAA;YAC1B,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACvB,MAAM,GAAG,GACP,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,MAAM;gBAC7C,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC;gBAC3B,CAAC,CAAC,KAAK,CAAA;YACX,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;YACtB,OAAO,GAAG,CAAA;QACZ,CAAC;aAAM,IAAI,EAAE,KAAK,QAAQ,EAAE,CAAC;YAC3B,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;YAChC,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;YACtB,OAAO,GAAG,CAAA;QACZ,CAAC;aAAM,IAAI,EAAE,KAAK,QAAQ,IAAI,EAAE,KAAK,WAAW,EAAE,CAAC;YACjD,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;YAC1B,IAAI,CAAC,kBAAkB,CAAC,EAAE,CAAC,CAAA;YAC3B,OAAO,GAAG,CAAA;QACZ,CAAC;QAED,2BAA2B;QAC3B,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,EAAY,EAAE,GAAG,IAAI,CAAC,CAAA;QAC7C,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;QACtB,OAAO,GAAG,CAAA;IAAA,CACX;IAED,CAAC,QAAQ,CAAC,CAAC,IAAW,EAAE;QACtB,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5B,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAa,CAAC,KAAK,KAAK;gBAAE,IAAI,CAAC,KAAK,EAAE,CAAA;QACzD,CAAC;QACD,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;QAC9D,IAAI,CAAC,cAAc,CAAC,EAAE,CAAA;QACtB,OAAO,GAAG,CAAA;IAAA,CACX;IAED,CAAC,OAAO,CAAC,GAAG;QACV,IAAI,IAAI,CAAC,WAAW,CAAC;YAAE,OAAO,KAAK,CAAA;QAEnC,IAAI,CAAC,WAAW,CAAC,GAAG,IAAI,CAAA;QACxB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAA;QACrB,OAAO,IAAI,CAAC,KAAK,CAAC;YAChB,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC;YACvC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAA;IAAA,CACrB;IAED,CAAC,QAAQ,CAAC,GAAG;QACX,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;YAClB,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,CAAA;YAChC,IAAI,IAAI,EAAE,CAAC;gBACT,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC5B,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAa,CAAC,CAAA;gBAC7B,CAAC;gBACD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC;oBAAE,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;YAChD,CAAC;QACH,CAAC;QAED,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5B,CAAC,CAAC,GAAG,EAAE,CAAA;QACT,CAAC;QACD,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QAC7B,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAA;QAC9B,OAAO,GAAG,CAAA;IAAA,CACX;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO,GAA8C;QACzD,MAAM,GAAG,GAAqC,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE;YAC9D,UAAU,EAAE,CAAC;SACd,CAAC,CAAA;QACF,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC;YAAE,GAAG,CAAC,UAAU,GAAG,CAAC,CAAA;QACzC,oDAAoD;QACpD,+BAA+B;QAC/B,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,EAAE,CAAA;QACxB,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC;YACnB,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;YACX,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC;gBACnB,GAAG,CAAC,UAAU,IAAK,CAA6B,CAAC,MAAM,CAAA;QAAA,CAC1D,CAAC,CAAA;QACF,MAAM,CAAC,CAAA;QACP,OAAO,GAAG,CAAA;IAAA,CACX;IAED;;;;;OAKG;IACH,KAAK,CAAC,MAAM,GAAmB;QAC7B,IAAI,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;QAChD,CAAC;QACD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,EAAE,CAAA;QAChC,OAAO,CACL,IAAI,CAAC,QAAQ,CAAC;YACZ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACd,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,GAAe,EAAE,GAAG,CAAC,UAAU,CAAC,CAC1C,CAAA;IAAA,CACX;IAED;;OAEG;IACH,KAAK,CAAC,OAAO,GAAkB;QAC7B,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC;YAC5C,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAA;YAC/D,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAA;YAClC,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAA;QAAA,CAChC,CAAC,CAAA;IAAA,CACH;IAED;;;;OAIG;IACH,CAAC,MAAM,CAAC,aAAa,CAAC,GAAsC;QAC1D,8DAA8D;QAC9D,cAAc;QACd,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAA;QACvB,IAAI,OAAO,GAAG,KAAK,CAAA;QACnB,MAAM,IAAI,GAAG,KAAK,IAAyC,EAAE,CAAC;YAC5D,IAAI,CAAC,KAAK,EAAE,CAAA;YACZ,OAAO,GAAG,IAAI,CAAA;YACd,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;QAAA,CACxC,CAAA;QACD,MAAM,IAAI,GAAG,GAAyC,EAAE,CAAC;YACvD,IAAI,OAAO;gBAAE,OAAO,IAAI,EAAE,CAAA;YAC1B,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,EAAE,CAAA;YACvB,IAAI,GAAG,KAAK,IAAI;gBAAE,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;YAErE,IAAI,IAAI,CAAC,GAAG,CAAC;gBAAE,OAAO,IAAI,EAAE,CAAA;YAE5B,IAAI,OAA8C,CAAA;YAClD,IAAI,MAA8B,CAAA;YAClC,MAAM,KAAK,GAAG,CAAC,EAAW,EAAE,EAAE,CAAC;gBAC7B,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;gBACxB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;gBACtB,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;gBAC9B,IAAI,EAAE,CAAA;gBACN,MAAM,CAAC,EAAE,CAAC,CAAA;YAAA,CACX,CAAA;YACD,MAAM,MAAM,GAAG,CAAC,KAAY,EAAE,EAAE,CAAC;gBAC/B,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;gBACxB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;gBACtB,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;gBAC9B,IAAI,CAAC,KAAK,EAAE,CAAA;gBACZ,OAAO,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;YAAA,CACtC,CAAA;YACD,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC;gBAClB,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;gBACxB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;gBACxB,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;gBAC9B,IAAI,EAAE,CAAA;gBACN,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAA;YAAA,CAC1C,CAAA;YACD,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC,CAAA;YAC5D,OAAO,IAAI,OAAO,CAAwB,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC;gBACtD,MAAM,GAAG,GAAG,CAAA;gBACZ,OAAO,GAAG,GAAG,CAAA;gBACb,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;gBAC/B,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;gBACzB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;gBACvB,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;YAAA,CAC1B,CAAC,CAAA;QAAA,CACH,CAAA;QAED,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,IAAI;YACX,MAAM,EAAE,IAAI;YACZ,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG;gBACvB,OAAO,IAAI,CAAA;YAAA,CACZ;YACD,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC,EAAC,CAAC;SACtC,CAAA;IAAA,CACF;IAED;;;;;OAKG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAiC;QAChD,8DAA8D;QAC9D,cAAc;QACd,IAAI,CAAC,SAAS,CAAC,GAAG,KAAK,CAAA;QACvB,IAAI,OAAO,GAAG,KAAK,CAAA;QACnB,MAAM,IAAI,GAAG,GAA+B,EAAE,CAAC;YAC7C,IAAI,CAAC,KAAK,EAAE,CAAA;YACZ,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACrB,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;YACzB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;YACrB,OAAO,GAAG,IAAI,CAAA;YACd,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAA;QAAA,CACxC,CAAA;QAED,MAAM,IAAI,GAAG,GAAgC,EAAE,CAAC;YAC9C,IAAI,OAAO;gBAAE,OAAO,IAAI,EAAE,CAAA;YAC1B,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,EAAE,CAAA;YACzB,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAA;QAAA,CACxD,CAAA;QAED,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACtB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;QACtB,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;QAE1B,OAAO;YACL,IAAI;YACJ,KAAK,EAAE,IAAI;YACX,MAAM,EAAE,IAAI;YACZ,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG;gBAClB,OAAO,IAAI,CAAA;YAAA,CACZ;YACD,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,CAAC,EAAC,CAAC;SAC3B,CAAA;IAAA,CACF;IAED;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAY,EAAE;QACpB,IAAI,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YACpB,IAAI,EAAE;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;;gBACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;YACzB,OAAO,IAAI,CAAA;QACb,CAAC;QAED,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAA;QACtB,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAA;QAEtB,sDAAsD;QACtD,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAA;QACvB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QAEtB,MAAM,EAAE,GAAG,IAEV,CAAA;QACD,IAAI,OAAO,EAAE,CAAC,KAAK,KAAK,UAAU,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,EAAE,CAAC,KAAK,EAAE,CAAA;QAE/D,IAAI,EAAE;YAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;QAC9B,qDAAqD;;YAChD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAEzB,OAAO,IAAI,CAAA;IAAA,CACZ;IAED;;;;;;OAMG;IACH,MAAM,KAAK,QAAQ,GAAG;QACpB,OAAO,QAAQ,CAAA;IAAA,CAChB;CACF","sourcesContent":["const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n src: Minipass\n dest: Minipass\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable = Iterable & AsyncIterable\n\n type EventArguments = Record\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events = Minipass.Events\n >\n extends EventEmitter\n implements Minipass.DualIterable\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options]\n : [Minipass.Options])\n ) {\n const options: Minipass.Options = (args[0] ||\n {}) as Minipass.Options\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe(this as Minipass, dest, opts)\n : new PipeProxyErrors(this as Minipass, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise {\n return new Promise((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n [Symbol.asyncDispose]: async () => {},\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n [Symbol.dispose]: () => {},\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/minipass/dist/esm/package.json b/tools/ui/node_modules/minipass/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/tools/ui/node_modules/minipass/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/tools/ui/node_modules/minipass/package.json b/tools/ui/node_modules/minipass/package.json new file mode 100644 index 0000000000000000000000000000000000000000..800f215cb02c01bbf5cb206ecfcac6783fbcfd9e --- /dev/null +++ b/tools/ui/node_modules/minipass/package.json @@ -0,0 +1,77 @@ +{ + "name": "minipass", + "version": "7.1.3", + "description": "minimal implementation of a PassThrough stream", + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js", + "type": "module", + "tshy": { + "selfLink": false, + "compiler": "tsgo", + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/end-of-stream": "^1.4.2", + "@types/node": "^25.2.3", + "end-of-stream": "^1.4.0", + "node-abort-controller": "^3.1.1", + "prettier": "^3.8.1", + "tap": "^21.6.1", + "through2": "^2.0.3", + "tshy": "^3.3.2", + "typedoc": "^0.28.17" + }, + "repository": "https://github.com/isaacs/minipass", + "keywords": [ + "passthrough", + "stream" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } +} diff --git a/tools/ui/node_modules/minizlib/LICENSE b/tools/ui/node_modules/minizlib/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..49f7efe431c9ea33cade9f79490695c6b16fd7c4 --- /dev/null +++ b/tools/ui/node_modules/minizlib/LICENSE @@ -0,0 +1,26 @@ +Minizlib was created by Isaac Z. Schlueter. +It is a derivative work of the Node.js project. + +""" +Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors +Copyright (c) 2017-2023 Node.js contributors. All rights reserved. +Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved. + +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. +""" diff --git a/tools/ui/node_modules/minizlib/README.md b/tools/ui/node_modules/minizlib/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1b6f008d291661bc8d2f820b9b6ceb71125bd7c9 --- /dev/null +++ b/tools/ui/node_modules/minizlib/README.md @@ -0,0 +1,64 @@ +# minizlib + +A fast zlib stream built on [minipass](http://npm.im/minipass) and +Node.js's zlib binding. + +This module was created to serve the needs of +[node-tar](http://npm.im/tar) and +[minipass-fetch](http://npm.im/minipass-fetch). + +Brotli is supported in versions of node with a Brotli binding. + +## How does this differ from the streams in `'node:zlib'`? + +First, there are no convenience methods to compress or decompress a +buffer. If you want those, use the built-in `zlib` module. This is +only streams. That being said, Minipass streams to make it fairly easy to +use as one-liners: `new zlib.Deflate().end(data).read()` will return the +deflate compressed result. + +This module compresses and decompresses the data as fast as you feed +it in. It is synchronous, and runs on the main process thread. Zlib +and Brotli operations can be high CPU, but they're very fast, and doing it +this way means much less bookkeeping and artificial deferral. + +Node's built in zlib streams are built on top of `stream.Transform`. +They do the maximally safe thing with respect to consistent +asynchrony, buffering, and backpressure. + +See [Minipass](http://npm.im/minipass) for more on the differences between +Node.js core streams and Minipass streams, and the convenience methods +provided by that class. + +## Classes + +- Deflate +- Inflate +- Gzip +- Gunzip +- DeflateRaw +- InflateRaw +- Unzip +- BrotliCompress (Node v10 and higher) +- BrotliDecompress (Node v10 and higher) +- ZstdCompress (Node v22.15 and higher) +- ZstdDecompress (Node v22.15 and higher) + +## USAGE + +```js +import { BrotliDecompress } from 'minizlib' +// or: const BrotliDecompress = require('minizlib') + +const input = sourceOfCompressedData() +const decode = new BrotliDecompress() +const output = whereToWriteTheDecodedData() +input.pipe(decode).pipe(output) +``` + +## REPRODUCIBLE BUILDS + +To create reproducible gzip compressed files across different operating +systems, set `portable: true` in the options. This causes minizlib to set +the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for +'unknown'. diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/constants.d.ts b/tools/ui/node_modules/minizlib/dist/commonjs/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67c47b4aa34ea79f63632549c0f4e0439711d12f --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/constants.d.ts @@ -0,0 +1,2 @@ +export declare const constants: any; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/constants.d.ts.map b/tools/ui/node_modules/minizlib/dist/commonjs/constants.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..25affce76739678bb862eb8edd35904a7a78ed31 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,SAAS,KAiHrB,CAAA"} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/constants.js b/tools/ui/node_modules/minizlib/dist/commonjs/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..dfc2c1957bfc9974baad180b59ec8ae83c62568a --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/constants.js @@ -0,0 +1,123 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.constants = void 0; +// Update with any zlib constants that are added or changed in the future. +// Node v6 didn't export this, so we just hard code the version and rely +// on all the other hard-coded values from zlib v4736. When node v6 +// support drops, we can just export the realZlibConstants object. +const zlib_1 = __importDefault(require("zlib")); +/* c8 ignore start */ +const realZlibConstants = zlib_1.default.constants || { ZLIB_VERNUM: 4736 }; +/* c8 ignore stop */ +exports.constants = Object.freeze(Object.assign(Object.create(null), { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + Z_VERSION_ERROR: -6, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + DEFLATE: 1, + INFLATE: 2, + GZIP: 3, + GUNZIP: 4, + DEFLATERAW: 5, + INFLATERAW: 6, + UNZIP: 7, + BROTLI_DECODE: 8, + BROTLI_ENCODE: 9, + Z_MIN_WINDOWBITS: 8, + Z_MAX_WINDOWBITS: 15, + Z_DEFAULT_WINDOWBITS: 15, + Z_MIN_CHUNK: 64, + Z_MAX_CHUNK: Infinity, + Z_DEFAULT_CHUNK: 16384, + Z_MIN_MEMLEVEL: 1, + Z_MAX_MEMLEVEL: 9, + Z_DEFAULT_MEMLEVEL: 8, + Z_MIN_LEVEL: -1, + Z_MAX_LEVEL: 9, + Z_DEFAULT_LEVEL: -1, + BROTLI_OPERATION_PROCESS: 0, + BROTLI_OPERATION_FLUSH: 1, + BROTLI_OPERATION_FINISH: 2, + BROTLI_OPERATION_EMIT_METADATA: 3, + BROTLI_MODE_GENERIC: 0, + BROTLI_MODE_TEXT: 1, + BROTLI_MODE_FONT: 2, + BROTLI_DEFAULT_MODE: 0, + BROTLI_MIN_QUALITY: 0, + BROTLI_MAX_QUALITY: 11, + BROTLI_DEFAULT_QUALITY: 11, + BROTLI_MIN_WINDOW_BITS: 10, + BROTLI_MAX_WINDOW_BITS: 24, + BROTLI_LARGE_MAX_WINDOW_BITS: 30, + BROTLI_DEFAULT_WINDOW: 22, + BROTLI_MIN_INPUT_BLOCK_BITS: 16, + BROTLI_MAX_INPUT_BLOCK_BITS: 24, + BROTLI_PARAM_MODE: 0, + BROTLI_PARAM_QUALITY: 1, + BROTLI_PARAM_LGWIN: 2, + BROTLI_PARAM_LGBLOCK: 3, + BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, + BROTLI_PARAM_SIZE_HINT: 5, + BROTLI_PARAM_LARGE_WINDOW: 6, + BROTLI_PARAM_NPOSTFIX: 7, + BROTLI_PARAM_NDIRECT: 8, + BROTLI_DECODER_RESULT_ERROR: 0, + BROTLI_DECODER_RESULT_SUCCESS: 1, + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, + BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, + BROTLI_DECODER_NO_ERROR: 0, + BROTLI_DECODER_SUCCESS: 1, + BROTLI_DECODER_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, + BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, + BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, + BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, + BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, + BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, + BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, + BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, + BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, + BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, + BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, + BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, + BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, + BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, + BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, + BROTLI_DECODER_ERROR_UNREACHABLE: -31, +}, realZlibConstants)); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/constants.js.map b/tools/ui/node_modules/minizlib/dist/commonjs/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..3b733358a0926a5145364ec25c7070c188c3e22a --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";;;;;;AAAA,0EAA0E;AAC1E,wEAAwE;AACxE,oEAAoE;AACpE,kEAAkE;AAClE,gDAA2B;AAC3B,qBAAqB;AACrB,MAAM,iBAAiB,GAAG,cAAQ,CAAC,SAAS,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAA;AACrE,oBAAoB;AAEP,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CACpC,MAAM,CAAC,MAAM,CACX,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EACnB;IACE,UAAU,EAAE,CAAC;IACb,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,CAAC;IACf,YAAY,EAAE,CAAC;IACf,QAAQ,EAAE,CAAC;IACX,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,OAAO,EAAE,CAAC,CAAC;IACX,cAAc,EAAE,CAAC,CAAC;IAClB,YAAY,EAAE,CAAC,CAAC;IAChB,WAAW,EAAE,CAAC,CAAC;IACf,WAAW,EAAE,CAAC,CAAC;IACf,eAAe,EAAE,CAAC,CAAC;IACnB,gBAAgB,EAAE,CAAC;IACnB,YAAY,EAAE,CAAC;IACf,kBAAkB,EAAE,CAAC;IACrB,qBAAqB,EAAE,CAAC,CAAC;IACzB,UAAU,EAAE,CAAC;IACb,cAAc,EAAE,CAAC;IACjB,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,kBAAkB,EAAE,CAAC;IACrB,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;IACR,aAAa,EAAE,CAAC;IAChB,aAAa,EAAE,CAAC;IAChB,gBAAgB,EAAE,CAAC;IACnB,gBAAgB,EAAE,EAAE;IACpB,oBAAoB,EAAE,EAAE;IACxB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,QAAQ;IACrB,eAAe,EAAE,KAAK;IACtB,cAAc,EAAE,CAAC;IACjB,cAAc,EAAE,CAAC;IACjB,kBAAkB,EAAE,CAAC;IACrB,WAAW,EAAE,CAAC,CAAC;IACf,WAAW,EAAE,CAAC;IACd,eAAe,EAAE,CAAC,CAAC;IACnB,wBAAwB,EAAE,CAAC;IAC3B,sBAAsB,EAAE,CAAC;IACzB,uBAAuB,EAAE,CAAC;IAC1B,8BAA8B,EAAE,CAAC;IACjC,mBAAmB,EAAE,CAAC;IACtB,gBAAgB,EAAE,CAAC;IACnB,gBAAgB,EAAE,CAAC;IACnB,mBAAmB,EAAE,CAAC;IACtB,kBAAkB,EAAE,CAAC;IACrB,kBAAkB,EAAE,EAAE;IACtB,sBAAsB,EAAE,EAAE;IAC1B,sBAAsB,EAAE,EAAE;IAC1B,sBAAsB,EAAE,EAAE;IAC1B,4BAA4B,EAAE,EAAE;IAChC,qBAAqB,EAAE,EAAE;IACzB,2BAA2B,EAAE,EAAE;IAC/B,2BAA2B,EAAE,EAAE;IAC/B,iBAAiB,EAAE,CAAC;IACpB,oBAAoB,EAAE,CAAC;IACvB,kBAAkB,EAAE,CAAC;IACrB,oBAAoB,EAAE,CAAC;IACvB,6CAA6C,EAAE,CAAC;IAChD,sBAAsB,EAAE,CAAC;IACzB,yBAAyB,EAAE,CAAC;IAC5B,qBAAqB,EAAE,CAAC;IACxB,oBAAoB,EAAE,CAAC;IACvB,2BAA2B,EAAE,CAAC;IAC9B,6BAA6B,EAAE,CAAC;IAChC,sCAAsC,EAAE,CAAC;IACzC,uCAAuC,EAAE,CAAC;IAC1C,qDAAqD,EAAE,CAAC;IACxD,iCAAiC,EAAE,CAAC;IACpC,uBAAuB,EAAE,CAAC;IAC1B,sBAAsB,EAAE,CAAC;IACzB,+BAA+B,EAAE,CAAC;IAClC,gCAAgC,EAAE,CAAC;IACnC,4CAA4C,EAAE,CAAC,CAAC;IAChD,oCAAoC,EAAE,CAAC,CAAC;IACxC,iDAAiD,EAAE,CAAC,CAAC;IACrD,mDAAmD,EAAE,CAAC,CAAC;IACvD,+CAA+C,EAAE,CAAC,CAAC;IACnD,oCAAoC,EAAE,CAAC,CAAC;IACxC,yCAAyC,EAAE,CAAC,CAAC;IAC7C,8CAA8C,EAAE,CAAC,CAAC;IAClD,0CAA0C,EAAE,CAAC,CAAC;IAC9C,0CAA0C,EAAE,CAAC,EAAE;IAC/C,qCAAqC,EAAE,CAAC,EAAE;IAC1C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,uCAAuC,EAAE,CAAC,EAAE;IAC5C,qCAAqC,EAAE,CAAC,EAAE;IAC1C,qCAAqC,EAAE,CAAC,EAAE;IAC1C,oCAAoC,EAAE,CAAC,EAAE;IACzC,uCAAuC,EAAE,CAAC,EAAE;IAC5C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,wCAAwC,EAAE,CAAC,EAAE;IAC7C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,wCAAwC,EAAE,CAAC,EAAE;IAC7C,wCAAwC,EAAE,CAAC,EAAE;IAC7C,2CAA2C,EAAE,CAAC,EAAE;IAChD,gCAAgC,EAAE,CAAC,EAAE;CACtC,EACD,iBAAiB,CAClB,CACF,CAAA","sourcesContent":["// Update with any zlib constants that are added or changed in the future.\n// Node v6 didn't export this, so we just hard code the version and rely\n// on all the other hard-coded values from zlib v4736. When node v6\n// support drops, we can just export the realZlibConstants object.\nimport realZlib from 'zlib'\n/* c8 ignore start */\nconst realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }\n/* c8 ignore stop */\n\nexport const constants = Object.freeze(\n Object.assign(\n Object.create(null),\n {\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n Z_VERSION_ERROR: -6,\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n DEFLATE: 1,\n INFLATE: 2,\n GZIP: 3,\n GUNZIP: 4,\n DEFLATERAW: 5,\n INFLATERAW: 6,\n UNZIP: 7,\n BROTLI_DECODE: 8,\n BROTLI_ENCODE: 9,\n Z_MIN_WINDOWBITS: 8,\n Z_MAX_WINDOWBITS: 15,\n Z_DEFAULT_WINDOWBITS: 15,\n Z_MIN_CHUNK: 64,\n Z_MAX_CHUNK: Infinity,\n Z_DEFAULT_CHUNK: 16384,\n Z_MIN_MEMLEVEL: 1,\n Z_MAX_MEMLEVEL: 9,\n Z_DEFAULT_MEMLEVEL: 8,\n Z_MIN_LEVEL: -1,\n Z_MAX_LEVEL: 9,\n Z_DEFAULT_LEVEL: -1,\n BROTLI_OPERATION_PROCESS: 0,\n BROTLI_OPERATION_FLUSH: 1,\n BROTLI_OPERATION_FINISH: 2,\n BROTLI_OPERATION_EMIT_METADATA: 3,\n BROTLI_MODE_GENERIC: 0,\n BROTLI_MODE_TEXT: 1,\n BROTLI_MODE_FONT: 2,\n BROTLI_DEFAULT_MODE: 0,\n BROTLI_MIN_QUALITY: 0,\n BROTLI_MAX_QUALITY: 11,\n BROTLI_DEFAULT_QUALITY: 11,\n BROTLI_MIN_WINDOW_BITS: 10,\n BROTLI_MAX_WINDOW_BITS: 24,\n BROTLI_LARGE_MAX_WINDOW_BITS: 30,\n BROTLI_DEFAULT_WINDOW: 22,\n BROTLI_MIN_INPUT_BLOCK_BITS: 16,\n BROTLI_MAX_INPUT_BLOCK_BITS: 24,\n BROTLI_PARAM_MODE: 0,\n BROTLI_PARAM_QUALITY: 1,\n BROTLI_PARAM_LGWIN: 2,\n BROTLI_PARAM_LGBLOCK: 3,\n BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,\n BROTLI_PARAM_SIZE_HINT: 5,\n BROTLI_PARAM_LARGE_WINDOW: 6,\n BROTLI_PARAM_NPOSTFIX: 7,\n BROTLI_PARAM_NDIRECT: 8,\n BROTLI_DECODER_RESULT_ERROR: 0,\n BROTLI_DECODER_RESULT_SUCCESS: 1,\n BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,\n BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,\n BROTLI_DECODER_NO_ERROR: 0,\n BROTLI_DECODER_SUCCESS: 1,\n BROTLI_DECODER_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,\n BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,\n BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,\n BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,\n BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,\n BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,\n BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,\n BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,\n BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,\n BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,\n BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,\n BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,\n BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,\n BROTLI_DECODER_ERROR_UNREACHABLE: -31,\n },\n realZlibConstants,\n ),\n)\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/index.d.ts b/tools/ui/node_modules/minizlib/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8044bd061aac745cb532182ce714778303323530 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/index.d.ts @@ -0,0 +1,99 @@ +import { Buffer } from 'buffer'; +import { Minipass } from 'minipass'; +import * as realZlib from 'zlib'; +export { constants } from './constants.js'; +declare const _superWrite: unique symbol; +export declare class ZlibError extends Error { + code?: string; + errno?: number; + constructor(err: NodeJS.ErrnoException | Error, origin?: Function); + get name(): string; +} +declare const _flushFlag: unique symbol; +export type ChunkWithFlushFlag = Minipass.ContiguousData & { + [_flushFlag]?: number; +}; +export type ZlibBaseOptions = Minipass.Options & { + flush?: number; + finishFlush?: number; + fullFlushFlag?: number; +}; +export type ZlibHandle = realZlib.Gzip | realZlib.Gunzip | realZlib.Deflate | realZlib.Inflate | realZlib.DeflateRaw | realZlib.InflateRaw | realZlib.BrotliCompress | realZlib.BrotliDecompress | realZlib.ZstdCompress | realZlib.ZstdDecompress; +export type ZlibMode = 'Gzip' | 'Gunzip' | 'Deflate' | 'Inflate' | 'DeflateRaw' | 'InflateRaw' | 'Unzip'; +export type BrotliMode = 'BrotliCompress' | 'BrotliDecompress'; +export type ZstdMode = 'ZstdCompress' | 'ZstdDecompress'; +declare abstract class ZlibBase extends Minipass { + #private; + get sawError(): boolean; + get handle(): ZlibHandle | undefined; + get flushFlag(): number; + constructor(opts: ZlibBaseOptions, mode: ZlibMode | BrotliMode | ZstdMode); + close(): void; + reset(): any; + flush(flushFlag?: number): void; + end(cb?: () => void): this; + end(chunk: ChunkWithFlushFlag, cb?: () => void): this; + end(chunk: ChunkWithFlushFlag, encoding?: Minipass.Encoding, cb?: () => void): this; + get ended(): boolean; + [_superWrite](data: Buffer & { + [_flushFlag]?: number; + }): boolean; + write(chunk: ChunkWithFlushFlag, cb?: () => void): boolean; + write(chunk: ChunkWithFlushFlag, encoding?: Minipass.Encoding, cb?: () => void): boolean; +} +export type ZlibOptions = ZlibBaseOptions & { + level?: number; + strategy?: number; +}; +export declare class Zlib extends ZlibBase { + #private; + constructor(opts: ZlibOptions, mode: ZlibMode); + params(level: number, strategy: number): void; +} +export declare class Deflate extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class Inflate extends Zlib { + constructor(opts: ZlibOptions); +} +export type GzipOptions = ZlibOptions & { + portable?: boolean; +}; +export declare class Gzip extends Zlib { + #private; + constructor(opts: GzipOptions); + [_superWrite](data: Buffer & { + [_flushFlag]?: number; + }): boolean; +} +export declare class Gunzip extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class DeflateRaw extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class InflateRaw extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class Unzip extends Zlib { + constructor(opts: ZlibOptions); +} +declare class Brotli extends ZlibBase { + constructor(opts: ZlibOptions, mode: BrotliMode); +} +export declare class BrotliCompress extends Brotli { + constructor(opts: ZlibOptions); +} +export declare class BrotliDecompress extends Brotli { + constructor(opts: ZlibOptions); +} +declare class Zstd extends ZlibBase { + constructor(opts: ZlibOptions, mode: ZstdMode); +} +export declare class ZstdCompress extends Zstd { + constructor(opts: ZlibOptions); +} +export declare class ZstdDecompress extends Zstd { + constructor(opts: ZlibOptions); +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/index.d.ts.map b/tools/ui/node_modules/minizlib/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..dcf6141b63036b9b86058a6d199a3edd408065dc --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,QAAQ,MAAM,MAAM,CAAA;AAEhC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAY1C,QAAA,MAAM,WAAW,eAAwB,CAAA;AAEzC,qBAAa,SAAU,SAAQ,KAAK;IAClC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;gBACF,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,KAAK,EAAE,MAAM,CAAC,EAAE,QAAQ;IAWjE,IAAI,IAAI,WAEP;CACF;AAMD,QAAA,MAAM,UAAU,eAAsB,CAAA;AAEtC,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC,cAAc,GAAG;IACzD,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC,GAAG;IACxE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,CAAA;AAED,MAAM,MAAM,UAAU,GAClB,QAAQ,CAAC,IAAI,GACb,QAAQ,CAAC,MAAM,GACf,QAAQ,CAAC,OAAO,GAChB,QAAQ,CAAC,OAAO,GAChB,QAAQ,CAAC,UAAU,GACnB,QAAQ,CAAC,UAAU,GACnB,QAAQ,CAAC,cAAc,GACvB,QAAQ,CAAC,gBAAgB,GACzB,QAAQ,CAAC,YAAY,GACrB,QAAQ,CAAC,cAAc,CAAA;AAC3B,MAAM,MAAM,QAAQ,GAChB,MAAM,GACN,QAAQ,GACR,SAAS,GACT,SAAS,GACT,YAAY,GACZ,YAAY,GACZ,OAAO,CAAA;AACX,MAAM,MAAM,UAAU,GAAG,gBAAgB,GAAG,kBAAkB,CAAA;AAC9D,MAAM,MAAM,QAAQ,GAAG,cAAc,GAAG,gBAAgB,CAAA;AAExD,uBAAe,QAAS,SAAQ,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;;IASlE,IAAI,QAAQ,YAEX;IACD,IAAI,MAAM,2BAET;IAED,IAAI,SAAS,WAEZ;gBAGW,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,QAAQ,GAAG,UAAU,GAAG,QAAQ;IA4CzE,KAAK;IAQL,KAAK;IAQL,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM;IAQxB,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI;IAC1B,GAAG,CAAC,KAAK,EAAE,kBAAkB,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI;IACrD,GAAG,CACD,KAAK,EAAE,kBAAkB,EACzB,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,EAC5B,EAAE,CAAC,EAAE,MAAM,IAAI,GACd,IAAI;IA0BP,IAAI,KAAK,YAER;IAGD,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG;QAAE,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,CAAA;KAAE;IAItD,KAAK,CAAC,KAAK,EAAE,kBAAkB,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO;IAC1D,KAAK,CACH,KAAK,EAAE,kBAAkB,EACzB,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,EAC5B,EAAE,CAAC,EAAE,MAAM,IAAI,GACd,OAAO;CAqFX;AAED,MAAM,MAAM,WAAW,GAAG,eAAe,GAAG;IAC1C,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,qBAAa,IAAK,SAAQ,QAAQ;;gBAIpB,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ;IAY7C,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAiDvC;AAGD,qBAAa,OAAQ,SAAQ,IAAI;gBACnB,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,OAAQ,SAAQ,IAAI;gBACnB,IAAI,EAAE,WAAW;CAG9B;AAGD,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAC9D,qBAAa,IAAK,SAAQ,IAAI;;gBAEhB,IAAI,EAAE,WAAW;IAK7B,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG;QAAE,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,CAAA;KAAE;CASvD;AAED,qBAAa,MAAO,SAAQ,IAAI;gBAClB,IAAI,EAAE,WAAW;CAG9B;AAGD,qBAAa,UAAW,SAAQ,IAAI;gBACtB,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,UAAW,SAAQ,IAAI;gBACtB,IAAI,EAAE,WAAW;CAG9B;AAGD,qBAAa,KAAM,SAAQ,IAAI;gBACjB,IAAI,EAAE,WAAW;CAG9B;AAED,cAAM,MAAO,SAAQ,QAAQ;gBACf,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU;CAShD;AAED,qBAAa,cAAe,SAAQ,MAAM;gBAC5B,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,gBAAiB,SAAQ,MAAM;gBAC9B,IAAI,EAAE,WAAW;CAG9B;AAED,cAAM,IAAK,SAAQ,QAAQ;gBACb,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ;CAQ9C;AAED,qBAAa,YAAa,SAAQ,IAAI;gBACxB,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,cAAe,SAAQ,IAAI;gBAC1B,IAAI,EAAE,WAAW;CAG9B"} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/index.js b/tools/ui/node_modules/minizlib/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..78c6536baf6be9f39aff9a12e41fedf4fd215a02 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/index.js @@ -0,0 +1,416 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ZstdDecompress = exports.ZstdCompress = exports.BrotliDecompress = exports.BrotliCompress = exports.Unzip = exports.InflateRaw = exports.DeflateRaw = exports.Gunzip = exports.Gzip = exports.Inflate = exports.Deflate = exports.Zlib = exports.ZlibError = exports.constants = void 0; +const assert_1 = __importDefault(require("assert")); +const buffer_1 = require("buffer"); +const minipass_1 = require("minipass"); +const realZlib = __importStar(require("zlib")); +const constants_js_1 = require("./constants.js"); +var constants_js_2 = require("./constants.js"); +Object.defineProperty(exports, "constants", { enumerable: true, get: function () { return constants_js_2.constants; } }); +const OriginalBufferConcat = buffer_1.Buffer.concat; +const desc = Object.getOwnPropertyDescriptor(buffer_1.Buffer, 'concat'); +const noop = (args) => args; +const passthroughBufferConcat = desc?.writable === true || desc?.set !== undefined + ? (makeNoOp) => { + buffer_1.Buffer.concat = makeNoOp ? noop : OriginalBufferConcat; + } + : (_) => { }; +const _superWrite = Symbol('_superWrite'); +class ZlibError extends Error { + code; + errno; + constructor(err, origin) { + super('zlib: ' + err.message, { cause: err }); + this.code = err.code; + this.errno = err.errno; + /* c8 ignore next */ + if (!this.code) + this.code = 'ZLIB_ERROR'; + this.message = 'zlib: ' + err.message; + Error.captureStackTrace(this, origin ?? this.constructor); + } + get name() { + return 'ZlibError'; + } +} +exports.ZlibError = ZlibError; +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. +const _flushFlag = Symbol('flushFlag'); +class ZlibBase extends minipass_1.Minipass { + #sawError = false; + #ended = false; + #flushFlag; + #finishFlushFlag; + #fullFlushFlag; + #handle; + #onError; + get sawError() { + return this.#sawError; + } + get handle() { + return this.#handle; + } + /* c8 ignore start */ + get flushFlag() { + return this.#flushFlag; + } + /* c8 ignore stop */ + constructor(opts, mode) { + if (!opts || typeof opts !== 'object') + throw new TypeError('invalid options for ZlibBase constructor'); + //@ts-ignore + super(opts); + /* c8 ignore start */ + this.#flushFlag = opts.flush ?? 0; + this.#finishFlushFlag = opts.finishFlush ?? 0; + this.#fullFlushFlag = opts.fullFlushFlag ?? 0; + /* c8 ignore stop */ + //@ts-ignore + if (typeof realZlib[mode] !== 'function') { + throw new TypeError('Compression method not supported: ' + mode); + } + // this will throw if any options are invalid for the class selected + try { + // @types/node doesn't know that it exports the classes, but they're there + //@ts-ignore + this.#handle = new realZlib[mode](opts); + } + catch (er) { + // make sure that all errors get decorated properly + throw new ZlibError(er, this.constructor); + } + this.#onError = err => { + // no sense raising multiple errors, since we abort on the first one. + if (this.#sawError) + return; + this.#sawError = true; + // there is no way to cleanly recover. + // continuing only obscures problems. + this.close(); + this.emit('error', err); + }; + this.#handle?.on('error', er => this.#onError(new ZlibError(er))); + this.once('end', () => this.close); + } + close() { + if (this.#handle) { + this.#handle.close(); + this.#handle = undefined; + this.emit('close'); + } + } + reset() { + if (!this.#sawError) { + (0, assert_1.default)(this.#handle, 'zlib binding closed'); + //@ts-ignore + return this.#handle.reset?.(); + } + } + flush(flushFlag) { + if (this.ended) + return; + if (typeof flushFlag !== 'number') + flushFlag = this.#fullFlushFlag; + this.write(Object.assign(buffer_1.Buffer.alloc(0), { [_flushFlag]: flushFlag })); + } + end(chunk, encoding, cb) { + /* c8 ignore start */ + if (typeof chunk === 'function') { + cb = chunk; + encoding = undefined; + chunk = undefined; + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = undefined; + } + /* c8 ignore stop */ + if (chunk) { + if (encoding) + this.write(chunk, encoding); + else + this.write(chunk); + } + this.flush(this.#finishFlushFlag); + this.#ended = true; + return super.end(cb); + } + get ended() { + return this.#ended; + } + // overridden in the gzip classes to do portable writes + [_superWrite](data) { + return super.write(data); + } + write(chunk, encoding, cb) { + // process the chunk using the sync process + // then super.write() all the outputted chunks + if (typeof encoding === 'function') + (cb = encoding), (encoding = 'utf8'); + if (typeof chunk === 'string') + chunk = buffer_1.Buffer.from(chunk, encoding); + if (this.#sawError) + return; + (0, assert_1.default)(this.#handle, 'zlib binding closed'); + // _processChunk tries to .close() the native handle after it's done, so we + // intercept that by temporarily making it a no-op. + // diving into the node:zlib internals a bit here + const nativeHandle = this.#handle + ._handle; + const originalNativeClose = nativeHandle.close; + nativeHandle.close = () => { }; + const originalClose = this.#handle.close; + this.#handle.close = () => { }; + // It also calls `Buffer.concat()` at the end, which may be convenient + // for some, but which we are not interested in as it slows us down. + passthroughBufferConcat(true); + let result = undefined; + try { + const flushFlag = typeof chunk[_flushFlag] === 'number' + ? chunk[_flushFlag] + : this.#flushFlag; + result = this.#handle._processChunk(chunk, flushFlag); + // if we don't throw, reset it back how it was + passthroughBufferConcat(false); + } + catch (err) { + // or if we do, put Buffer.concat() back before we emit error + // Error events call into user code, which may call Buffer.concat() + passthroughBufferConcat(false); + this.#onError(new ZlibError(err, this.write)); + } + finally { + if (this.#handle) { + // Core zlib resets `_handle` to null after attempting to close the + // native handle. Our no-op handler prevented actual closure, but we + // need to restore the `._handle` property. + ; + this.#handle._handle = + nativeHandle; + nativeHandle.close = originalNativeClose; + this.#handle.close = originalClose; + // `_processChunk()` adds an 'error' listener. If we don't remove it + // after each call, these handlers start piling up. + this.#handle.removeAllListeners('error'); + // make sure OUR error listener is still attached tho + } + } + if (this.#handle) + this.#handle.on('error', er => this.#onError(new ZlibError(er, this.write))); + let writeReturn; + if (result) { + if (Array.isArray(result) && result.length > 0) { + const r = result[0]; + // The first buffer is always `handle._outBuffer`, which would be + // re-used for later invocations; so, we always have to copy that one. + writeReturn = this[_superWrite](buffer_1.Buffer.from(r)); + for (let i = 1; i < result.length; i++) { + writeReturn = this[_superWrite](result[i]); + } + } + else { + // either a single Buffer or an empty array + writeReturn = this[_superWrite](buffer_1.Buffer.from(result)); + } + } + if (cb) + cb(); + return writeReturn; + } +} +class Zlib extends ZlibBase { + #level; + #strategy; + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants_js_1.constants.Z_NO_FLUSH; + opts.finishFlush = opts.finishFlush || constants_js_1.constants.Z_FINISH; + opts.fullFlushFlag = constants_js_1.constants.Z_FULL_FLUSH; + super(opts, mode); + this.#level = opts.level; + this.#strategy = opts.strategy; + } + params(level, strategy) { + if (this.sawError) + return; + if (!this.handle) + throw new Error('cannot switch params when binding is closed'); + // no way to test this without also not supporting params at all + /* c8 ignore start */ + if (!this.handle.params) + throw new Error('not supported in this implementation'); + /* c8 ignore stop */ + if (this.#level !== level || this.#strategy !== strategy) { + this.flush(constants_js_1.constants.Z_SYNC_FLUSH); + (0, assert_1.default)(this.handle, 'zlib binding closed'); + // .params() calls .flush(), but the latter is always async in the + // core zlib. We override .flush() temporarily to intercept that and + // flush synchronously. + const origFlush = this.handle.flush; + this.handle.flush = (flushFlag, cb) => { + /* c8 ignore start */ + if (typeof flushFlag === 'function') { + cb = flushFlag; + flushFlag = this.flushFlag; + } + /* c8 ignore stop */ + this.flush(flushFlag); + cb?.(); + }; + try { + ; + this.handle.params(level, strategy); + } + finally { + this.handle.flush = origFlush; + } + /* c8 ignore start */ + if (this.handle) { + this.#level = level; + this.#strategy = strategy; + } + /* c8 ignore stop */ + } + } +} +exports.Zlib = Zlib; +// minimal 2-byte header +class Deflate extends Zlib { + constructor(opts) { + super(opts, 'Deflate'); + } +} +exports.Deflate = Deflate; +class Inflate extends Zlib { + constructor(opts) { + super(opts, 'Inflate'); + } +} +exports.Inflate = Inflate; +class Gzip extends Zlib { + #portable; + constructor(opts) { + super(opts, 'Gzip'); + this.#portable = opts && !!opts.portable; + } + [_superWrite](data) { + if (!this.#portable) + return super[_superWrite](data); + // we'll always get the header emitted in one first chunk + // overwrite the OS indicator byte with 0xFF + this.#portable = false; + data[9] = 255; + return super[_superWrite](data); + } +} +exports.Gzip = Gzip; +class Gunzip extends Zlib { + constructor(opts) { + super(opts, 'Gunzip'); + } +} +exports.Gunzip = Gunzip; +// raw - no header +class DeflateRaw extends Zlib { + constructor(opts) { + super(opts, 'DeflateRaw'); + } +} +exports.DeflateRaw = DeflateRaw; +class InflateRaw extends Zlib { + constructor(opts) { + super(opts, 'InflateRaw'); + } +} +exports.InflateRaw = InflateRaw; +// auto-detect header. +class Unzip extends Zlib { + constructor(opts) { + super(opts, 'Unzip'); + } +} +exports.Unzip = Unzip; +class Brotli extends ZlibBase { + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants_js_1.constants.BROTLI_OPERATION_PROCESS; + opts.finishFlush = + opts.finishFlush || constants_js_1.constants.BROTLI_OPERATION_FINISH; + opts.fullFlushFlag = constants_js_1.constants.BROTLI_OPERATION_FLUSH; + super(opts, mode); + } +} +class BrotliCompress extends Brotli { + constructor(opts) { + super(opts, 'BrotliCompress'); + } +} +exports.BrotliCompress = BrotliCompress; +class BrotliDecompress extends Brotli { + constructor(opts) { + super(opts, 'BrotliDecompress'); + } +} +exports.BrotliDecompress = BrotliDecompress; +class Zstd extends ZlibBase { + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants_js_1.constants.ZSTD_e_continue; + opts.finishFlush = opts.finishFlush || constants_js_1.constants.ZSTD_e_end; + opts.fullFlushFlag = constants_js_1.constants.ZSTD_e_flush; + super(opts, mode); + } +} +class ZstdCompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdCompress'); + } +} +exports.ZstdCompress = ZstdCompress; +class ZstdDecompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdDecompress'); + } +} +exports.ZstdDecompress = ZstdDecompress; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/index.js.map b/tools/ui/node_modules/minizlib/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ca841077b67e74e156621b7db5fdd43d3fb268c4 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,oDAA2B;AAC3B,mCAA+B;AAC/B,uCAAmC;AACnC,+CAAgC;AAChC,iDAA0C;AAC1C,+CAA0C;AAAjC,yGAAA,SAAS,OAAA;AAElB,MAAM,oBAAoB,GAAG,eAAM,CAAC,MAAM,CAAA;AAC1C,MAAM,IAAI,GAAG,MAAM,CAAC,wBAAwB,CAAC,eAAM,EAAE,QAAQ,CAAC,CAAA;AAC9D,MAAM,IAAI,GAAG,CAAC,IAAc,EAAE,EAAE,CAAC,IAAyB,CAAA;AAC1D,MAAM,uBAAuB,GAC3B,IAAI,EAAE,QAAQ,KAAK,IAAI,IAAI,IAAI,EAAE,GAAG,KAAK,SAAS;IAChD,CAAC,CAAC,CAAC,QAAiB,EAAE,EAAE;QACpB,eAAM,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,oBAAoB,CAAA;IACxD,CAAC;IACH,CAAC,CAAC,CAAC,CAAU,EAAE,EAAE,GAAE,CAAC,CAAA;AAExB,MAAM,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AAEzC,MAAa,SAAU,SAAQ,KAAK;IAClC,IAAI,CAAS;IACb,KAAK,CAAS;IACd,YAAY,GAAkC,EAAE,MAAiB;QAC/D,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;QAC7C,IAAI,CAAC,IAAI,GAAI,GAA6B,CAAC,IAAI,CAAA;QAC/C,IAAI,CAAC,KAAK,GAAI,GAA6B,CAAC,KAAK,CAAA;QACjD,oBAAoB;QACpB,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,IAAI,CAAC,IAAI,GAAG,YAAY,CAAA;QAExC,IAAI,CAAC,OAAO,GAAG,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAA;QACrC,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,WAAW,CAAC,CAAA;IAC3D,CAAC;IAED,IAAI,IAAI;QACN,OAAO,WAAW,CAAA;IACpB,CAAC;CACF;AAjBD,8BAiBC;AAED,uCAAuC;AACvC,wDAAwD;AACxD,uDAAuD;AACvD,gCAAgC;AAChC,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAA;AAkCtC,MAAe,QAAS,SAAQ,mBAAoC;IAClE,SAAS,GAAY,KAAK,CAAA;IAC1B,MAAM,GAAY,KAAK,CAAA;IACvB,UAAU,CAAQ;IAClB,gBAAgB,CAAQ;IACxB,cAAc,CAAQ;IACtB,OAAO,CAAa;IACpB,QAAQ,CAAyB;IAEjC,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;IACD,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IACD,qBAAqB;IACrB,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,UAAU,CAAA;IACxB,CAAC;IACD,oBAAoB;IAEpB,YAAY,IAAqB,EAAE,IAAsC;QACvE,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;YACnC,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAA;QAEjE,YAAY;QACZ,KAAK,CAAC,IAAI,CAAC,CAAA;QAEX,qBAAqB;QACrB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC,CAAA;QACjC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,WAAW,IAAI,CAAC,CAAA;QAC7C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,aAAa,IAAI,CAAC,CAAA;QAC7C,oBAAoB;QAEpB,YAAY;QACZ,IAAI,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,UAAU,EAAE,CAAC;YACzC,MAAM,IAAI,SAAS,CAAC,oCAAoC,GAAG,IAAI,CAAC,CAAA;QAClE,CAAC;QAED,oEAAoE;QACpE,IAAI,CAAC;YACH,0EAA0E;YAC1E,YAAY;YACZ,IAAI,CAAC,OAAO,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAA;QACzC,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,mDAAmD;YACnD,MAAM,IAAI,SAAS,CAAC,EAA2B,EAAE,IAAI,CAAC,WAAW,CAAC,CAAA;QACpE,CAAC;QAED,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,EAAE;YACpB,qEAAqE;YACrE,IAAI,IAAI,CAAC,SAAS;gBAAE,OAAM;YAE1B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;YAErB,sCAAsC;YACtC,qCAAqC;YACrC,IAAI,CAAC,KAAK,EAAE,CAAA;YACZ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;QACzB,CAAC,CAAA;QAED,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QACjE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IACpC,CAAC;IAED,KAAK;QACH,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAA;YACpB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAA;YACxB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QACpB,CAAC;IACH,CAAC;IAED,KAAK;QACH,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,IAAA,gBAAM,EAAC,IAAI,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAA;YAC3C,YAAY;YACZ,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAA;QAC/B,CAAC;IACH,CAAC;IAED,KAAK,CAAC,SAAkB;QACtB,IAAI,IAAI,CAAC,KAAK;YAAE,OAAM;QAEtB,IAAI,OAAO,SAAS,KAAK,QAAQ;YAAE,SAAS,GAAG,IAAI,CAAC,cAAc,CAAA;QAElE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,eAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAA;IACzE,CAAC;IASD,GAAG,CACD,KAAyC,EACzC,QAA2C,EAC3C,EAAe;QAEf,qBAAqB;QACrB,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;YAChC,EAAE,GAAG,KAAK,CAAA;YACV,QAAQ,GAAG,SAAS,CAAA;YACpB,KAAK,GAAG,SAAS,CAAA;QACnB,CAAC;QACD,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;YACnC,EAAE,GAAG,QAAQ,CAAA;YACb,QAAQ,GAAG,SAAS,CAAA;QACtB,CAAC;QACD,oBAAoB;QACpB,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,QAAQ;gBAAE,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;;gBACpC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACxB,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QACjC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;QAClB,OAAO,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IACtB,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,uDAAuD;IACvD,CAAC,WAAW,CAAC,CAAC,IAAwC;QACpD,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAC1B,CAAC;IAQD,KAAK,CACH,KAAyB,EACzB,QAA2C,EAC3C,EAAe;QAEf,2CAA2C;QAC3C,8CAA8C;QAC9C,IAAI,OAAO,QAAQ,KAAK,UAAU;YAChC,CAAC,EAAE,GAAG,QAAQ,CAAC,EAAE,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAA;QAEtC,IAAI,OAAO,KAAK,KAAK,QAAQ;YAC3B,KAAK,GAAG,eAAM,CAAC,IAAI,CAAC,KAAe,EAAE,QAA0B,CAAC,CAAA;QAElE,IAAI,IAAI,CAAC,SAAS;YAAE,OAAM;QAC1B,IAAA,gBAAM,EAAC,IAAI,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAA;QAE3C,2EAA2E;QAC3E,mDAAmD;QACnD,iDAAiD;QACjD,MAAM,YAAY,GAAI,IAAI,CAAC,OAAuC;aAC/D,OAAO,CAAA;QACV,MAAM,mBAAmB,GAAG,YAAY,CAAC,KAAK,CAAA;QAC9C,YAAY,CAAC,KAAK,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;QAC7B,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAA;QACxC,IAAI,CAAC,OAAO,CAAC,KAAK,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;QAC7B,sEAAsE;QACtE,oEAAoE;QACpE,uBAAuB,CAAC,IAAI,CAAC,CAAA;QAC7B,IAAI,MAAM,GAAkC,SAAS,CAAA;QACrD,IAAI,CAAC;YACH,MAAM,SAAS,GACb,OAAO,KAAK,CAAC,UAAU,CAAC,KAAK,QAAQ;gBACnC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC;gBACnB,CAAC,CAAC,IAAI,CAAC,UAAU,CAAA;YACrB,MAAM,GACJ,IAAI,CAAC,OAGN,CAAC,aAAa,CAAC,KAAe,EAAE,SAAS,CAAC,CAAA;YAC3C,8CAA8C;YAC9C,uBAAuB,CAAC,KAAK,CAAC,CAAA;QAChC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,6DAA6D;YAC7D,mEAAmE;YACnE,uBAAuB,CAAC,KAAK,CAAC,CAAA;YAC9B,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,GAA4B,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;QACxE,CAAC;gBAAS,CAAC;YACT,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBACjB,mEAAmE;gBACnE,oEAAoE;gBACpE,2CAA2C;gBAC3C,CAAC;gBAAC,IAAI,CAAC,OAAuC,CAAC,OAAO;oBACpD,YAAY,CAAA;gBACd,YAAY,CAAC,KAAK,GAAG,mBAAmB,CAAA;gBACxC,IAAI,CAAC,OAAO,CAAC,KAAK,GAAG,aAAa,CAAA;gBAClC,oEAAoE;gBACpE,mDAAmD;gBACnD,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAA;gBACxC,qDAAqD;YACvD,CAAC;QACH,CAAC;QAED,IAAI,IAAI,CAAC,OAAO;YACd,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAE9E,IAAI,WAAW,CAAA;QACf,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC/C,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;gBACnB,iEAAiE;gBACjE,sEAAsE;gBACtE,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,eAAM,CAAC,IAAI,CAAC,CAAW,CAAC,CAAC,CAAA;gBACzD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;oBACvC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,CAAW,CAAC,CAAA;gBACtD,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,2CAA2C;gBAC3C,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,eAAM,CAAC,IAAI,CAAC,MAAqB,CAAC,CAAC,CAAA;YACrE,CAAC;QACH,CAAC;QAED,IAAI,EAAE;YAAE,EAAE,EAAE,CAAA;QACZ,OAAO,WAAW,CAAA;IACpB,CAAC;CACF;AAOD,MAAa,IAAK,SAAQ,QAAQ;IAChC,MAAM,CAAS;IACf,SAAS,CAAS;IAElB,YAAY,IAAiB,EAAE,IAAc;QAC3C,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,wBAAS,CAAC,UAAU,CAAA;QAC/C,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,wBAAS,CAAC,QAAQ,CAAA;QACzD,IAAI,CAAC,aAAa,GAAG,wBAAS,CAAC,YAAY,CAAA;QAC3C,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAEjB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAA;QACxB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAA;IAChC,CAAC;IAED,MAAM,CAAC,KAAa,EAAE,QAAgB;QACpC,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAM;QAEzB,IAAI,CAAC,IAAI,CAAC,MAAM;YACd,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;QAEhE,gEAAgE;QAChE,qBAAqB;QACrB,IAAI,CAAE,IAAI,CAAC,MAA2B,CAAC,MAAM;YAC3C,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;QACzD,oBAAoB;QAEpB,IAAI,IAAI,CAAC,MAAM,KAAK,KAAK,IAAI,IAAI,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;YACzD,IAAI,CAAC,KAAK,CAAC,wBAAS,CAAC,YAAY,CAAC,CAAA;YAClC,IAAA,gBAAM,EAAC,IAAI,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAA;YAC1C,kEAAkE;YAClE,oEAAoE;YACpE,uBAAuB;YACvB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAA;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,GAAG,CAClB,SAAiC,EACjC,EAAe,EACf,EAAE;gBACF,qBAAqB;gBACrB,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;oBACpC,EAAE,GAAG,SAAS,CAAA;oBACd,SAAS,GAAG,IAAI,CAAC,SAAS,CAAA;gBAC5B,CAAC;gBACD,oBAAoB;gBACpB,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;gBACrB,EAAE,EAAE,EAAE,CAAA;YACR,CAAC,CAAA;YACD,IAAI,CAAC;gBACH,CAAC;gBACC,IAAI,CAAC,MAGN,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;YAC3B,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC,MAAM,CAAC,KAAK,GAAG,SAAS,CAAA;YAC/B,CAAC;YACD,qBAAqB;YACrB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;gBACnB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;YAC3B,CAAC;YACD,oBAAoB;QACtB,CAAC;IACH,CAAC;CACF;AAjED,oBAiEC;AAED,wBAAwB;AACxB,MAAa,OAAQ,SAAQ,IAAI;IAC/B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACxB,CAAC;CACF;AAJD,0BAIC;AAED,MAAa,OAAQ,SAAQ,IAAI;IAC/B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACxB,CAAC;CACF;AAJD,0BAIC;AAID,MAAa,IAAK,SAAQ,IAAI;IAC5B,SAAS,CAAS;IAClB,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;QACnB,IAAI,CAAC,SAAS,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAA;IAC1C,CAAC;IAED,CAAC,WAAW,CAAC,CAAC,IAAwC;QACpD,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAA;QAEpD,yDAAyD;QACzD,4CAA4C;QAC5C,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;QACtB,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAA;QACb,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAA;IACjC,CAAC;CACF;AAhBD,oBAgBC;AAED,MAAa,MAAO,SAAQ,IAAI;IAC9B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;IACvB,CAAC;CACF;AAJD,wBAIC;AAED,kBAAkB;AAClB,MAAa,UAAW,SAAQ,IAAI;IAClC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;IAC3B,CAAC;CACF;AAJD,gCAIC;AAED,MAAa,UAAW,SAAQ,IAAI;IAClC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;IAC3B,CAAC;CACF;AAJD,gCAIC;AAED,sBAAsB;AACtB,MAAa,KAAM,SAAQ,IAAI;IAC7B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACtB,CAAC;CACF;AAJD,sBAIC;AAED,MAAM,MAAO,SAAQ,QAAQ;IAC3B,YAAY,IAAiB,EAAE,IAAgB;QAC7C,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,wBAAS,CAAC,wBAAwB,CAAA;QAC7D,IAAI,CAAC,WAAW;YACd,IAAI,CAAC,WAAW,IAAI,wBAAS,CAAC,uBAAuB,CAAA;QACvD,IAAI,CAAC,aAAa,GAAG,wBAAS,CAAC,sBAAsB,CAAA;QACrD,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACnB,CAAC;CACF;AAED,MAAa,cAAe,SAAQ,MAAM;IACxC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAA;IAC/B,CAAC;CACF;AAJD,wCAIC;AAED,MAAa,gBAAiB,SAAQ,MAAM;IAC1C,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAA;IACjC,CAAC;CACF;AAJD,4CAIC;AAED,MAAM,IAAK,SAAQ,QAAQ;IACzB,YAAY,IAAiB,EAAE,IAAc;QAC3C,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,wBAAS,CAAC,eAAe,CAAA;QACpD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,wBAAS,CAAC,UAAU,CAAA;QAC3D,IAAI,CAAC,aAAa,GAAG,wBAAS,CAAC,YAAY,CAAA;QAC3C,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACnB,CAAC;CACF;AAED,MAAa,YAAa,SAAQ,IAAI;IACpC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAA;IAC7B,CAAC;CACF;AAJD,oCAIC;AAED,MAAa,cAAe,SAAQ,IAAI;IACtC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAA;IAC/B,CAAC;CACF;AAJD,wCAIC","sourcesContent":["import assert from 'assert'\nimport { Buffer } from 'buffer'\nimport { Minipass } from 'minipass'\nimport * as realZlib from 'zlib'\nimport { constants } from './constants.js'\nexport { constants } from './constants.js'\n\nconst OriginalBufferConcat = Buffer.concat\nconst desc = Object.getOwnPropertyDescriptor(Buffer, 'concat')\nconst noop = (args: Buffer[]) => args as unknown as Buffer\nconst passthroughBufferConcat =\n desc?.writable === true || desc?.set !== undefined\n ? (makeNoOp: boolean) => {\n Buffer.concat = makeNoOp ? noop : OriginalBufferConcat\n }\n : (_: boolean) => {}\n\nconst _superWrite = Symbol('_superWrite')\n\nexport class ZlibError extends Error {\n code?: string\n errno?: number\n constructor(err: NodeJS.ErrnoException | Error, origin?: Function) {\n super('zlib: ' + err.message, { cause: err })\n this.code = (err as NodeJS.ErrnoException).code\n this.errno = (err as NodeJS.ErrnoException).errno\n /* c8 ignore next */\n if (!this.code) this.code = 'ZLIB_ERROR'\n\n this.message = 'zlib: ' + err.message\n Error.captureStackTrace(this, origin ?? this.constructor)\n }\n\n get name() {\n return 'ZlibError'\n }\n}\n\n// the Zlib class they all inherit from\n// This thing manages the queue of requests, and returns\n// true or false if there is anything in the queue when\n// you call the .write() method.\nconst _flushFlag = Symbol('flushFlag')\n\nexport type ChunkWithFlushFlag = Minipass.ContiguousData & {\n [_flushFlag]?: number\n}\n\nexport type ZlibBaseOptions = Minipass.Options & {\n flush?: number\n finishFlush?: number\n fullFlushFlag?: number\n}\n\nexport type ZlibHandle =\n | realZlib.Gzip\n | realZlib.Gunzip\n | realZlib.Deflate\n | realZlib.Inflate\n | realZlib.DeflateRaw\n | realZlib.InflateRaw\n | realZlib.BrotliCompress\n | realZlib.BrotliDecompress\n | realZlib.ZstdCompress\n | realZlib.ZstdDecompress\nexport type ZlibMode =\n | 'Gzip'\n | 'Gunzip'\n | 'Deflate'\n | 'Inflate'\n | 'DeflateRaw'\n | 'InflateRaw'\n | 'Unzip'\nexport type BrotliMode = 'BrotliCompress' | 'BrotliDecompress'\nexport type ZstdMode = 'ZstdCompress' | 'ZstdDecompress'\n\nabstract class ZlibBase extends Minipass {\n #sawError: boolean = false\n #ended: boolean = false\n #flushFlag: number\n #finishFlushFlag: number\n #fullFlushFlag: number\n #handle?: ZlibHandle\n #onError: (err: ZlibError) => any\n\n get sawError() {\n return this.#sawError\n }\n get handle() {\n return this.#handle\n }\n /* c8 ignore start */\n get flushFlag() {\n return this.#flushFlag\n }\n /* c8 ignore stop */\n\n constructor(opts: ZlibBaseOptions, mode: ZlibMode | BrotliMode | ZstdMode) {\n if (!opts || typeof opts !== 'object')\n throw new TypeError('invalid options for ZlibBase constructor')\n\n //@ts-ignore\n super(opts)\n\n /* c8 ignore start */\n this.#flushFlag = opts.flush ?? 0\n this.#finishFlushFlag = opts.finishFlush ?? 0\n this.#fullFlushFlag = opts.fullFlushFlag ?? 0\n /* c8 ignore stop */\n\n //@ts-ignore\n if (typeof realZlib[mode] !== 'function') {\n throw new TypeError('Compression method not supported: ' + mode)\n }\n\n // this will throw if any options are invalid for the class selected\n try {\n // @types/node doesn't know that it exports the classes, but they're there\n //@ts-ignore\n this.#handle = new realZlib[mode](opts)\n } catch (er) {\n // make sure that all errors get decorated properly\n throw new ZlibError(er as NodeJS.ErrnoException, this.constructor)\n }\n\n this.#onError = err => {\n // no sense raising multiple errors, since we abort on the first one.\n if (this.#sawError) return\n\n this.#sawError = true\n\n // there is no way to cleanly recover.\n // continuing only obscures problems.\n this.close()\n this.emit('error', err)\n }\n\n this.#handle?.on('error', er => this.#onError(new ZlibError(er)))\n this.once('end', () => this.close)\n }\n\n close() {\n if (this.#handle) {\n this.#handle.close()\n this.#handle = undefined\n this.emit('close')\n }\n }\n\n reset() {\n if (!this.#sawError) {\n assert(this.#handle, 'zlib binding closed')\n //@ts-ignore\n return this.#handle.reset?.()\n }\n }\n\n flush(flushFlag?: number) {\n if (this.ended) return\n\n if (typeof flushFlag !== 'number') flushFlag = this.#fullFlushFlag\n\n this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }))\n }\n\n end(cb?: () => void): this\n end(chunk: ChunkWithFlushFlag, cb?: () => void): this\n end(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): this\n end(\n chunk?: ChunkWithFlushFlag | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n /* c8 ignore start */\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n /* c8 ignore stop */\n if (chunk) {\n if (encoding) this.write(chunk, encoding)\n else this.write(chunk)\n }\n this.flush(this.#finishFlushFlag)\n this.#ended = true\n return super.end(cb)\n }\n\n get ended() {\n return this.#ended\n }\n\n // overridden in the gzip classes to do portable writes\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n return super.write(data)\n }\n\n write(chunk: ChunkWithFlushFlag, cb?: () => void): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n // process the chunk using the sync process\n // then super.write() all the outputted chunks\n if (typeof encoding === 'function')\n (cb = encoding), (encoding = 'utf8')\n\n if (typeof chunk === 'string')\n chunk = Buffer.from(chunk as string, encoding as BufferEncoding)\n\n if (this.#sawError) return\n assert(this.#handle, 'zlib binding closed')\n\n // _processChunk tries to .close() the native handle after it's done, so we\n // intercept that by temporarily making it a no-op.\n // diving into the node:zlib internals a bit here\n const nativeHandle = (this.#handle as unknown as { _handle: any })\n ._handle\n const originalNativeClose = nativeHandle.close\n nativeHandle.close = () => {}\n const originalClose = this.#handle.close\n this.#handle.close = () => {}\n // It also calls `Buffer.concat()` at the end, which may be convenient\n // for some, but which we are not interested in as it slows us down.\n passthroughBufferConcat(true)\n let result: undefined | Buffer | Buffer[] = undefined\n try {\n const flushFlag =\n typeof chunk[_flushFlag] === 'number'\n ? chunk[_flushFlag]\n : this.#flushFlag\n result = (\n this.#handle as unknown as {\n _processChunk: (chunk: Buffer, flushFlag: number) => Buffer[]\n }\n )._processChunk(chunk as Buffer, flushFlag)\n // if we don't throw, reset it back how it was\n passthroughBufferConcat(false)\n } catch (err) {\n // or if we do, put Buffer.concat() back before we emit error\n // Error events call into user code, which may call Buffer.concat()\n passthroughBufferConcat(false)\n this.#onError(new ZlibError(err as NodeJS.ErrnoException, this.write))\n } finally {\n if (this.#handle) {\n // Core zlib resets `_handle` to null after attempting to close the\n // native handle. Our no-op handler prevented actual closure, but we\n // need to restore the `._handle` property.\n ;(this.#handle as unknown as { _handle: any })._handle =\n nativeHandle\n nativeHandle.close = originalNativeClose\n this.#handle.close = originalClose\n // `_processChunk()` adds an 'error' listener. If we don't remove it\n // after each call, these handlers start piling up.\n this.#handle.removeAllListeners('error')\n // make sure OUR error listener is still attached tho\n }\n }\n\n if (this.#handle)\n this.#handle.on('error', er => this.#onError(new ZlibError(er, this.write)))\n\n let writeReturn\n if (result) {\n if (Array.isArray(result) && result.length > 0) {\n const r = result[0]\n // The first buffer is always `handle._outBuffer`, which would be\n // re-used for later invocations; so, we always have to copy that one.\n writeReturn = this[_superWrite](Buffer.from(r as Buffer))\n for (let i = 1; i < result.length; i++) {\n writeReturn = this[_superWrite](result[i] as Buffer)\n }\n } else {\n // either a single Buffer or an empty array\n writeReturn = this[_superWrite](Buffer.from(result as Buffer | []))\n }\n }\n\n if (cb) cb()\n return writeReturn\n }\n}\n\nexport type ZlibOptions = ZlibBaseOptions & {\n level?: number\n strategy?: number\n}\n\nexport class Zlib extends ZlibBase {\n #level?: number\n #strategy?: number\n\n constructor(opts: ZlibOptions, mode: ZlibMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.Z_NO_FLUSH\n opts.finishFlush = opts.finishFlush || constants.Z_FINISH\n opts.fullFlushFlag = constants.Z_FULL_FLUSH\n super(opts, mode)\n\n this.#level = opts.level\n this.#strategy = opts.strategy\n }\n\n params(level: number, strategy: number) {\n if (this.sawError) return\n\n if (!this.handle)\n throw new Error('cannot switch params when binding is closed')\n\n // no way to test this without also not supporting params at all\n /* c8 ignore start */\n if (!(this.handle as { params?: any }).params)\n throw new Error('not supported in this implementation')\n /* c8 ignore stop */\n\n if (this.#level !== level || this.#strategy !== strategy) {\n this.flush(constants.Z_SYNC_FLUSH)\n assert(this.handle, 'zlib binding closed')\n // .params() calls .flush(), but the latter is always async in the\n // core zlib. We override .flush() temporarily to intercept that and\n // flush synchronously.\n const origFlush = this.handle.flush\n this.handle.flush = (\n flushFlag?: (() => void) | number,\n cb?: () => void,\n ) => {\n /* c8 ignore start */\n if (typeof flushFlag === 'function') {\n cb = flushFlag\n flushFlag = this.flushFlag\n }\n /* c8 ignore stop */\n this.flush(flushFlag)\n cb?.()\n }\n try {\n ;(\n this.handle as unknown as {\n params: (level?: number, strategy?: number) => void\n }\n ).params(level, strategy)\n } finally {\n this.handle.flush = origFlush\n }\n /* c8 ignore start */\n if (this.handle) {\n this.#level = level\n this.#strategy = strategy\n }\n /* c8 ignore stop */\n }\n }\n}\n\n// minimal 2-byte header\nexport class Deflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Deflate')\n }\n}\n\nexport class Inflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Inflate')\n }\n}\n\n// gzip - bigger header, same deflate compression\nexport type GzipOptions = ZlibOptions & { portable?: boolean }\nexport class Gzip extends Zlib {\n #portable: boolean\n constructor(opts: GzipOptions) {\n super(opts, 'Gzip')\n this.#portable = opts && !!opts.portable\n }\n\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n if (!this.#portable) return super[_superWrite](data)\n\n // we'll always get the header emitted in one first chunk\n // overwrite the OS indicator byte with 0xFF\n this.#portable = false\n data[9] = 255\n return super[_superWrite](data)\n }\n}\n\nexport class Gunzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Gunzip')\n }\n}\n\n// raw - no header\nexport class DeflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'DeflateRaw')\n }\n}\n\nexport class InflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'InflateRaw')\n }\n}\n\n// auto-detect header.\nexport class Unzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Unzip')\n }\n}\n\nclass Brotli extends ZlibBase {\n constructor(opts: ZlibOptions, mode: BrotliMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS\n opts.finishFlush =\n opts.finishFlush || constants.BROTLI_OPERATION_FINISH\n opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH\n super(opts, mode)\n }\n}\n\nexport class BrotliCompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliCompress')\n }\n}\n\nexport class BrotliDecompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliDecompress')\n }\n}\n\nclass Zstd extends ZlibBase {\n constructor(opts: ZlibOptions, mode: ZstdMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.ZSTD_e_continue\n opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end\n opts.fullFlushFlag = constants.ZSTD_e_flush\n super(opts, mode)\n }\n}\n\nexport class ZstdCompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdCompress')\n }\n}\n\nexport class ZstdDecompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdDecompress')\n }\n}\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/commonjs/package.json b/tools/ui/node_modules/minizlib/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/tools/ui/node_modules/minizlib/dist/esm/constants.d.ts b/tools/ui/node_modules/minizlib/dist/esm/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67c47b4aa34ea79f63632549c0f4e0439711d12f --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/constants.d.ts @@ -0,0 +1,2 @@ +export declare const constants: any; +//# sourceMappingURL=constants.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/constants.d.ts.map b/tools/ui/node_modules/minizlib/dist/esm/constants.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..25affce76739678bb862eb8edd35904a7a78ed31 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/constants.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,SAAS,KAiHrB,CAAA"} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/constants.js b/tools/ui/node_modules/minizlib/dist/esm/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..7faf40be5068d01a892b1dbecc786c61b8e71526 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/constants.js @@ -0,0 +1,117 @@ +// Update with any zlib constants that are added or changed in the future. +// Node v6 didn't export this, so we just hard code the version and rely +// on all the other hard-coded values from zlib v4736. When node v6 +// support drops, we can just export the realZlibConstants object. +import realZlib from 'zlib'; +/* c8 ignore start */ +const realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }; +/* c8 ignore stop */ +export const constants = Object.freeze(Object.assign(Object.create(null), { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + Z_VERSION_ERROR: -6, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + DEFLATE: 1, + INFLATE: 2, + GZIP: 3, + GUNZIP: 4, + DEFLATERAW: 5, + INFLATERAW: 6, + UNZIP: 7, + BROTLI_DECODE: 8, + BROTLI_ENCODE: 9, + Z_MIN_WINDOWBITS: 8, + Z_MAX_WINDOWBITS: 15, + Z_DEFAULT_WINDOWBITS: 15, + Z_MIN_CHUNK: 64, + Z_MAX_CHUNK: Infinity, + Z_DEFAULT_CHUNK: 16384, + Z_MIN_MEMLEVEL: 1, + Z_MAX_MEMLEVEL: 9, + Z_DEFAULT_MEMLEVEL: 8, + Z_MIN_LEVEL: -1, + Z_MAX_LEVEL: 9, + Z_DEFAULT_LEVEL: -1, + BROTLI_OPERATION_PROCESS: 0, + BROTLI_OPERATION_FLUSH: 1, + BROTLI_OPERATION_FINISH: 2, + BROTLI_OPERATION_EMIT_METADATA: 3, + BROTLI_MODE_GENERIC: 0, + BROTLI_MODE_TEXT: 1, + BROTLI_MODE_FONT: 2, + BROTLI_DEFAULT_MODE: 0, + BROTLI_MIN_QUALITY: 0, + BROTLI_MAX_QUALITY: 11, + BROTLI_DEFAULT_QUALITY: 11, + BROTLI_MIN_WINDOW_BITS: 10, + BROTLI_MAX_WINDOW_BITS: 24, + BROTLI_LARGE_MAX_WINDOW_BITS: 30, + BROTLI_DEFAULT_WINDOW: 22, + BROTLI_MIN_INPUT_BLOCK_BITS: 16, + BROTLI_MAX_INPUT_BLOCK_BITS: 24, + BROTLI_PARAM_MODE: 0, + BROTLI_PARAM_QUALITY: 1, + BROTLI_PARAM_LGWIN: 2, + BROTLI_PARAM_LGBLOCK: 3, + BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, + BROTLI_PARAM_SIZE_HINT: 5, + BROTLI_PARAM_LARGE_WINDOW: 6, + BROTLI_PARAM_NPOSTFIX: 7, + BROTLI_PARAM_NDIRECT: 8, + BROTLI_DECODER_RESULT_ERROR: 0, + BROTLI_DECODER_RESULT_SUCCESS: 1, + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, + BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, + BROTLI_DECODER_NO_ERROR: 0, + BROTLI_DECODER_SUCCESS: 1, + BROTLI_DECODER_NEEDS_MORE_INPUT: 2, + BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, + BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, + BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, + BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, + BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, + BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, + BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, + BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, + BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, + BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, + BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, + BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, + BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, + BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, + BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, + BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, + BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, + BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, + BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, + BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, + BROTLI_DECODER_ERROR_UNREACHABLE: -31, +}, realZlibConstants)); +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/constants.js.map b/tools/ui/node_modules/minizlib/dist/esm/constants.js.map new file mode 100644 index 0000000000000000000000000000000000000000..bf23cbbc79e0c5c49655880c2378a1dcfcbce9c5 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wEAAwE;AACxE,oEAAoE;AACpE,kEAAkE;AAClE,OAAO,QAAQ,MAAM,MAAM,CAAA;AAC3B,qBAAqB;AACrB,MAAM,iBAAiB,GAAG,QAAQ,CAAC,SAAS,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAA;AACrE,oBAAoB;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CACpC,MAAM,CAAC,MAAM,CACX,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EACnB;IACE,UAAU,EAAE,CAAC;IACb,eAAe,EAAE,CAAC;IAClB,YAAY,EAAE,CAAC;IACf,YAAY,EAAE,CAAC;IACf,QAAQ,EAAE,CAAC;IACX,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,YAAY,EAAE,CAAC;IACf,WAAW,EAAE,CAAC;IACd,OAAO,EAAE,CAAC,CAAC;IACX,cAAc,EAAE,CAAC,CAAC;IAClB,YAAY,EAAE,CAAC,CAAC;IAChB,WAAW,EAAE,CAAC,CAAC;IACf,WAAW,EAAE,CAAC,CAAC;IACf,eAAe,EAAE,CAAC,CAAC;IACnB,gBAAgB,EAAE,CAAC;IACnB,YAAY,EAAE,CAAC;IACf,kBAAkB,EAAE,CAAC;IACrB,qBAAqB,EAAE,CAAC,CAAC;IACzB,UAAU,EAAE,CAAC;IACb,cAAc,EAAE,CAAC;IACjB,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,kBAAkB,EAAE,CAAC;IACrB,OAAO,EAAE,CAAC;IACV,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,MAAM,EAAE,CAAC;IACT,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IACb,KAAK,EAAE,CAAC;IACR,aAAa,EAAE,CAAC;IAChB,aAAa,EAAE,CAAC;IAChB,gBAAgB,EAAE,CAAC;IACnB,gBAAgB,EAAE,EAAE;IACpB,oBAAoB,EAAE,EAAE;IACxB,WAAW,EAAE,EAAE;IACf,WAAW,EAAE,QAAQ;IACrB,eAAe,EAAE,KAAK;IACtB,cAAc,EAAE,CAAC;IACjB,cAAc,EAAE,CAAC;IACjB,kBAAkB,EAAE,CAAC;IACrB,WAAW,EAAE,CAAC,CAAC;IACf,WAAW,EAAE,CAAC;IACd,eAAe,EAAE,CAAC,CAAC;IACnB,wBAAwB,EAAE,CAAC;IAC3B,sBAAsB,EAAE,CAAC;IACzB,uBAAuB,EAAE,CAAC;IAC1B,8BAA8B,EAAE,CAAC;IACjC,mBAAmB,EAAE,CAAC;IACtB,gBAAgB,EAAE,CAAC;IACnB,gBAAgB,EAAE,CAAC;IACnB,mBAAmB,EAAE,CAAC;IACtB,kBAAkB,EAAE,CAAC;IACrB,kBAAkB,EAAE,EAAE;IACtB,sBAAsB,EAAE,EAAE;IAC1B,sBAAsB,EAAE,EAAE;IAC1B,sBAAsB,EAAE,EAAE;IAC1B,4BAA4B,EAAE,EAAE;IAChC,qBAAqB,EAAE,EAAE;IACzB,2BAA2B,EAAE,EAAE;IAC/B,2BAA2B,EAAE,EAAE;IAC/B,iBAAiB,EAAE,CAAC;IACpB,oBAAoB,EAAE,CAAC;IACvB,kBAAkB,EAAE,CAAC;IACrB,oBAAoB,EAAE,CAAC;IACvB,6CAA6C,EAAE,CAAC;IAChD,sBAAsB,EAAE,CAAC;IACzB,yBAAyB,EAAE,CAAC;IAC5B,qBAAqB,EAAE,CAAC;IACxB,oBAAoB,EAAE,CAAC;IACvB,2BAA2B,EAAE,CAAC;IAC9B,6BAA6B,EAAE,CAAC;IAChC,sCAAsC,EAAE,CAAC;IACzC,uCAAuC,EAAE,CAAC;IAC1C,qDAAqD,EAAE,CAAC;IACxD,iCAAiC,EAAE,CAAC;IACpC,uBAAuB,EAAE,CAAC;IAC1B,sBAAsB,EAAE,CAAC;IACzB,+BAA+B,EAAE,CAAC;IAClC,gCAAgC,EAAE,CAAC;IACnC,4CAA4C,EAAE,CAAC,CAAC;IAChD,oCAAoC,EAAE,CAAC,CAAC;IACxC,iDAAiD,EAAE,CAAC,CAAC;IACrD,mDAAmD,EAAE,CAAC,CAAC;IACvD,+CAA+C,EAAE,CAAC,CAAC;IACnD,oCAAoC,EAAE,CAAC,CAAC;IACxC,yCAAyC,EAAE,CAAC,CAAC;IAC7C,8CAA8C,EAAE,CAAC,CAAC;IAClD,0CAA0C,EAAE,CAAC,CAAC;IAC9C,0CAA0C,EAAE,CAAC,EAAE;IAC/C,qCAAqC,EAAE,CAAC,EAAE;IAC1C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,uCAAuC,EAAE,CAAC,EAAE;IAC5C,qCAAqC,EAAE,CAAC,EAAE;IAC1C,qCAAqC,EAAE,CAAC,EAAE;IAC1C,oCAAoC,EAAE,CAAC,EAAE;IACzC,uCAAuC,EAAE,CAAC,EAAE;IAC5C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,wCAAwC,EAAE,CAAC,EAAE;IAC7C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,sCAAsC,EAAE,CAAC,EAAE;IAC3C,wCAAwC,EAAE,CAAC,EAAE;IAC7C,wCAAwC,EAAE,CAAC,EAAE;IAC7C,2CAA2C,EAAE,CAAC,EAAE;IAChD,gCAAgC,EAAE,CAAC,EAAE;CACtC,EACD,iBAAiB,CAClB,CACF,CAAA","sourcesContent":["// Update with any zlib constants that are added or changed in the future.\n// Node v6 didn't export this, so we just hard code the version and rely\n// on all the other hard-coded values from zlib v4736. When node v6\n// support drops, we can just export the realZlibConstants object.\nimport realZlib from 'zlib'\n/* c8 ignore start */\nconst realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }\n/* c8 ignore stop */\n\nexport const constants = Object.freeze(\n Object.assign(\n Object.create(null),\n {\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n Z_VERSION_ERROR: -6,\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n DEFLATE: 1,\n INFLATE: 2,\n GZIP: 3,\n GUNZIP: 4,\n DEFLATERAW: 5,\n INFLATERAW: 6,\n UNZIP: 7,\n BROTLI_DECODE: 8,\n BROTLI_ENCODE: 9,\n Z_MIN_WINDOWBITS: 8,\n Z_MAX_WINDOWBITS: 15,\n Z_DEFAULT_WINDOWBITS: 15,\n Z_MIN_CHUNK: 64,\n Z_MAX_CHUNK: Infinity,\n Z_DEFAULT_CHUNK: 16384,\n Z_MIN_MEMLEVEL: 1,\n Z_MAX_MEMLEVEL: 9,\n Z_DEFAULT_MEMLEVEL: 8,\n Z_MIN_LEVEL: -1,\n Z_MAX_LEVEL: 9,\n Z_DEFAULT_LEVEL: -1,\n BROTLI_OPERATION_PROCESS: 0,\n BROTLI_OPERATION_FLUSH: 1,\n BROTLI_OPERATION_FINISH: 2,\n BROTLI_OPERATION_EMIT_METADATA: 3,\n BROTLI_MODE_GENERIC: 0,\n BROTLI_MODE_TEXT: 1,\n BROTLI_MODE_FONT: 2,\n BROTLI_DEFAULT_MODE: 0,\n BROTLI_MIN_QUALITY: 0,\n BROTLI_MAX_QUALITY: 11,\n BROTLI_DEFAULT_QUALITY: 11,\n BROTLI_MIN_WINDOW_BITS: 10,\n BROTLI_MAX_WINDOW_BITS: 24,\n BROTLI_LARGE_MAX_WINDOW_BITS: 30,\n BROTLI_DEFAULT_WINDOW: 22,\n BROTLI_MIN_INPUT_BLOCK_BITS: 16,\n BROTLI_MAX_INPUT_BLOCK_BITS: 24,\n BROTLI_PARAM_MODE: 0,\n BROTLI_PARAM_QUALITY: 1,\n BROTLI_PARAM_LGWIN: 2,\n BROTLI_PARAM_LGBLOCK: 3,\n BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,\n BROTLI_PARAM_SIZE_HINT: 5,\n BROTLI_PARAM_LARGE_WINDOW: 6,\n BROTLI_PARAM_NPOSTFIX: 7,\n BROTLI_PARAM_NDIRECT: 8,\n BROTLI_DECODER_RESULT_ERROR: 0,\n BROTLI_DECODER_RESULT_SUCCESS: 1,\n BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,\n BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,\n BROTLI_DECODER_NO_ERROR: 0,\n BROTLI_DECODER_SUCCESS: 1,\n BROTLI_DECODER_NEEDS_MORE_INPUT: 2,\n BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,\n BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,\n BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,\n BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,\n BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,\n BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,\n BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,\n BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,\n BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,\n BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,\n BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,\n BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,\n BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,\n BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,\n BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,\n BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,\n BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,\n BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,\n BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,\n BROTLI_DECODER_ERROR_UNREACHABLE: -31,\n },\n realZlibConstants,\n ),\n)\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/index.d.ts b/tools/ui/node_modules/minizlib/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8044bd061aac745cb532182ce714778303323530 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/index.d.ts @@ -0,0 +1,99 @@ +import { Buffer } from 'buffer'; +import { Minipass } from 'minipass'; +import * as realZlib from 'zlib'; +export { constants } from './constants.js'; +declare const _superWrite: unique symbol; +export declare class ZlibError extends Error { + code?: string; + errno?: number; + constructor(err: NodeJS.ErrnoException | Error, origin?: Function); + get name(): string; +} +declare const _flushFlag: unique symbol; +export type ChunkWithFlushFlag = Minipass.ContiguousData & { + [_flushFlag]?: number; +}; +export type ZlibBaseOptions = Minipass.Options & { + flush?: number; + finishFlush?: number; + fullFlushFlag?: number; +}; +export type ZlibHandle = realZlib.Gzip | realZlib.Gunzip | realZlib.Deflate | realZlib.Inflate | realZlib.DeflateRaw | realZlib.InflateRaw | realZlib.BrotliCompress | realZlib.BrotliDecompress | realZlib.ZstdCompress | realZlib.ZstdDecompress; +export type ZlibMode = 'Gzip' | 'Gunzip' | 'Deflate' | 'Inflate' | 'DeflateRaw' | 'InflateRaw' | 'Unzip'; +export type BrotliMode = 'BrotliCompress' | 'BrotliDecompress'; +export type ZstdMode = 'ZstdCompress' | 'ZstdDecompress'; +declare abstract class ZlibBase extends Minipass { + #private; + get sawError(): boolean; + get handle(): ZlibHandle | undefined; + get flushFlag(): number; + constructor(opts: ZlibBaseOptions, mode: ZlibMode | BrotliMode | ZstdMode); + close(): void; + reset(): any; + flush(flushFlag?: number): void; + end(cb?: () => void): this; + end(chunk: ChunkWithFlushFlag, cb?: () => void): this; + end(chunk: ChunkWithFlushFlag, encoding?: Minipass.Encoding, cb?: () => void): this; + get ended(): boolean; + [_superWrite](data: Buffer & { + [_flushFlag]?: number; + }): boolean; + write(chunk: ChunkWithFlushFlag, cb?: () => void): boolean; + write(chunk: ChunkWithFlushFlag, encoding?: Minipass.Encoding, cb?: () => void): boolean; +} +export type ZlibOptions = ZlibBaseOptions & { + level?: number; + strategy?: number; +}; +export declare class Zlib extends ZlibBase { + #private; + constructor(opts: ZlibOptions, mode: ZlibMode); + params(level: number, strategy: number): void; +} +export declare class Deflate extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class Inflate extends Zlib { + constructor(opts: ZlibOptions); +} +export type GzipOptions = ZlibOptions & { + portable?: boolean; +}; +export declare class Gzip extends Zlib { + #private; + constructor(opts: GzipOptions); + [_superWrite](data: Buffer & { + [_flushFlag]?: number; + }): boolean; +} +export declare class Gunzip extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class DeflateRaw extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class InflateRaw extends Zlib { + constructor(opts: ZlibOptions); +} +export declare class Unzip extends Zlib { + constructor(opts: ZlibOptions); +} +declare class Brotli extends ZlibBase { + constructor(opts: ZlibOptions, mode: BrotliMode); +} +export declare class BrotliCompress extends Brotli { + constructor(opts: ZlibOptions); +} +export declare class BrotliDecompress extends Brotli { + constructor(opts: ZlibOptions); +} +declare class Zstd extends ZlibBase { + constructor(opts: ZlibOptions, mode: ZstdMode); +} +export declare class ZstdCompress extends Zstd { + constructor(opts: ZlibOptions); +} +export declare class ZstdDecompress extends Zstd { + constructor(opts: ZlibOptions); +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/index.d.ts.map b/tools/ui/node_modules/minizlib/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..dcf6141b63036b9b86058a6d199a3edd408065dc --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,QAAQ,MAAM,MAAM,CAAA;AAEhC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAY1C,QAAA,MAAM,WAAW,eAAwB,CAAA;AAEzC,qBAAa,SAAU,SAAQ,KAAK;IAClC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;gBACF,GAAG,EAAE,MAAM,CAAC,cAAc,GAAG,KAAK,EAAE,MAAM,CAAC,EAAE,QAAQ;IAWjE,IAAI,IAAI,WAEP;CACF;AAMD,QAAA,MAAM,UAAU,eAAsB,CAAA;AAEtC,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC,cAAc,GAAG;IACzD,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC,GAAG;IACxE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,CAAA;AAED,MAAM,MAAM,UAAU,GAClB,QAAQ,CAAC,IAAI,GACb,QAAQ,CAAC,MAAM,GACf,QAAQ,CAAC,OAAO,GAChB,QAAQ,CAAC,OAAO,GAChB,QAAQ,CAAC,UAAU,GACnB,QAAQ,CAAC,UAAU,GACnB,QAAQ,CAAC,cAAc,GACvB,QAAQ,CAAC,gBAAgB,GACzB,QAAQ,CAAC,YAAY,GACrB,QAAQ,CAAC,cAAc,CAAA;AAC3B,MAAM,MAAM,QAAQ,GAChB,MAAM,GACN,QAAQ,GACR,SAAS,GACT,SAAS,GACT,YAAY,GACZ,YAAY,GACZ,OAAO,CAAA;AACX,MAAM,MAAM,UAAU,GAAG,gBAAgB,GAAG,kBAAkB,CAAA;AAC9D,MAAM,MAAM,QAAQ,GAAG,cAAc,GAAG,gBAAgB,CAAA;AAExD,uBAAe,QAAS,SAAQ,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;;IASlE,IAAI,QAAQ,YAEX;IACD,IAAI,MAAM,2BAET;IAED,IAAI,SAAS,WAEZ;gBAGW,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,QAAQ,GAAG,UAAU,GAAG,QAAQ;IA4CzE,KAAK;IAQL,KAAK;IAQL,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM;IAQxB,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI;IAC1B,GAAG,CAAC,KAAK,EAAE,kBAAkB,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,IAAI;IACrD,GAAG,CACD,KAAK,EAAE,kBAAkB,EACzB,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,EAC5B,EAAE,CAAC,EAAE,MAAM,IAAI,GACd,IAAI;IA0BP,IAAI,KAAK,YAER;IAGD,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG;QAAE,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,CAAA;KAAE;IAItD,KAAK,CAAC,KAAK,EAAE,kBAAkB,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO;IAC1D,KAAK,CACH,KAAK,EAAE,kBAAkB,EACzB,QAAQ,CAAC,EAAE,QAAQ,CAAC,QAAQ,EAC5B,EAAE,CAAC,EAAE,MAAM,IAAI,GACd,OAAO;CAqFX;AAED,MAAM,MAAM,WAAW,GAAG,eAAe,GAAG;IAC1C,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,qBAAa,IAAK,SAAQ,QAAQ;;gBAIpB,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ;IAY7C,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAiDvC;AAGD,qBAAa,OAAQ,SAAQ,IAAI;gBACnB,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,OAAQ,SAAQ,IAAI;gBACnB,IAAI,EAAE,WAAW;CAG9B;AAGD,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,CAAA;AAC9D,qBAAa,IAAK,SAAQ,IAAI;;gBAEhB,IAAI,EAAE,WAAW;IAK7B,CAAC,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG;QAAE,CAAC,UAAU,CAAC,CAAC,EAAE,MAAM,CAAA;KAAE;CASvD;AAED,qBAAa,MAAO,SAAQ,IAAI;gBAClB,IAAI,EAAE,WAAW;CAG9B;AAGD,qBAAa,UAAW,SAAQ,IAAI;gBACtB,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,UAAW,SAAQ,IAAI;gBACtB,IAAI,EAAE,WAAW;CAG9B;AAGD,qBAAa,KAAM,SAAQ,IAAI;gBACjB,IAAI,EAAE,WAAW;CAG9B;AAED,cAAM,MAAO,SAAQ,QAAQ;gBACf,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU;CAShD;AAED,qBAAa,cAAe,SAAQ,MAAM;gBAC5B,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,gBAAiB,SAAQ,MAAM;gBAC9B,IAAI,EAAE,WAAW;CAG9B;AAED,cAAM,IAAK,SAAQ,QAAQ;gBACb,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ;CAQ9C;AAED,qBAAa,YAAa,SAAQ,IAAI;gBACxB,IAAI,EAAE,WAAW;CAG9B;AAED,qBAAa,cAAe,SAAQ,IAAI;gBAC1B,IAAI,EAAE,WAAW;CAG9B"} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/index.js b/tools/ui/node_modules/minizlib/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b70ba1f2cd84f1e56054076bc5322063150e88d7 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/index.js @@ -0,0 +1,363 @@ +import assert from 'assert'; +import { Buffer } from 'buffer'; +import { Minipass } from 'minipass'; +import * as realZlib from 'zlib'; +import { constants } from './constants.js'; +export { constants } from './constants.js'; +const OriginalBufferConcat = Buffer.concat; +const desc = Object.getOwnPropertyDescriptor(Buffer, 'concat'); +const noop = (args) => args; +const passthroughBufferConcat = desc?.writable === true || desc?.set !== undefined + ? (makeNoOp) => { + Buffer.concat = makeNoOp ? noop : OriginalBufferConcat; + } + : (_) => { }; +const _superWrite = Symbol('_superWrite'); +export class ZlibError extends Error { + code; + errno; + constructor(err, origin) { + super('zlib: ' + err.message, { cause: err }); + this.code = err.code; + this.errno = err.errno; + /* c8 ignore next */ + if (!this.code) + this.code = 'ZLIB_ERROR'; + this.message = 'zlib: ' + err.message; + Error.captureStackTrace(this, origin ?? this.constructor); + } + get name() { + return 'ZlibError'; + } +} +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. +const _flushFlag = Symbol('flushFlag'); +class ZlibBase extends Minipass { + #sawError = false; + #ended = false; + #flushFlag; + #finishFlushFlag; + #fullFlushFlag; + #handle; + #onError; + get sawError() { + return this.#sawError; + } + get handle() { + return this.#handle; + } + /* c8 ignore start */ + get flushFlag() { + return this.#flushFlag; + } + /* c8 ignore stop */ + constructor(opts, mode) { + if (!opts || typeof opts !== 'object') + throw new TypeError('invalid options for ZlibBase constructor'); + //@ts-ignore + super(opts); + /* c8 ignore start */ + this.#flushFlag = opts.flush ?? 0; + this.#finishFlushFlag = opts.finishFlush ?? 0; + this.#fullFlushFlag = opts.fullFlushFlag ?? 0; + /* c8 ignore stop */ + //@ts-ignore + if (typeof realZlib[mode] !== 'function') { + throw new TypeError('Compression method not supported: ' + mode); + } + // this will throw if any options are invalid for the class selected + try { + // @types/node doesn't know that it exports the classes, but they're there + //@ts-ignore + this.#handle = new realZlib[mode](opts); + } + catch (er) { + // make sure that all errors get decorated properly + throw new ZlibError(er, this.constructor); + } + this.#onError = err => { + // no sense raising multiple errors, since we abort on the first one. + if (this.#sawError) + return; + this.#sawError = true; + // there is no way to cleanly recover. + // continuing only obscures problems. + this.close(); + this.emit('error', err); + }; + this.#handle?.on('error', er => this.#onError(new ZlibError(er))); + this.once('end', () => this.close); + } + close() { + if (this.#handle) { + this.#handle.close(); + this.#handle = undefined; + this.emit('close'); + } + } + reset() { + if (!this.#sawError) { + assert(this.#handle, 'zlib binding closed'); + //@ts-ignore + return this.#handle.reset?.(); + } + } + flush(flushFlag) { + if (this.ended) + return; + if (typeof flushFlag !== 'number') + flushFlag = this.#fullFlushFlag; + this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag })); + } + end(chunk, encoding, cb) { + /* c8 ignore start */ + if (typeof chunk === 'function') { + cb = chunk; + encoding = undefined; + chunk = undefined; + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = undefined; + } + /* c8 ignore stop */ + if (chunk) { + if (encoding) + this.write(chunk, encoding); + else + this.write(chunk); + } + this.flush(this.#finishFlushFlag); + this.#ended = true; + return super.end(cb); + } + get ended() { + return this.#ended; + } + // overridden in the gzip classes to do portable writes + [_superWrite](data) { + return super.write(data); + } + write(chunk, encoding, cb) { + // process the chunk using the sync process + // then super.write() all the outputted chunks + if (typeof encoding === 'function') + (cb = encoding), (encoding = 'utf8'); + if (typeof chunk === 'string') + chunk = Buffer.from(chunk, encoding); + if (this.#sawError) + return; + assert(this.#handle, 'zlib binding closed'); + // _processChunk tries to .close() the native handle after it's done, so we + // intercept that by temporarily making it a no-op. + // diving into the node:zlib internals a bit here + const nativeHandle = this.#handle + ._handle; + const originalNativeClose = nativeHandle.close; + nativeHandle.close = () => { }; + const originalClose = this.#handle.close; + this.#handle.close = () => { }; + // It also calls `Buffer.concat()` at the end, which may be convenient + // for some, but which we are not interested in as it slows us down. + passthroughBufferConcat(true); + let result = undefined; + try { + const flushFlag = typeof chunk[_flushFlag] === 'number' + ? chunk[_flushFlag] + : this.#flushFlag; + result = this.#handle._processChunk(chunk, flushFlag); + // if we don't throw, reset it back how it was + passthroughBufferConcat(false); + } + catch (err) { + // or if we do, put Buffer.concat() back before we emit error + // Error events call into user code, which may call Buffer.concat() + passthroughBufferConcat(false); + this.#onError(new ZlibError(err, this.write)); + } + finally { + if (this.#handle) { + // Core zlib resets `_handle` to null after attempting to close the + // native handle. Our no-op handler prevented actual closure, but we + // need to restore the `._handle` property. + ; + this.#handle._handle = + nativeHandle; + nativeHandle.close = originalNativeClose; + this.#handle.close = originalClose; + // `_processChunk()` adds an 'error' listener. If we don't remove it + // after each call, these handlers start piling up. + this.#handle.removeAllListeners('error'); + // make sure OUR error listener is still attached tho + } + } + if (this.#handle) + this.#handle.on('error', er => this.#onError(new ZlibError(er, this.write))); + let writeReturn; + if (result) { + if (Array.isArray(result) && result.length > 0) { + const r = result[0]; + // The first buffer is always `handle._outBuffer`, which would be + // re-used for later invocations; so, we always have to copy that one. + writeReturn = this[_superWrite](Buffer.from(r)); + for (let i = 1; i < result.length; i++) { + writeReturn = this[_superWrite](result[i]); + } + } + else { + // either a single Buffer or an empty array + writeReturn = this[_superWrite](Buffer.from(result)); + } + } + if (cb) + cb(); + return writeReturn; + } +} +export class Zlib extends ZlibBase { + #level; + #strategy; + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants.Z_NO_FLUSH; + opts.finishFlush = opts.finishFlush || constants.Z_FINISH; + opts.fullFlushFlag = constants.Z_FULL_FLUSH; + super(opts, mode); + this.#level = opts.level; + this.#strategy = opts.strategy; + } + params(level, strategy) { + if (this.sawError) + return; + if (!this.handle) + throw new Error('cannot switch params when binding is closed'); + // no way to test this without also not supporting params at all + /* c8 ignore start */ + if (!this.handle.params) + throw new Error('not supported in this implementation'); + /* c8 ignore stop */ + if (this.#level !== level || this.#strategy !== strategy) { + this.flush(constants.Z_SYNC_FLUSH); + assert(this.handle, 'zlib binding closed'); + // .params() calls .flush(), but the latter is always async in the + // core zlib. We override .flush() temporarily to intercept that and + // flush synchronously. + const origFlush = this.handle.flush; + this.handle.flush = (flushFlag, cb) => { + /* c8 ignore start */ + if (typeof flushFlag === 'function') { + cb = flushFlag; + flushFlag = this.flushFlag; + } + /* c8 ignore stop */ + this.flush(flushFlag); + cb?.(); + }; + try { + ; + this.handle.params(level, strategy); + } + finally { + this.handle.flush = origFlush; + } + /* c8 ignore start */ + if (this.handle) { + this.#level = level; + this.#strategy = strategy; + } + /* c8 ignore stop */ + } + } +} +// minimal 2-byte header +export class Deflate extends Zlib { + constructor(opts) { + super(opts, 'Deflate'); + } +} +export class Inflate extends Zlib { + constructor(opts) { + super(opts, 'Inflate'); + } +} +export class Gzip extends Zlib { + #portable; + constructor(opts) { + super(opts, 'Gzip'); + this.#portable = opts && !!opts.portable; + } + [_superWrite](data) { + if (!this.#portable) + return super[_superWrite](data); + // we'll always get the header emitted in one first chunk + // overwrite the OS indicator byte with 0xFF + this.#portable = false; + data[9] = 255; + return super[_superWrite](data); + } +} +export class Gunzip extends Zlib { + constructor(opts) { + super(opts, 'Gunzip'); + } +} +// raw - no header +export class DeflateRaw extends Zlib { + constructor(opts) { + super(opts, 'DeflateRaw'); + } +} +export class InflateRaw extends Zlib { + constructor(opts) { + super(opts, 'InflateRaw'); + } +} +// auto-detect header. +export class Unzip extends Zlib { + constructor(opts) { + super(opts, 'Unzip'); + } +} +class Brotli extends ZlibBase { + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS; + opts.finishFlush = + opts.finishFlush || constants.BROTLI_OPERATION_FINISH; + opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH; + super(opts, mode); + } +} +export class BrotliCompress extends Brotli { + constructor(opts) { + super(opts, 'BrotliCompress'); + } +} +export class BrotliDecompress extends Brotli { + constructor(opts) { + super(opts, 'BrotliDecompress'); + } +} +class Zstd extends ZlibBase { + constructor(opts, mode) { + opts = opts || {}; + opts.flush = opts.flush || constants.ZSTD_e_continue; + opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end; + opts.fullFlushFlag = constants.ZSTD_e_flush; + super(opts, mode); + } +} +export class ZstdCompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdCompress'); + } +} +export class ZstdDecompress extends Zstd { + constructor(opts) { + super(opts, 'ZstdDecompress'); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/index.js.map b/tools/ui/node_modules/minizlib/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..1cbc6502ff661a9516a50d5f9d55874bf6dba69a --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAC3B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,QAAQ,MAAM,MAAM,CAAA;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAE1C,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,CAAA;AAC1C,MAAM,IAAI,GAAG,MAAM,CAAC,wBAAwB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;AAC9D,MAAM,IAAI,GAAG,CAAC,IAAc,EAAE,EAAE,CAAC,IAAyB,CAAA;AAC1D,MAAM,uBAAuB,GAC3B,IAAI,EAAE,QAAQ,KAAK,IAAI,IAAI,IAAI,EAAE,GAAG,KAAK,SAAS;IAChD,CAAC,CAAC,CAAC,QAAiB,EAAE,EAAE;QACpB,MAAM,CAAC,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,oBAAoB,CAAA;IACxD,CAAC;IACH,CAAC,CAAC,CAAC,CAAU,EAAE,EAAE,GAAE,CAAC,CAAA;AAExB,MAAM,WAAW,GAAG,MAAM,CAAC,aAAa,CAAC,CAAA;AAEzC,MAAM,OAAO,SAAU,SAAQ,KAAK;IAClC,IAAI,CAAS;IACb,KAAK,CAAS;IACd,YAAY,GAAkC,EAAE,MAAiB;QAC/D,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;QAC7C,IAAI,CAAC,IAAI,GAAI,GAA6B,CAAC,IAAI,CAAA;QAC/C,IAAI,CAAC,KAAK,GAAI,GAA6B,CAAC,KAAK,CAAA;QACjD,oBAAoB;QACpB,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,IAAI,CAAC,IAAI,GAAG,YAAY,CAAA;QAExC,IAAI,CAAC,OAAO,GAAG,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAA;QACrC,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,WAAW,CAAC,CAAA;IAC3D,CAAC;IAED,IAAI,IAAI;QACN,OAAO,WAAW,CAAA;IACpB,CAAC;CACF;AAED,uCAAuC;AACvC,wDAAwD;AACxD,uDAAuD;AACvD,gCAAgC;AAChC,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAA;AAkCtC,MAAe,QAAS,SAAQ,QAAoC;IAClE,SAAS,GAAY,KAAK,CAAA;IAC1B,MAAM,GAAY,KAAK,CAAA;IACvB,UAAU,CAAQ;IAClB,gBAAgB,CAAQ;IACxB,cAAc,CAAQ;IACtB,OAAO,CAAa;IACpB,QAAQ,CAAyB;IAEjC,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;IACD,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IACD,qBAAqB;IACrB,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,UAAU,CAAA;IACxB,CAAC;IACD,oBAAoB;IAEpB,YAAY,IAAqB,EAAE,IAAsC;QACvE,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;YACnC,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAA;QAEjE,YAAY;QACZ,KAAK,CAAC,IAAI,CAAC,CAAA;QAEX,qBAAqB;QACrB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC,CAAA;QACjC,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,WAAW,IAAI,CAAC,CAAA;QAC7C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,aAAa,IAAI,CAAC,CAAA;QAC7C,oBAAoB;QAEpB,YAAY;QACZ,IAAI,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,UAAU,EAAE,CAAC;YACzC,MAAM,IAAI,SAAS,CAAC,oCAAoC,GAAG,IAAI,CAAC,CAAA;QAClE,CAAC;QAED,oEAAoE;QACpE,IAAI,CAAC;YACH,0EAA0E;YAC1E,YAAY;YACZ,IAAI,CAAC,OAAO,GAAG,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAA;QACzC,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,mDAAmD;YACnD,MAAM,IAAI,SAAS,CAAC,EAA2B,EAAE,IAAI,CAAC,WAAW,CAAC,CAAA;QACpE,CAAC;QAED,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,EAAE;YACpB,qEAAqE;YACrE,IAAI,IAAI,CAAC,SAAS;gBAAE,OAAM;YAE1B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;YAErB,sCAAsC;YACtC,qCAAqC;YACrC,IAAI,CAAC,KAAK,EAAE,CAAA;YACZ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;QACzB,CAAC,CAAA;QAED,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QACjE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IACpC,CAAC;IAED,KAAK;QACH,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAA;YACpB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAA;YACxB,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QACpB,CAAC;IACH,CAAC;IAED,KAAK;QACH,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAA;YAC3C,YAAY;YACZ,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAA;QAC/B,CAAC;IACH,CAAC;IAED,KAAK,CAAC,SAAkB;QACtB,IAAI,IAAI,CAAC,KAAK;YAAE,OAAM;QAEtB,IAAI,OAAO,SAAS,KAAK,QAAQ;YAAE,SAAS,GAAG,IAAI,CAAC,cAAc,CAAA;QAElE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAA;IACzE,CAAC;IASD,GAAG,CACD,KAAyC,EACzC,QAA2C,EAC3C,EAAe;QAEf,qBAAqB;QACrB,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;YAChC,EAAE,GAAG,KAAK,CAAA;YACV,QAAQ,GAAG,SAAS,CAAA;YACpB,KAAK,GAAG,SAAS,CAAA;QACnB,CAAC;QACD,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;YACnC,EAAE,GAAG,QAAQ,CAAA;YACb,QAAQ,GAAG,SAAS,CAAA;QACtB,CAAC;QACD,oBAAoB;QACpB,IAAI,KAAK,EAAE,CAAC;YACV,IAAI,QAAQ;gBAAE,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;;gBACpC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACxB,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QACjC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAA;QAClB,OAAO,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IACtB,CAAC;IAED,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,uDAAuD;IACvD,CAAC,WAAW,CAAC,CAAC,IAAwC;QACpD,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;IAC1B,CAAC;IAQD,KAAK,CACH,KAAyB,EACzB,QAA2C,EAC3C,EAAe;QAEf,2CAA2C;QAC3C,8CAA8C;QAC9C,IAAI,OAAO,QAAQ,KAAK,UAAU;YAChC,CAAC,EAAE,GAAG,QAAQ,CAAC,EAAE,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAA;QAEtC,IAAI,OAAO,KAAK,KAAK,QAAQ;YAC3B,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAe,EAAE,QAA0B,CAAC,CAAA;QAElE,IAAI,IAAI,CAAC,SAAS;YAAE,OAAM;QAC1B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAA;QAE3C,2EAA2E;QAC3E,mDAAmD;QACnD,iDAAiD;QACjD,MAAM,YAAY,GAAI,IAAI,CAAC,OAAuC;aAC/D,OAAO,CAAA;QACV,MAAM,mBAAmB,GAAG,YAAY,CAAC,KAAK,CAAA;QAC9C,YAAY,CAAC,KAAK,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;QAC7B,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAA;QACxC,IAAI,CAAC,OAAO,CAAC,KAAK,GAAG,GAAG,EAAE,GAAE,CAAC,CAAA;QAC7B,sEAAsE;QACtE,oEAAoE;QACpE,uBAAuB,CAAC,IAAI,CAAC,CAAA;QAC7B,IAAI,MAAM,GAAkC,SAAS,CAAA;QACrD,IAAI,CAAC;YACH,MAAM,SAAS,GACb,OAAO,KAAK,CAAC,UAAU,CAAC,KAAK,QAAQ;gBACnC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC;gBACnB,CAAC,CAAC,IAAI,CAAC,UAAU,CAAA;YACrB,MAAM,GACJ,IAAI,CAAC,OAGN,CAAC,aAAa,CAAC,KAAe,EAAE,SAAS,CAAC,CAAA;YAC3C,8CAA8C;YAC9C,uBAAuB,CAAC,KAAK,CAAC,CAAA;QAChC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,6DAA6D;YAC7D,mEAAmE;YACnE,uBAAuB,CAAC,KAAK,CAAC,CAAA;YAC9B,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,GAA4B,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAA;QACxE,CAAC;gBAAS,CAAC;YACT,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBACjB,mEAAmE;gBACnE,oEAAoE;gBACpE,2CAA2C;gBAC3C,CAAC;gBAAC,IAAI,CAAC,OAAuC,CAAC,OAAO;oBACpD,YAAY,CAAA;gBACd,YAAY,CAAC,KAAK,GAAG,mBAAmB,CAAA;gBACxC,IAAI,CAAC,OAAO,CAAC,KAAK,GAAG,aAAa,CAAA;gBAClC,oEAAoE;gBACpE,mDAAmD;gBACnD,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAA;gBACxC,qDAAqD;YACvD,CAAC;QACH,CAAC;QAED,IAAI,IAAI,CAAC,OAAO;YACd,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAE9E,IAAI,WAAW,CAAA;QACf,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC/C,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;gBACnB,iEAAiE;gBACjE,sEAAsE;gBACtE,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAW,CAAC,CAAC,CAAA;gBACzD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;oBACvC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,CAAW,CAAC,CAAA;gBACtD,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,2CAA2C;gBAC3C,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAqB,CAAC,CAAC,CAAA;YACrE,CAAC;QACH,CAAC;QAED,IAAI,EAAE;YAAE,EAAE,EAAE,CAAA;QACZ,OAAO,WAAW,CAAA;IACpB,CAAC;CACF;AAOD,MAAM,OAAO,IAAK,SAAQ,QAAQ;IAChC,MAAM,CAAS;IACf,SAAS,CAAS;IAElB,YAAY,IAAiB,EAAE,IAAc;QAC3C,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,SAAS,CAAC,UAAU,CAAA;QAC/C,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,SAAS,CAAC,QAAQ,CAAA;QACzD,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC,YAAY,CAAA;QAC3C,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;QAEjB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAA;QACxB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAA;IAChC,CAAC;IAED,MAAM,CAAC,KAAa,EAAE,QAAgB;QACpC,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAM;QAEzB,IAAI,CAAC,IAAI,CAAC,MAAM;YACd,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;QAEhE,gEAAgE;QAChE,qBAAqB;QACrB,IAAI,CAAE,IAAI,CAAC,MAA2B,CAAC,MAAM;YAC3C,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;QACzD,oBAAoB;QAEpB,IAAI,IAAI,CAAC,MAAM,KAAK,KAAK,IAAI,IAAI,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;YACzD,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,YAAY,CAAC,CAAA;YAClC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAA;YAC1C,kEAAkE;YAClE,oEAAoE;YACpE,uBAAuB;YACvB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAA;YACnC,IAAI,CAAC,MAAM,CAAC,KAAK,GAAG,CAClB,SAAiC,EACjC,EAAe,EACf,EAAE;gBACF,qBAAqB;gBACrB,IAAI,OAAO,SAAS,KAAK,UAAU,EAAE,CAAC;oBACpC,EAAE,GAAG,SAAS,CAAA;oBACd,SAAS,GAAG,IAAI,CAAC,SAAS,CAAA;gBAC5B,CAAC;gBACD,oBAAoB;gBACpB,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;gBACrB,EAAE,EAAE,EAAE,CAAA;YACR,CAAC,CAAA;YACD,IAAI,CAAC;gBACH,CAAC;gBACC,IAAI,CAAC,MAGN,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;YAC3B,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC,MAAM,CAAC,KAAK,GAAG,SAAS,CAAA;YAC/B,CAAC;YACD,qBAAqB;YACrB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;gBACnB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;YAC3B,CAAC;YACD,oBAAoB;QACtB,CAAC;IACH,CAAC;CACF;AAED,wBAAwB;AACxB,MAAM,OAAO,OAAQ,SAAQ,IAAI;IAC/B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACxB,CAAC;CACF;AAED,MAAM,OAAO,OAAQ,SAAQ,IAAI;IAC/B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAA;IACxB,CAAC;CACF;AAID,MAAM,OAAO,IAAK,SAAQ,IAAI;IAC5B,SAAS,CAAS;IAClB,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;QACnB,IAAI,CAAC,SAAS,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAA;IAC1C,CAAC;IAED,CAAC,WAAW,CAAC,CAAC,IAAwC;QACpD,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAA;QAEpD,yDAAyD;QACzD,4CAA4C;QAC5C,IAAI,CAAC,SAAS,GAAG,KAAK,CAAA;QACtB,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAA;QACb,OAAO,KAAK,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAA;IACjC,CAAC;CACF;AAED,MAAM,OAAO,MAAO,SAAQ,IAAI;IAC9B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAA;IACvB,CAAC;CACF;AAED,kBAAkB;AAClB,MAAM,OAAO,UAAW,SAAQ,IAAI;IAClC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;IAC3B,CAAC;CACF;AAED,MAAM,OAAO,UAAW,SAAQ,IAAI;IAClC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;IAC3B,CAAC;CACF;AAED,sBAAsB;AACtB,MAAM,OAAO,KAAM,SAAQ,IAAI;IAC7B,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IACtB,CAAC;CACF;AAED,MAAM,MAAO,SAAQ,QAAQ;IAC3B,YAAY,IAAiB,EAAE,IAAgB;QAC7C,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,SAAS,CAAC,wBAAwB,CAAA;QAC7D,IAAI,CAAC,WAAW;YACd,IAAI,CAAC,WAAW,IAAI,SAAS,CAAC,uBAAuB,CAAA;QACvD,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC,sBAAsB,CAAA;QACrD,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACnB,CAAC;CACF;AAED,MAAM,OAAO,cAAe,SAAQ,MAAM;IACxC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAA;IAC/B,CAAC;CACF;AAED,MAAM,OAAO,gBAAiB,SAAQ,MAAM;IAC1C,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,kBAAkB,CAAC,CAAA;IACjC,CAAC;CACF;AAED,MAAM,IAAK,SAAQ,QAAQ;IACzB,YAAY,IAAiB,EAAE,IAAc;QAC3C,IAAI,GAAG,IAAI,IAAI,EAAE,CAAA;QAEjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,SAAS,CAAC,eAAe,CAAA;QACpD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,SAAS,CAAC,UAAU,CAAA;QAC3D,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC,YAAY,CAAA;QAC3C,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IACnB,CAAC;CACF;AAED,MAAM,OAAO,YAAa,SAAQ,IAAI;IACpC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,cAAc,CAAC,CAAA;IAC7B,CAAC;CACF;AAED,MAAM,OAAO,cAAe,SAAQ,IAAI;IACtC,YAAY,IAAiB;QAC3B,KAAK,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAA;IAC/B,CAAC;CACF","sourcesContent":["import assert from 'assert'\nimport { Buffer } from 'buffer'\nimport { Minipass } from 'minipass'\nimport * as realZlib from 'zlib'\nimport { constants } from './constants.js'\nexport { constants } from './constants.js'\n\nconst OriginalBufferConcat = Buffer.concat\nconst desc = Object.getOwnPropertyDescriptor(Buffer, 'concat')\nconst noop = (args: Buffer[]) => args as unknown as Buffer\nconst passthroughBufferConcat =\n desc?.writable === true || desc?.set !== undefined\n ? (makeNoOp: boolean) => {\n Buffer.concat = makeNoOp ? noop : OriginalBufferConcat\n }\n : (_: boolean) => {}\n\nconst _superWrite = Symbol('_superWrite')\n\nexport class ZlibError extends Error {\n code?: string\n errno?: number\n constructor(err: NodeJS.ErrnoException | Error, origin?: Function) {\n super('zlib: ' + err.message, { cause: err })\n this.code = (err as NodeJS.ErrnoException).code\n this.errno = (err as NodeJS.ErrnoException).errno\n /* c8 ignore next */\n if (!this.code) this.code = 'ZLIB_ERROR'\n\n this.message = 'zlib: ' + err.message\n Error.captureStackTrace(this, origin ?? this.constructor)\n }\n\n get name() {\n return 'ZlibError'\n }\n}\n\n// the Zlib class they all inherit from\n// This thing manages the queue of requests, and returns\n// true or false if there is anything in the queue when\n// you call the .write() method.\nconst _flushFlag = Symbol('flushFlag')\n\nexport type ChunkWithFlushFlag = Minipass.ContiguousData & {\n [_flushFlag]?: number\n}\n\nexport type ZlibBaseOptions = Minipass.Options & {\n flush?: number\n finishFlush?: number\n fullFlushFlag?: number\n}\n\nexport type ZlibHandle =\n | realZlib.Gzip\n | realZlib.Gunzip\n | realZlib.Deflate\n | realZlib.Inflate\n | realZlib.DeflateRaw\n | realZlib.InflateRaw\n | realZlib.BrotliCompress\n | realZlib.BrotliDecompress\n | realZlib.ZstdCompress\n | realZlib.ZstdDecompress\nexport type ZlibMode =\n | 'Gzip'\n | 'Gunzip'\n | 'Deflate'\n | 'Inflate'\n | 'DeflateRaw'\n | 'InflateRaw'\n | 'Unzip'\nexport type BrotliMode = 'BrotliCompress' | 'BrotliDecompress'\nexport type ZstdMode = 'ZstdCompress' | 'ZstdDecompress'\n\nabstract class ZlibBase extends Minipass {\n #sawError: boolean = false\n #ended: boolean = false\n #flushFlag: number\n #finishFlushFlag: number\n #fullFlushFlag: number\n #handle?: ZlibHandle\n #onError: (err: ZlibError) => any\n\n get sawError() {\n return this.#sawError\n }\n get handle() {\n return this.#handle\n }\n /* c8 ignore start */\n get flushFlag() {\n return this.#flushFlag\n }\n /* c8 ignore stop */\n\n constructor(opts: ZlibBaseOptions, mode: ZlibMode | BrotliMode | ZstdMode) {\n if (!opts || typeof opts !== 'object')\n throw new TypeError('invalid options for ZlibBase constructor')\n\n //@ts-ignore\n super(opts)\n\n /* c8 ignore start */\n this.#flushFlag = opts.flush ?? 0\n this.#finishFlushFlag = opts.finishFlush ?? 0\n this.#fullFlushFlag = opts.fullFlushFlag ?? 0\n /* c8 ignore stop */\n\n //@ts-ignore\n if (typeof realZlib[mode] !== 'function') {\n throw new TypeError('Compression method not supported: ' + mode)\n }\n\n // this will throw if any options are invalid for the class selected\n try {\n // @types/node doesn't know that it exports the classes, but they're there\n //@ts-ignore\n this.#handle = new realZlib[mode](opts)\n } catch (er) {\n // make sure that all errors get decorated properly\n throw new ZlibError(er as NodeJS.ErrnoException, this.constructor)\n }\n\n this.#onError = err => {\n // no sense raising multiple errors, since we abort on the first one.\n if (this.#sawError) return\n\n this.#sawError = true\n\n // there is no way to cleanly recover.\n // continuing only obscures problems.\n this.close()\n this.emit('error', err)\n }\n\n this.#handle?.on('error', er => this.#onError(new ZlibError(er)))\n this.once('end', () => this.close)\n }\n\n close() {\n if (this.#handle) {\n this.#handle.close()\n this.#handle = undefined\n this.emit('close')\n }\n }\n\n reset() {\n if (!this.#sawError) {\n assert(this.#handle, 'zlib binding closed')\n //@ts-ignore\n return this.#handle.reset?.()\n }\n }\n\n flush(flushFlag?: number) {\n if (this.ended) return\n\n if (typeof flushFlag !== 'number') flushFlag = this.#fullFlushFlag\n\n this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }))\n }\n\n end(cb?: () => void): this\n end(chunk: ChunkWithFlushFlag, cb?: () => void): this\n end(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): this\n end(\n chunk?: ChunkWithFlushFlag | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n /* c8 ignore start */\n if (typeof chunk === 'function') {\n cb = chunk\n encoding = undefined\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = undefined\n }\n /* c8 ignore stop */\n if (chunk) {\n if (encoding) this.write(chunk, encoding)\n else this.write(chunk)\n }\n this.flush(this.#finishFlushFlag)\n this.#ended = true\n return super.end(cb)\n }\n\n get ended() {\n return this.#ended\n }\n\n // overridden in the gzip classes to do portable writes\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n return super.write(data)\n }\n\n write(chunk: ChunkWithFlushFlag, cb?: () => void): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding,\n cb?: () => void,\n ): boolean\n write(\n chunk: ChunkWithFlushFlag,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void,\n ) {\n // process the chunk using the sync process\n // then super.write() all the outputted chunks\n if (typeof encoding === 'function')\n (cb = encoding), (encoding = 'utf8')\n\n if (typeof chunk === 'string')\n chunk = Buffer.from(chunk as string, encoding as BufferEncoding)\n\n if (this.#sawError) return\n assert(this.#handle, 'zlib binding closed')\n\n // _processChunk tries to .close() the native handle after it's done, so we\n // intercept that by temporarily making it a no-op.\n // diving into the node:zlib internals a bit here\n const nativeHandle = (this.#handle as unknown as { _handle: any })\n ._handle\n const originalNativeClose = nativeHandle.close\n nativeHandle.close = () => {}\n const originalClose = this.#handle.close\n this.#handle.close = () => {}\n // It also calls `Buffer.concat()` at the end, which may be convenient\n // for some, but which we are not interested in as it slows us down.\n passthroughBufferConcat(true)\n let result: undefined | Buffer | Buffer[] = undefined\n try {\n const flushFlag =\n typeof chunk[_flushFlag] === 'number'\n ? chunk[_flushFlag]\n : this.#flushFlag\n result = (\n this.#handle as unknown as {\n _processChunk: (chunk: Buffer, flushFlag: number) => Buffer[]\n }\n )._processChunk(chunk as Buffer, flushFlag)\n // if we don't throw, reset it back how it was\n passthroughBufferConcat(false)\n } catch (err) {\n // or if we do, put Buffer.concat() back before we emit error\n // Error events call into user code, which may call Buffer.concat()\n passthroughBufferConcat(false)\n this.#onError(new ZlibError(err as NodeJS.ErrnoException, this.write))\n } finally {\n if (this.#handle) {\n // Core zlib resets `_handle` to null after attempting to close the\n // native handle. Our no-op handler prevented actual closure, but we\n // need to restore the `._handle` property.\n ;(this.#handle as unknown as { _handle: any })._handle =\n nativeHandle\n nativeHandle.close = originalNativeClose\n this.#handle.close = originalClose\n // `_processChunk()` adds an 'error' listener. If we don't remove it\n // after each call, these handlers start piling up.\n this.#handle.removeAllListeners('error')\n // make sure OUR error listener is still attached tho\n }\n }\n\n if (this.#handle)\n this.#handle.on('error', er => this.#onError(new ZlibError(er, this.write)))\n\n let writeReturn\n if (result) {\n if (Array.isArray(result) && result.length > 0) {\n const r = result[0]\n // The first buffer is always `handle._outBuffer`, which would be\n // re-used for later invocations; so, we always have to copy that one.\n writeReturn = this[_superWrite](Buffer.from(r as Buffer))\n for (let i = 1; i < result.length; i++) {\n writeReturn = this[_superWrite](result[i] as Buffer)\n }\n } else {\n // either a single Buffer or an empty array\n writeReturn = this[_superWrite](Buffer.from(result as Buffer | []))\n }\n }\n\n if (cb) cb()\n return writeReturn\n }\n}\n\nexport type ZlibOptions = ZlibBaseOptions & {\n level?: number\n strategy?: number\n}\n\nexport class Zlib extends ZlibBase {\n #level?: number\n #strategy?: number\n\n constructor(opts: ZlibOptions, mode: ZlibMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.Z_NO_FLUSH\n opts.finishFlush = opts.finishFlush || constants.Z_FINISH\n opts.fullFlushFlag = constants.Z_FULL_FLUSH\n super(opts, mode)\n\n this.#level = opts.level\n this.#strategy = opts.strategy\n }\n\n params(level: number, strategy: number) {\n if (this.sawError) return\n\n if (!this.handle)\n throw new Error('cannot switch params when binding is closed')\n\n // no way to test this without also not supporting params at all\n /* c8 ignore start */\n if (!(this.handle as { params?: any }).params)\n throw new Error('not supported in this implementation')\n /* c8 ignore stop */\n\n if (this.#level !== level || this.#strategy !== strategy) {\n this.flush(constants.Z_SYNC_FLUSH)\n assert(this.handle, 'zlib binding closed')\n // .params() calls .flush(), but the latter is always async in the\n // core zlib. We override .flush() temporarily to intercept that and\n // flush synchronously.\n const origFlush = this.handle.flush\n this.handle.flush = (\n flushFlag?: (() => void) | number,\n cb?: () => void,\n ) => {\n /* c8 ignore start */\n if (typeof flushFlag === 'function') {\n cb = flushFlag\n flushFlag = this.flushFlag\n }\n /* c8 ignore stop */\n this.flush(flushFlag)\n cb?.()\n }\n try {\n ;(\n this.handle as unknown as {\n params: (level?: number, strategy?: number) => void\n }\n ).params(level, strategy)\n } finally {\n this.handle.flush = origFlush\n }\n /* c8 ignore start */\n if (this.handle) {\n this.#level = level\n this.#strategy = strategy\n }\n /* c8 ignore stop */\n }\n }\n}\n\n// minimal 2-byte header\nexport class Deflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Deflate')\n }\n}\n\nexport class Inflate extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Inflate')\n }\n}\n\n// gzip - bigger header, same deflate compression\nexport type GzipOptions = ZlibOptions & { portable?: boolean }\nexport class Gzip extends Zlib {\n #portable: boolean\n constructor(opts: GzipOptions) {\n super(opts, 'Gzip')\n this.#portable = opts && !!opts.portable\n }\n\n [_superWrite](data: Buffer & { [_flushFlag]?: number }) {\n if (!this.#portable) return super[_superWrite](data)\n\n // we'll always get the header emitted in one first chunk\n // overwrite the OS indicator byte with 0xFF\n this.#portable = false\n data[9] = 255\n return super[_superWrite](data)\n }\n}\n\nexport class Gunzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Gunzip')\n }\n}\n\n// raw - no header\nexport class DeflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'DeflateRaw')\n }\n}\n\nexport class InflateRaw extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'InflateRaw')\n }\n}\n\n// auto-detect header.\nexport class Unzip extends Zlib {\n constructor(opts: ZlibOptions) {\n super(opts, 'Unzip')\n }\n}\n\nclass Brotli extends ZlibBase {\n constructor(opts: ZlibOptions, mode: BrotliMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS\n opts.finishFlush =\n opts.finishFlush || constants.BROTLI_OPERATION_FINISH\n opts.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH\n super(opts, mode)\n }\n}\n\nexport class BrotliCompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliCompress')\n }\n}\n\nexport class BrotliDecompress extends Brotli {\n constructor(opts: ZlibOptions) {\n super(opts, 'BrotliDecompress')\n }\n}\n\nclass Zstd extends ZlibBase {\n constructor(opts: ZlibOptions, mode: ZstdMode) {\n opts = opts || {}\n\n opts.flush = opts.flush || constants.ZSTD_e_continue\n opts.finishFlush = opts.finishFlush || constants.ZSTD_e_end\n opts.fullFlushFlag = constants.ZSTD_e_flush\n super(opts, mode)\n }\n}\n\nexport class ZstdCompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdCompress')\n }\n}\n\nexport class ZstdDecompress extends Zstd {\n constructor(opts: ZlibOptions) {\n super(opts, 'ZstdDecompress')\n }\n}\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/minizlib/dist/esm/package.json b/tools/ui/node_modules/minizlib/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/tools/ui/node_modules/minizlib/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/tools/ui/node_modules/minizlib/package.json b/tools/ui/node_modules/minizlib/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dceaed923d3db84e000310324c6db21583a26959 --- /dev/null +++ b/tools/ui/node_modules/minizlib/package.json @@ -0,0 +1,80 @@ +{ + "name": "minizlib", + "version": "3.1.0", + "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.", + "main": "./dist/commonjs/index.js", + "dependencies": { + "minipass": "^7.1.2" + }, + "scripts": { + "prepare": "tshy", + "pretest": "npm run prepare", + "test": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/minizlib.git" + }, + "keywords": [ + "zlib", + "gzip", + "gunzip", + "deflate", + "inflate", + "compression", + "zip", + "unzip" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "MIT", + "devDependencies": { + "@types/node": "^24.5.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.1" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">= 18" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "types": "./dist/commonjs/index.d.ts", + "type": "module", + "prettier": { + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "module": "./dist/esm/index.js" +} diff --git a/tools/ui/node_modules/mode-watcher/LICENSE b/tools/ui/node_modules/mode-watcher/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8a60e9698b2015e8c1862fdb9c5dbe42482b1daa --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024 Hunter Johnston +Copyright (c) 2024 Svecosystem + +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. diff --git a/tools/ui/node_modules/mode-watcher/README.md b/tools/ui/node_modules/mode-watcher/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3481e0757d676276b5d70150891e0b933e60be5f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/README.md @@ -0,0 +1,162 @@ +# Mode Watcher + +Simple utilities to manage light & dark mode in your SvelteKit app. + + + +[![npm version](https://flat.badgen.net/npm/v/mode-watcher?color=yellow)](https://npmjs.com/package/mode-watcher) +[![npm downloads](https://flat.badgen.net/npm/dm/mode-watcher?color=yellow)](https://npmjs.com/package/mode-watcher) +[![license](https://flat.badgen.net/github/license/svecosystem/mode-watcher?color=yellow)](https://github.com/svecosystem/mode-watcher/blob/main/LICENSE) + + + +[![](https://dcbadge.vercel.app/api/server/fdXy3Sk8Gq?style=flat)](https://discord.gg/fdXy3Sk8Gq) + +## Installation + +```bash +npm install mode-watcher +``` + +## Usage + +Add the `ModeWatcher` component to your root `+layout.svelte` file. + +```svelte + + + +{@render children()} +``` + +The `ModeWatcher` component will automatically detect the user's preferences and apply/remove the `"dark"` class, along with the corresponding `color-scheme` style attribute to the `html` element. + +`ModeWatcher` will automatically track operating system preferences and apply these if no user preference is set. If you wish to disable this behavior, set the `track` prop to `false`: + +```svelte + +``` + +`ModeWatcher` can also be configured with a default mode instead of automatically detecting the user's preference. + +To set a default mode, use the `defaultMode` prop: + +```svelte + +``` + +`ModeWatcher` can manage the `theme-color` meta tag for you. + +To enable this, set the `themeColors` prop to your preferred colors: + +```svelte + +``` + +## API + +### toggleMode + +A function that toggles the current mode. + +```svelte + + + +``` + +### setMode + +A function that sets the current mode. It accepts a string with the value `"light"`, `"dark"` or `"system"`. + +```svelte + + + + +``` + +### resetMode + +A function that resets the mode to system preferences. + +```svelte + + + +``` + +### mode + +A readable store that contains the current mode. It can be `"light"` or `"dark"` or `undefined` if evaluated on the server. + +```svelte + + + +``` + +### userPrefersMode + +A writeable store that represents the user's mode preference. It can be `"light"`, `"dark"` or `"system"`. + +### systemPrefersMode + +A readable store that represents the operating system's mode preference. It can be `"light"`, `"dark"` or `undefined` if evaluated on the server. Will automatically track changes to the operating system's mode preference unless this is disabled with the `tracking()` method which takes a boolean. Normally this is disabled by setting the `track` prop to false in the `` component. + +## Demo / Reproduction Template + +[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/svecosystem/mode-watcher-reproduction) + +## Sponsors + +This project is supported by the following beautiful people/organizations: + +

+ + Logos from Sponsors + +

+ +## License + + + +Published under the [MIT](https://github.com/svecosystem/mode-watcher/blob/main/LICENSE) license. +Made by [@huntabyte](https://github.com/huntabyte), [@ollema](https://github.com/ollema), and [community](https://github.com/svecosystem/mode-watcher/graphs/contributors) 💛 +

+ + + + + + +## Community + +Join the Discord server to ask questions, find collaborators, or just say hi! + + + + + Svecosystem Discord community + + diff --git a/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-full.svelte b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-full.svelte new file mode 100644 index 0000000000000000000000000000000000000000..fa7c24cb2ab9aa2d3df3c9b23037cb53c7bad510 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-full.svelte @@ -0,0 +1,29 @@ + + + + {#if themeColors} + + + + + {/if} + + {@html `(` + + setInitialMode.toString() + + `)(` + + JSON.stringify(initConfig) + + `);`} + diff --git a/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-full.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-full.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..471e83dd093b0267af9027b33271f547365a2725 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-full.svelte.d.ts @@ -0,0 +1,10 @@ +import { setInitialMode } from "../mode.js"; +import type { ThemeColors } from "../types.js"; +type $$ComponentProps = { + trueNonce: string; + initConfig: Parameters[0]; + themeColors: ThemeColors; +}; +declare const ModeWatcherFull: import("svelte").Component<$$ComponentProps, {}, "">; +type ModeWatcherFull = ReturnType; +export default ModeWatcherFull; diff --git a/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-lite.svelte b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-lite.svelte new file mode 100644 index 0000000000000000000000000000000000000000..3f7a6b0f151caf8d64c8c605eddd8a2ce71bf3da --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-lite.svelte @@ -0,0 +1,12 @@ + + +{#if themeColors} + + + + +{/if} diff --git a/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-lite.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-lite.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcb53bb8827e81acb0dcbf70b625938bccf8162f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher-lite.svelte.d.ts @@ -0,0 +1,7 @@ +import type { ThemeColors } from "../types.js"; +type $$ComponentProps = { + themeColors: ThemeColors; +}; +declare const ModeWatcherLite: import("svelte").Component<$$ComponentProps, {}, "">; +type ModeWatcherLite = ReturnType; +export default ModeWatcherLite; diff --git a/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher.svelte b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher.svelte new file mode 100644 index 0000000000000000000000000000000000000000..9c48b5c1dd59e2c1cc4439cf56eaba3456cb05a7 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher.svelte @@ -0,0 +1,104 @@ + + +{#if disableHeadScriptInjection} + +{:else} + +{/if} diff --git a/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..337744684382456c90fbb75c74289466d9d5ac7d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/mode-watcher.svelte.d.ts @@ -0,0 +1,4 @@ +import type { ModeWatcherProps } from "../types.js"; +declare const ModeWatcher: import("svelte").Component; +type ModeWatcher = ReturnType; +export default ModeWatcher; diff --git a/tools/ui/node_modules/mode-watcher/dist/components/types.d.ts b/tools/ui/node_modules/mode-watcher/dist/components/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/types.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/mode-watcher/dist/components/types.js b/tools/ui/node_modules/mode-watcher/dist/components/types.js new file mode 100644 index 0000000000000000000000000000000000000000..3918c74e446336be4151ea3bdad00f4d9e6df47a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/components/types.js @@ -0,0 +1 @@ +"use strict"; diff --git a/tools/ui/node_modules/mode-watcher/dist/index.d.ts b/tools/ui/node_modules/mode-watcher/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..468c05f8fb7d3f63697bc732e5bf3db03bfc07e0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/index.d.ts @@ -0,0 +1,7 @@ +import { generateSetInitialModeExpression, createInitialModeExpression, resetMode, setMode, setTheme, toggleMode } from "./mode.js"; +import { modeStorageKey, themeStorageKey } from "./storage-keys.svelte.js"; +import { mode, theme } from "./states.svelte.js"; +import { userPrefersMode, systemPrefersMode } from "./mode-states.svelte.js"; +export { generateSetInitialModeExpression, createInitialModeExpression, setMode, toggleMode, resetMode, modeStorageKey, userPrefersMode, systemPrefersMode, mode, theme, setTheme, themeStorageKey, }; +export type { SystemModeValue, UserPrefersMode, SystemPrefersMode } from "./mode-states.svelte.js"; +export { default as ModeWatcher } from "./components/mode-watcher.svelte"; diff --git a/tools/ui/node_modules/mode-watcher/dist/index.js b/tools/ui/node_modules/mode-watcher/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b3ef9e01670243f227794feaa8be17896f8c1990 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/index.js @@ -0,0 +1,6 @@ +import { generateSetInitialModeExpression, createInitialModeExpression, resetMode, setMode, setTheme, toggleMode, } from "./mode.js"; +import { modeStorageKey, themeStorageKey } from "./storage-keys.svelte.js"; +import { mode, theme } from "./states.svelte.js"; +import { userPrefersMode, systemPrefersMode } from "./mode-states.svelte.js"; +export { generateSetInitialModeExpression, createInitialModeExpression, setMode, toggleMode, resetMode, modeStorageKey, userPrefersMode, systemPrefersMode, mode, theme, setTheme, themeStorageKey, }; +export { default as ModeWatcher } from "./components/mode-watcher.svelte"; diff --git a/tools/ui/node_modules/mode-watcher/dist/mode-states.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/mode-states.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b16d6132f1216732db3188fc8dc6e542113402b3 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/mode-states.svelte.d.ts @@ -0,0 +1,24 @@ +import type { Mode } from "./types.js"; +export declare class UserPrefersMode { + #private; + constructor(); + get current(): Mode; + set current(newValue: Mode); +} +export type SystemModeValue = "light" | "dark" | undefined; +export declare class SystemPrefersMode { + #private; + query(): void; + tracking(active: boolean): void; + constructor(); + get current(): SystemModeValue; +} +/** + * Writable state that represents the user's preferred mode + * (`"dark"`, `"light"` or `"system"`) + */ +export declare const userPrefersMode: UserPrefersMode; +/** + * Readable store that represents the system's preferred mode (`"dark"`, `"light"` or `undefined`) + */ +export declare const systemPrefersMode: SystemPrefersMode; diff --git a/tools/ui/node_modules/mode-watcher/dist/mode-states.svelte.js b/tools/ui/node_modules/mode-watcher/dist/mode-states.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..79743820f143371f0bf946b318c33a6f28bf4082 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/mode-states.svelte.js @@ -0,0 +1,80 @@ +import { PersistedState, watch } from "runed"; +import { isBrowser, noopStorage } from "./utils.js"; +import { modeStorageKey } from "./storage-keys.svelte.js"; +import { isValidMode } from "./modes.js"; +import { MediaQuery } from "svelte/reactivity"; +export class UserPrefersMode { + #defaultValue = "system"; + #storage = isBrowser ? localStorage : noopStorage; + #initialValue = this.#storage.getItem(modeStorageKey.current); + #value = isValidMode(this.#initialValue) ? this.#initialValue : this.#defaultValue; + #persisted = $state(this.#makePersisted()); + #makePersisted(value = this.#value) { + return new PersistedState(modeStorageKey.current, value, { + serializer: { + serialize: (v) => v, + deserialize: (v) => { + if (isValidMode(v)) + return v; + return this.#defaultValue; + }, + }, + }); + } + constructor() { + $effect.root(() => { + return watch.pre(() => modeStorageKey.current, (_, prevStorageKey) => { + const currModeValue = this.#persisted.current; + this.#persisted = this.#makePersisted(currModeValue); + if (prevStorageKey) { + localStorage.removeItem(prevStorageKey); + } + }); + }); + } + get current() { + return this.#persisted.current; + } + set current(newValue) { + this.#persisted.current = newValue; + } +} +export class SystemPrefersMode { + #defaultValue = undefined; + #track = true; + #current = $state(this.#defaultValue); + #mediaQueryState = typeof window !== "undefined" && typeof window.matchMedia === "function" + ? new MediaQuery("prefers-color-scheme: light") + : { current: false }; + query() { + if (!isBrowser) + return; + this.#current = this.#mediaQueryState.current ? "light" : "dark"; + } + tracking(active) { + this.#track = active; + } + constructor() { + $effect.root(() => { + $effect.pre(() => { + if (!this.#track) + return; + this.query(); + }); + }); + this.query = this.query.bind(this); + this.tracking = this.tracking.bind(this); + } + get current() { + return this.#current; + } +} +/** + * Writable state that represents the user's preferred mode + * (`"dark"`, `"light"` or `"system"`) + */ +export const userPrefersMode = new UserPrefersMode(); +/** + * Readable store that represents the system's preferred mode (`"dark"`, `"light"` or `undefined`) + */ +export const systemPrefersMode = new SystemPrefersMode(); diff --git a/tools/ui/node_modules/mode-watcher/dist/mode.d.ts b/tools/ui/node_modules/mode-watcher/dist/mode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a94826cff1b6c1fea9bc1fbc7e4c1d49bd6d8788 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/mode.d.ts @@ -0,0 +1,32 @@ +import type { Mode, ThemeColors } from "./types.js"; +/** Toggle between light and dark mode */ +export declare function toggleMode(): void; +/** Set the mode to light or dark */ +export declare function setMode(mode: Mode): void; +/** Reset the mode to operating system preference */ +export declare function resetMode(): void; +/** Set the theme to a custom value */ +export declare function setTheme(newTheme: string): void; +export declare function defineConfig(config: SetInitialModeArgs): SetInitialModeArgs; +type SetInitialModeArgs = { + defaultMode?: Mode; + themeColors?: ThemeColors; + darkClassNames?: string[]; + lightClassNames?: string[]; + defaultTheme?: string; + modeStorageKey?: string; + themeStorageKey?: string; +}; +/** Used to set the mode on initial page load to prevent FOUC */ +export declare function setInitialMode({ defaultMode, themeColors, darkClassNames, lightClassNames, defaultTheme, modeStorageKey, themeStorageKey, }: SetInitialModeArgs): void; +/** + * A type-safe way to generate the source expression used to set the initial mode and avoid FOUC. + */ +export declare function createInitialModeExpression(config?: SetInitialModeArgs): string; +/** + * A type-safe way to generate the source expression used to set the initial mode and avoid FOUC. + * + * @deprecated Use `createInitialModeExpression` instead. + */ +export declare const generateSetInitialModeExpression: typeof createInitialModeExpression; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/dist/mode.js b/tools/ui/node_modules/mode-watcher/dist/mode.js new file mode 100644 index 0000000000000000000000000000000000000000..d93639eab192160332101d074b4cbc1f10af4407 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/mode.js @@ -0,0 +1,66 @@ +import { userPrefersMode } from "./mode-states.svelte.js"; +import { customTheme } from "./theme-state.svelte.js"; +import { derivedMode } from "./states.svelte.js"; +/** Toggle between light and dark mode */ +export function toggleMode() { + userPrefersMode.current = derivedMode.current === "dark" ? "light" : "dark"; +} +/** Set the mode to light or dark */ +export function setMode(mode) { + userPrefersMode.current = mode; +} +/** Reset the mode to operating system preference */ +export function resetMode() { + userPrefersMode.current = "system"; +} +/** Set the theme to a custom value */ +export function setTheme(newTheme) { + customTheme.current = newTheme; +} +export function defineConfig(config) { + return config; +} +/** Used to set the mode on initial page load to prevent FOUC */ +export function setInitialMode({ defaultMode = "system", themeColors, darkClassNames = ["dark"], lightClassNames = [], defaultTheme = "", modeStorageKey = "mode-watcher-mode", themeStorageKey = "mode-watcher-theme", }) { + const rootEl = document.documentElement; + const mode = localStorage.getItem(modeStorageKey) ?? defaultMode; + const theme = localStorage.getItem(themeStorageKey) ?? defaultTheme; + const light = mode === "light" || + (mode === "system" && window.matchMedia("(prefers-color-scheme: light)").matches); + if (light) { + if (darkClassNames.length) + rootEl.classList.remove(...darkClassNames.filter(Boolean)); + if (lightClassNames.length) + rootEl.classList.add(...lightClassNames.filter(Boolean)); + } + else { + if (lightClassNames.length) + rootEl.classList.remove(...lightClassNames.filter(Boolean)); + if (darkClassNames.length) + rootEl.classList.add(...darkClassNames.filter(Boolean)); + } + rootEl.style.colorScheme = light ? "light" : "dark"; + if (themeColors) { + const themeMetaEl = document.querySelector('meta[name="theme-color"]'); + if (themeMetaEl) { + themeMetaEl.setAttribute("content", mode === "light" ? themeColors.light : themeColors.dark); + } + } + if (theme) { + rootEl.setAttribute("data-theme", theme); + localStorage.setItem(themeStorageKey, theme); + } + localStorage.setItem(modeStorageKey, mode); +} +/** + * A type-safe way to generate the source expression used to set the initial mode and avoid FOUC. + */ +export function createInitialModeExpression(config = {}) { + return `(${setInitialMode.toString()})(${JSON.stringify(config)});`; +} +/** + * A type-safe way to generate the source expression used to set the initial mode and avoid FOUC. + * + * @deprecated Use `createInitialModeExpression` instead. + */ +export const generateSetInitialModeExpression = createInitialModeExpression; diff --git a/tools/ui/node_modules/mode-watcher/dist/modes.d.ts b/tools/ui/node_modules/mode-watcher/dist/modes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67dfd36c004de270307881f0a8b740cd290d3172 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/modes.d.ts @@ -0,0 +1,7 @@ +import type { Mode } from "./types.js"; +/** + * the modes that are supported, used for validation & type + * derivation + */ +export declare const modes: readonly ["dark", "light", "system"]; +export declare function isValidMode(value: unknown): value is Mode; diff --git a/tools/ui/node_modules/mode-watcher/dist/modes.js b/tools/ui/node_modules/mode-watcher/dist/modes.js new file mode 100644 index 0000000000000000000000000000000000000000..5e64f51e39a3dbd88098c38ad61c454d48283ed9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/modes.js @@ -0,0 +1,10 @@ +/** + * the modes that are supported, used for validation & type + * derivation + */ +export const modes = ["dark", "light", "system"]; +export function isValidMode(value) { + if (typeof value !== "string") + return false; + return modes.includes(value); +} diff --git a/tools/ui/node_modules/mode-watcher/dist/states.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/states.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76fbb20d3cea046856adc5160e039cf976d8aa87 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/states.svelte.d.ts @@ -0,0 +1,36 @@ +import type { ThemeColors } from "./types.js"; +/** + * Theme colors for light and dark modes. + */ +export declare const themeColors: import("svelte-toolbelt").WritableBox; +/** + * Whether to disable transitions when changing the mode. + */ +export declare const disableTransitions: import("svelte-toolbelt").WritableBox; +/** + * Whether to run the mode changes synchronously instead of using + * an animation frame. If true, will have an impact on blocking performance + * due to blocking the main thread. + */ +export declare const synchronousModeChanges: import("svelte-toolbelt").WritableBox; +/** + * The classnames to add to the root `html` element when the mode is dark. + */ +export declare const darkClassNames: import("svelte-toolbelt").WritableBox; +/** + * The classnames to add to the root `html` element when the mode is light. + */ +export declare const lightClassNames: import("svelte-toolbelt").WritableBox; +/** + * Derived store that represents the current mode (`"dark"`, `"light"` or `undefined`) + */ +export declare const derivedMode: { + readonly current: import("./mode-states.svelte.js").SystemModeValue; +}; +/** + * Derived store that represents the current custom theme + */ +export declare const derivedTheme: { + readonly current: string | undefined; +}; +export { derivedMode as mode, derivedTheme as theme }; diff --git a/tools/ui/node_modules/mode-watcher/dist/states.svelte.js b/tools/ui/node_modules/mode-watcher/dist/states.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..2f415cfa8b3ca212bb3891d765fcdba0fc8b75f4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/states.svelte.js @@ -0,0 +1,107 @@ +import { box } from "svelte-toolbelt"; +import { isBrowser, sanitizeClassNames } from "./utils.js"; +import { withoutTransition } from "./without-transition.js"; +import { systemPrefersMode, userPrefersMode } from "./mode-states.svelte.js"; +import { customTheme } from "./theme-state.svelte.js"; +import { untrack } from "svelte"; +/** + * Theme colors for light and dark modes. + */ +export const themeColors = box(undefined); +/** + * Whether to disable transitions when changing the mode. + */ +export const disableTransitions = box(true); +/** + * Whether to run the mode changes synchronously instead of using + * an animation frame. If true, will have an impact on blocking performance + * due to blocking the main thread. + */ +export const synchronousModeChanges = box(false); +/** + * The classnames to add to the root `html` element when the mode is dark. + */ +export const darkClassNames = box([]); +/** + * The classnames to add to the root `html` element when the mode is light. + */ +export const lightClassNames = box([]); +function createDerivedMode() { + const current = $derived.by(() => { + if (!isBrowser) + return undefined; + const derivedMode = userPrefersMode.current === "system" + ? systemPrefersMode.current + : userPrefersMode.current; + const sanitizedDarkClassNames = sanitizeClassNames(darkClassNames.current); + const sanitizedLightClassNames = sanitizeClassNames(lightClassNames.current); + function update() { + const htmlEl = document.documentElement; + const themeColorEl = document.querySelector('meta[name="theme-color"]'); + if (derivedMode === "light") { + if (sanitizedDarkClassNames.length) + htmlEl.classList.remove(...sanitizedDarkClassNames); + if (sanitizedLightClassNames.length) + htmlEl.classList.add(...sanitizedLightClassNames); + htmlEl.style.colorScheme = "light"; + if (themeColorEl && themeColors.current) { + themeColorEl.setAttribute("content", themeColors.current.light); + } + } + else { + if (sanitizedLightClassNames.length) + htmlEl.classList.remove(...sanitizedLightClassNames); + if (sanitizedDarkClassNames.length) + htmlEl.classList.add(...sanitizedDarkClassNames); + htmlEl.style.colorScheme = "dark"; + if (themeColorEl && themeColors.current) { + themeColorEl.setAttribute("content", themeColors.current.dark); + } + } + } + if (disableTransitions.current) { + withoutTransition(update, synchronousModeChanges.current); + } + else { + update(); + } + return derivedMode; + }); + return { + get current() { + return current; + }, + }; +} +function createDerivedTheme() { + const current = $derived.by(() => { + customTheme.current; + if (!isBrowser) + return undefined; + function update() { + const htmlEl = document.documentElement; + htmlEl.setAttribute("data-theme", customTheme.current); + } + if (disableTransitions.current) { + withoutTransition(update, untrack(() => synchronousModeChanges.current)); + } + else { + update(); + } + return customTheme.current; + }); + return { + get current() { + return current; + }, + }; +} +/** + * Derived store that represents the current mode (`"dark"`, `"light"` or `undefined`) + */ +export const derivedMode = createDerivedMode(); +/** + * Derived store that represents the current custom theme + */ +export const derivedTheme = createDerivedTheme(); +export { derivedMode as mode, derivedTheme as theme }; diff --git a/tools/ui/node_modules/mode-watcher/dist/storage-keys.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/storage-keys.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a742ec1e15bbed2a7ad2aabfce40fc305dd68fa4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/storage-keys.svelte.d.ts @@ -0,0 +1,8 @@ +/** + * The key used to store the `mode` in localStorage. + */ +export declare const modeStorageKey: import("svelte-toolbelt").WritableBox; +/** + * The key used to store the `theme` in localStorage. + */ +export declare const themeStorageKey: import("svelte-toolbelt").WritableBox; diff --git a/tools/ui/node_modules/mode-watcher/dist/storage-keys.svelte.js b/tools/ui/node_modules/mode-watcher/dist/storage-keys.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..e94fb62e9dd1411d823f1cee59b3796f190df11c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/storage-keys.svelte.js @@ -0,0 +1,9 @@ +import { box } from "svelte-toolbelt"; +/** + * The key used to store the `mode` in localStorage. + */ +export const modeStorageKey = box("mode-watcher-mode"); +/** + * The key used to store the `theme` in localStorage. + */ +export const themeStorageKey = box("mode-watcher-theme"); diff --git a/tools/ui/node_modules/mode-watcher/dist/theme-state.svelte.d.ts b/tools/ui/node_modules/mode-watcher/dist/theme-state.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b88af4bfd075cde4a7fd4e3937bab62bbbc56112 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/theme-state.svelte.d.ts @@ -0,0 +1,19 @@ +declare class CustomTheme { + #private; + constructor(); + /** + * The current theme. + * @returns The current theme. + */ + get current(): string; + /** + * Set the current theme. + * @param newValue The new theme to set. + */ + set current(newValue: string); +} +/** + * A custom theme to apply and persist to the root `html` element. + */ +export declare const customTheme: CustomTheme; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/dist/theme-state.svelte.js b/tools/ui/node_modules/mode-watcher/dist/theme-state.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..ecf0788bed71edf2343cc4841c6c09d01bf02d65 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/theme-state.svelte.js @@ -0,0 +1,50 @@ +import { PersistedState, watch } from "runed"; +import { themeStorageKey } from "./storage-keys.svelte.js"; +import { isBrowser, noopStorage } from "./utils.js"; +class CustomTheme { + #storage = isBrowser ? localStorage : noopStorage; + #initialValue = this.#storage.getItem(themeStorageKey.current); + #value = this.#initialValue === null || this.#initialValue === undefined ? "" : this.#initialValue; + #persisted = $state(this.#makePersisted()); + #makePersisted(value = this.#value) { + return new PersistedState(themeStorageKey.current, value, { + serializer: { + serialize: (v) => { + if (typeof v !== "string") + return ""; + return v; + }, + deserialize: (v) => v, + }, + }); + } + constructor() { + $effect.root(() => { + return watch.pre(() => themeStorageKey.current, (_, prevStorageKey) => { + const currModeValue = this.#persisted.current; + this.#persisted = this.#makePersisted(currModeValue); + if (prevStorageKey) { + localStorage.removeItem(prevStorageKey); + } + }); + }); + } + /** + * The current theme. + * @returns The current theme. + */ + get current() { + return this.#persisted.current; + } + /** + * Set the current theme. + * @param newValue The new theme to set. + */ + set current(newValue) { + this.#persisted.current = newValue; + } +} +/** + * A custom theme to apply and persist to the root `html` element. + */ +export const customTheme = new CustomTheme(); diff --git a/tools/ui/node_modules/mode-watcher/dist/types.d.ts b/tools/ui/node_modules/mode-watcher/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a6eb53600e5db4db00466ae261d738519c11ec6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/types.d.ts @@ -0,0 +1,89 @@ +import type { modes } from "./modes.js"; +export type Mode = (typeof modes)[number]; +export type ThemeColors = { + dark: string; + light: string; +} | undefined; +export type ModeWatcherProps = { + /** + * Whether to automatically track operating system preferences + * and update the mode accordingly. + * + * @default `true` + */ + track?: boolean; + /** + * The default mode to use instead of the user's preference. + * + * @default `"system"` + */ + defaultMode?: Mode; + /** + * The default theme to use, which will be applied to the root `html` element + * and can be managed with the `setTheme` function. + * + * @example + * ```html + * + * ``` + * + * @default `undefined` + */ + defaultTheme?: string; + /** + * The theme colors to use for each mode. + */ + themeColors?: ThemeColors; + /** + * Whether to disable transitions when updating the mode. + */ + disableTransitions?: boolean; + /** + * The classname to add to the root `html` element when the mode is dark. + * + * @default `["dark"]` + */ + darkClassNames?: string[]; + /** + * The classname to add to the root `html` element when the mode is light. + * + * @default `[]` + */ + lightClassNames?: string[]; + /** + * Optionally provide a custom local storage key to use for storing the mode. + * + * @default `'mode-watcher-mode'` + */ + modeStorageKey?: string; + /** + * Optionally provide a custom local storage key to use for storing the theme. + * + * @default `'mode-watcher-theme'` + */ + themeStorageKey?: string; + /** + * An optional nonce to use for the injected script tag to allow-list mode-watcher + * if you are using a Content Security Policy. + * + * @default `undefined` + */ + nonce?: string; + /** + * Whether to disable the injected script tag that sets the initial mode. + * Set this if you are manually injecting the script using a hook. + * + * @default `false` + */ + disableHeadScriptInjection?: boolean; + /** + * Whether to run the mode changes synchronously instead of using + * an animation frame. If true, will have an impact on blocking performance + * due to blocking the main thread. + * + * Only applicable if `disableTransitions` is set to `true`. + * + * @default `false` + */ + synchronousModeChanges?: boolean; +}; diff --git a/tools/ui/node_modules/mode-watcher/dist/types.js b/tools/ui/node_modules/mode-watcher/dist/types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/types.js @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/mode-watcher/dist/utils.d.ts b/tools/ui/node_modules/mode-watcher/dist/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67b27ff82e6fdb1b21b32306686cbbe1dafc96df --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/utils.d.ts @@ -0,0 +1,9 @@ +/** + * Sanitizes an array of classnames by removing any empty strings. + */ +export declare function sanitizeClassNames(classNames: string[]): string[]; +export declare const noopStorage: { + getItem: (_key: string) => null; + setItem: (_key: string, _value: string) => void; +}; +export declare const isBrowser: boolean; diff --git a/tools/ui/node_modules/mode-watcher/dist/utils.js b/tools/ui/node_modules/mode-watcher/dist/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..c457c0059db390b87b17a95f175e76ac59def8d8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/utils.js @@ -0,0 +1,11 @@ +/** + * Sanitizes an array of classnames by removing any empty strings. + */ +export function sanitizeClassNames(classNames) { + return classNames.filter((className) => className.length > 0); +} +export const noopStorage = { + getItem: (_key) => null, + setItem: (_key, _value) => { }, +}; +export const isBrowser = typeof document !== "undefined"; diff --git a/tools/ui/node_modules/mode-watcher/dist/without-transition.d.ts b/tools/ui/node_modules/mode-watcher/dist/without-transition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..459b5c600582495a01e8f050ca02d21dcc879616 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/without-transition.d.ts @@ -0,0 +1 @@ +export declare function withoutTransition(action: () => any, synchronous?: boolean): void; diff --git a/tools/ui/node_modules/mode-watcher/dist/without-transition.js b/tools/ui/node_modules/mode-watcher/dist/without-transition.js new file mode 100644 index 0000000000000000000000000000000000000000..901fc9f4cb9bad79dba2dad2823f7eacddbb2ab2 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/dist/without-transition.js @@ -0,0 +1,79 @@ +// Original Source: https://reemus.dev/article/disable-css-transition-color-scheme-change#heading-ultimate-solution-for-changing-color-scheme-without-transitions +let timeoutAction; +let timeoutEnable; +/** + * Whether this is the first time the function has been + * called, which will be true for the initial load, where + * we shouldn't need to disable any transitions, as there + * is nothing to transition from. + */ +let hasLoaded = false; +let styleElement = null; +// Create reusable style element +function getStyleElement() { + if (styleElement) + return styleElement; + styleElement = document.createElement("style"); + styleElement.appendChild(document.createTextNode(`* { + -webkit-transition: none !important; + -moz-transition: none !important; + -o-transition: none !important; + -ms-transition: none !important; + transition: none !important; + }`)); + return styleElement; +} +// Perform a task without any css transitions +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function withoutTransition(action, synchronous = false) { + if (typeof document === "undefined") + return; + // Skip transition disabling on initial load + if (!hasLoaded) { + hasLoaded = true; + action(); + return; + } + // In test environments, run synchronously to avoid timing issues + const isTest = (typeof process !== "undefined" && process.env?.NODE_ENV === "test") || + (typeof window !== "undefined" && + window.__vitest_worker__); + if (isTest) { + action(); + return; + } + clearTimeout(timeoutAction); + clearTimeout(timeoutEnable); + const style = getStyleElement(); + const disable = () => document.head.appendChild(style); + const enable = () => { + if (style.parentNode) { + document.head.removeChild(style); + } + }; + function executeAction() { + action(); + // defer enable to ensure action completes + window.requestAnimationFrame(enable); + } + // Use requestAnimationFrame for better performance + if (typeof window.requestAnimationFrame !== "undefined") { + disable(); + if (synchronous) { + executeAction(); + } + else { + // defer action to next frame to avoid blocking + window.requestAnimationFrame(() => { + executeAction(); + }); + } + return; + } + // Fallback for older browsers + disable(); + timeoutAction = window.setTimeout(() => { + action(); + timeoutEnable = window.setTimeout(enable, 16); + }, 16); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/LICENSE b/tools/ui/node_modules/mode-watcher/node_modules/runed/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..66fd878694f2e19172751731c8b903e5a047e7ef --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024 Hunter Johnston +Copyright (c) 2024 Thomas G. Lopes + +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. diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/README.md b/tools/ui/node_modules/mode-watcher/node_modules/runed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e4ab80d0d815794acb89d6ac08a089c56e52e8c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/README.md @@ -0,0 +1,32 @@ +# Runed + + + +[![npm version](https://flat.badgen.net/npm/v/runed?color=green)](https://npmjs.com/package/runed) +[![npm downloads](https://flat.badgen.net/npm/dm/runed?color=green)](https://npmjs.com/package/runed) +[![license](https://flat.badgen.net/github/license/svecosystem/runed?color=green)](https://github.com/svecosystem/runed/blob/main/LICENSE) + + + +Runed provides utilities to power your applications using the magic of +[Svelte Runes](https://svelte.dev/blog/runes). + +## Features + + + +## Installation + +Runed will be published to NPM once Svelte 5 is released. + +## License + + + +Published under the [MIT](https://github.com/svecosystem/runed/blob/main/LICENSE) license. Made by +[@tglide](https://github.com/tglide), [@huntabyte](https://github.com/huntabyte) and +[community](https://github.com/svecosystem/runed/graphs/contributors) 💛

+ + + + diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01d2be1985ff9683c407139778042b081afe4785 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/index.d.ts @@ -0,0 +1 @@ +export * from "./utilities/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..01d2be1985ff9683c407139778042b081afe4785 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/index.js @@ -0,0 +1 @@ +export * from "./utilities/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/configurable-globals.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/configurable-globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43192a8559eeae16bd2e59c3c9d792dee826cf0e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/configurable-globals.d.ts @@ -0,0 +1,23 @@ +export type ConfigurableWindow = { + /** Provide a custom `window` object to use in place of the global `window` object. */ + window?: typeof globalThis & Window; +}; +export type ConfigurableDocument = { + /** Provide a custom `document` object to use in place of the global `document` object. */ + document?: Document; +}; +export type ConfigurableDocumentOrShadowRoot = { + document?: DocumentOrShadowRoot; +}; +export type ConfigurableNavigator = { + /** Provide a custom `navigator` object to use in place of the global `navigator` object. */ + navigator?: Navigator; +}; +export type ConfigurableLocation = { + /** Provide a custom `location` object to use in place of the global `location` object. */ + location?: Location; +}; +export declare const defaultWindow: (Window & typeof globalThis) | undefined; +export declare const defaultDocument: Document | undefined; +export declare const defaultNavigator: Navigator | undefined; +export declare const defaultLocation: Location | undefined; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/configurable-globals.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/configurable-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..c1c0765bbdf51e98ae17c2292910dc2524576670 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/configurable-globals.js @@ -0,0 +1,5 @@ +import { BROWSER } from "esm-env"; +export const defaultWindow = BROWSER && typeof window !== "undefined" ? window : undefined; +export const defaultDocument = BROWSER && typeof window !== "undefined" ? window.document : undefined; +export const defaultNavigator = BROWSER && typeof window !== "undefined" ? window.navigator : undefined; +export const defaultLocation = BROWSER && typeof window !== "undefined" ? window.location : undefined; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/types.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0292b0429a1bab2f3e93f35202ac6e388e6975ca --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/types.d.ts @@ -0,0 +1,11 @@ +export type Getter = () => T; +export type MaybeGetter = T | Getter; +export type MaybeElementGetter = MaybeGetter; +export type MaybeElement = HTMLElement | SVGElement | undefined | null; +export type Setter = (value: T) => void; +export type Expand = T extends infer U ? { + [K in keyof U]: U[K]; +} : never; +export type WritableProperties = { + -readonly [P in keyof T]: T[P]; +}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/types.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/types.js @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/array.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..858ea9088717041ac6d9bf8289969ab6f5f8f631 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/array.d.ts @@ -0,0 +1,5 @@ +/** + * Get nth item of Array. Negative for backward + */ +export declare function at(array: readonly T[], index: number): T | undefined; +export declare function last(array: readonly T[]): T | undefined; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/array.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/array.js new file mode 100644 index 0000000000000000000000000000000000000000..bcd82395afd8936a384049aa09c3928097a4cbc0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/array.js @@ -0,0 +1,14 @@ +/** + * Get nth item of Array. Negative for backward + */ +export function at(array, index) { + const len = array.length; + if (!len) + return undefined; + if (index < 0) + index += len; + return array[index]; +} +export function last(array) { + return array[array.length - 1]; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/browser.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5431041d4afccbb9c64cf6ecfa5331731de9c18 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/browser.d.ts @@ -0,0 +1 @@ +export { BROWSER as browser } from "esm-env"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/browser.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..e5431041d4afccbb9c64cf6ecfa5331731de9c18 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/browser.js @@ -0,0 +1 @@ +export { BROWSER as browser } from "esm-env"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/dom.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97809a965b1fd0d6847e831a722bb883e073e9f5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/dom.d.ts @@ -0,0 +1,25 @@ +/** + * Handles getting the active element in a document or shadow root. + * If the active element is within a shadow root, it will traverse the shadow root + * to find the active element. + * If not, it will return the active element in the document. + * + * @param document A document or shadow root to get the active element from. + * @returns The active element in the document or shadow root. + */ +export declare function getActiveElement(document: DocumentOrShadowRoot): Element | null; +/** + * Returns the owner document of a given element. + * + * @param node The element to get the owner document from. + * @returns + */ +export declare function getOwnerDocument(node: Element | null | undefined, fallback?: Document | undefined): Document | undefined; +/** + * Checks if an element is or is contained by another element. + * + * @param node The element to check if it or its descendants contain the target element. + * @param target The element to check if it is contained by the node. + * @returns + */ +export declare function isOrContainsTarget(node: Element, target: Element): boolean; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/dom.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..e0fb6b7eb0e341aafc81d069d8a249aeb36d96ee --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/dom.js @@ -0,0 +1,40 @@ +import { defaultDocument } from "../configurable-globals.js"; +/** + * Handles getting the active element in a document or shadow root. + * If the active element is within a shadow root, it will traverse the shadow root + * to find the active element. + * If not, it will return the active element in the document. + * + * @param document A document or shadow root to get the active element from. + * @returns The active element in the document or shadow root. + */ +export function getActiveElement(document) { + let activeElement = document.activeElement; + while (activeElement?.shadowRoot) { + const node = activeElement.shadowRoot.activeElement; + if (node === activeElement) + break; + else + activeElement = node; + } + return activeElement; +} +/** + * Returns the owner document of a given element. + * + * @param node The element to get the owner document from. + * @returns + */ +export function getOwnerDocument(node, fallback = defaultDocument) { + return node?.ownerDocument ?? fallback; +} +/** + * Checks if an element is or is contained by another element. + * + * @param node The element to check if it or its descendants contain the target element. + * @param target The element to check if it is contained by the node. + * @returns + */ +export function isOrContainsTarget(node, target) { + return node === target || node.contains(target); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/function.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/function.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..940809c20c17e42210afda39714ae2410ed566d6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/function.d.ts @@ -0,0 +1 @@ +export declare function noop(): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/function.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/function.js new file mode 100644 index 0000000000000000000000000000000000000000..510c075494c057a30a1add2e9cc2fffbcfa43478 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/function.js @@ -0,0 +1 @@ +export function noop() { } diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/get.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/get.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f946aab0136e40ab48412e77659632fdde4a4b4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/get.d.ts @@ -0,0 +1,2 @@ +import type { MaybeGetter } from "../types.js"; +export declare function get(value: MaybeGetter): T; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/get.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/get.js new file mode 100644 index 0000000000000000000000000000000000000000..7039f0e1f8baf1eaa6b1c670057bd7ef6c2f7f7c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/get.js @@ -0,0 +1,7 @@ +import { isFunction } from "./is.js"; +export function get(value) { + if (isFunction(value)) { + return value(); + } + return value; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/is.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/is.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56b733898063f7e543c8927c890a4b8d7bee292f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/is.d.ts @@ -0,0 +1,3 @@ +export declare function isFunction(value: unknown): value is (...args: unknown[]) => unknown; +export declare function isObject(value: unknown): value is Record; +export declare function isElement(value: unknown): value is Element; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/is.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/is.js new file mode 100644 index 0000000000000000000000000000000000000000..4f248e7350be7e5e212232073ade3ddd4d6c06e5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/is.js @@ -0,0 +1,9 @@ +export function isFunction(value) { + return typeof value === "function"; +} +export function isObject(value) { + return value !== null && typeof value === "object"; +} +export function isElement(value) { + return value instanceof Element; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/sleep.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/sleep.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5045cf22bb7e10a6229c8026cae8e99cf1243878 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/sleep.d.ts @@ -0,0 +1 @@ +export declare function sleep(ms?: number): Promise; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/sleep.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/sleep.js new file mode 100644 index 0000000000000000000000000000000000000000..eda75dce940fe106313c547d7ca40e343f04a1ab --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/internal/utils/sleep.js @@ -0,0 +1,3 @@ +export async function sleep(ms = 0) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/test/util.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/test/util.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..324b31676c949abbff26966ddfb128411ce97ff1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/test/util.svelte.d.ts @@ -0,0 +1,3 @@ +export declare function testWithEffect(name: string, fn: () => void | Promise): void; +export declare function effectRootScope(fn: () => void | Promise): void | Promise; +export declare function vitestSetTimeoutWrapper(fn: () => void, timeout: number): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/test/util.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/test/util.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..e9c5a27051de7036750535198cd3de80ade57a0c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/test/util.svelte.js @@ -0,0 +1,22 @@ +import { test, vi } from "vitest"; +export function testWithEffect(name, fn) { + test(name, () => effectRootScope(fn)); +} +export function effectRootScope(fn) { + let promise; + const cleanup = $effect.root(() => { + promise = fn(); + }); + if (promise instanceof Promise) { + return promise.finally(cleanup); + } + else { + cleanup(); + } +} +export function vitestSetTimeoutWrapper(fn, timeout) { + setTimeout(() => { + fn(); + }, timeout + 1); + vi.advanceTimersByTime(timeout); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/active-element.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/active-element.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e608e7a58f93a7d879892c48fa787b799bff83b4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/active-element.svelte.d.ts @@ -0,0 +1,18 @@ +import { type ConfigurableDocumentOrShadowRoot, type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface ActiveElementOptions extends ConfigurableDocumentOrShadowRoot, ConfigurableWindow { +} +export declare class ActiveElement { + #private; + constructor(options?: ActiveElementOptions); + get current(): Element | null; +} +/** + * An object holding a reactive value that is equal to `document.activeElement`. + * It automatically listens for changes, keeping the reference up to date. + * + * If you wish to use a custom document or shadowRoot, you should use + * [useActiveElement](https://runed.dev/docs/utilities/active-element) instead. + * + * @see {@link https://runed.dev/docs/utilities/active-element} + */ +export declare const activeElement: ActiveElement; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/active-element.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/active-element.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..c6c84c0e0b48a61717dad9955e3632d16413b253 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/active-element.svelte.js @@ -0,0 +1,38 @@ +import { defaultWindow, } from "../../internal/configurable-globals.js"; +import { getActiveElement } from "../../internal/utils/dom.js"; +import { on } from "svelte/events"; +import { createSubscriber } from "svelte/reactivity"; +export class ActiveElement { + #document; + #subscribe; + constructor(options = {}) { + const { window = defaultWindow, document = window?.document } = options; + if (window === undefined) + return; + this.#document = document; + this.#subscribe = createSubscriber((update) => { + const cleanupFocusIn = on(window, "focusin", update); + const cleanupFocusOut = on(window, "focusout", update); + return () => { + cleanupFocusIn(); + cleanupFocusOut(); + }; + }); + } + get current() { + this.#subscribe?.(); + if (!this.#document) + return null; + return getActiveElement(this.#document); + } +} +/** + * An object holding a reactive value that is equal to `document.activeElement`. + * It automatically listens for changes, keeping the reference up to date. + * + * If you wish to use a custom document or shadowRoot, you should use + * [useActiveElement](https://runed.dev/docs/utilities/active-element) instead. + * + * @see {@link https://runed.dev/docs/utilities/active-element} + */ +export const activeElement = new ActiveElement(); diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2088da81b429c7c55d0862fc3c07f20edc4c3400 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/index.d.ts @@ -0,0 +1 @@ +export * from "./active-element.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2088da81b429c7c55d0862fc3c07f20edc4c3400 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/active-element/index.js @@ -0,0 +1 @@ +export * from "./active-element.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a41ddd48612e4f24e5c6e2dae6f3ba482bc2dceb --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.d.ts @@ -0,0 +1,40 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +type RafCallbackParams = { + /** The number of milliseconds since the last frame. */ + delta: number; + /** + * Time elapsed since the creation of the web page. + * See {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin Time origin}. + */ + timestamp: DOMHighResTimeStamp; +}; +export type AnimationFramesOptions = ConfigurableWindow & { + /** + * Start calling requestAnimationFrame immediately. + * + * @default true + */ + immediate?: boolean; + /** + * Limit the number of frames per second. + * Set to `0` to disable + * + * @default 0 + */ + fpsLimit?: MaybeGetter; +}; +/** + * Wrapper over {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame}, + * with controls for pausing and resuming the animation, reactive tracking and optional limiting of fps, and utilities. + */ +export declare class AnimationFrames { + #private; + constructor(callback: (params: RafCallbackParams) => void, options?: AnimationFramesOptions); + start(): void; + stop(): void; + toggle(): void; + get fps(): number; + get running(): boolean; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..5af8aa5f524fb6c51c8f855c4e90c634e92e0b0f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.js @@ -0,0 +1,72 @@ +import { untrack } from "svelte"; +import { extract } from "../extract/index.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Wrapper over {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame}, + * with controls for pausing and resuming the animation, reactive tracking and optional limiting of fps, and utilities. + */ +export class AnimationFrames { + #callback; + #fpsLimitOption = 0; + #fpsLimit = $derived(extract(this.#fpsLimitOption) ?? 0); + #previousTimestamp = null; + #frame = null; + #fps = $state(0); + #running = $state(false); + #window = defaultWindow; + constructor(callback, options = {}) { + if (options.window) + this.#window = options.window; + this.#fpsLimitOption = options.fpsLimit; + this.#callback = callback; + this.start = this.start.bind(this); + this.stop = this.stop.bind(this); + this.toggle = this.toggle.bind(this); + $effect(() => { + if (options.immediate ?? true) { + untrack(this.start); + } + return this.stop; + }); + } + #loop(timestamp) { + if (!this.#running || !this.#window) + return; + if (this.#previousTimestamp === null) { + this.#previousTimestamp = timestamp; + } + const delta = timestamp - this.#previousTimestamp; + const fps = 1000 / delta; + if (this.#fpsLimit && fps > this.#fpsLimit) { + this.#frame = this.#window.requestAnimationFrame(this.#loop.bind(this)); + return; + } + this.#fps = fps; + this.#previousTimestamp = timestamp; + this.#callback({ delta, timestamp }); + this.#frame = this.#window.requestAnimationFrame(this.#loop.bind(this)); + } + start() { + if (!this.#window) + return; + this.#running = true; + this.#previousTimestamp = 0; + this.#frame = this.#window.requestAnimationFrame(this.#loop.bind(this)); + } + stop() { + if (!this.#frame || !this.#window) + return; + this.#running = false; + this.#window.cancelAnimationFrame(this.#frame); + this.#frame = null; + } + toggle() { + this.#running ? this.stop() : this.start(); + } + get fps() { + return !this.#running ? 0 : this.#fps; + } + get running() { + return this.#running; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9620b836ff6875aaf49cb4f43df743d39f5b42e2 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/index.d.ts @@ -0,0 +1 @@ +export * from "./animation-frames.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9620b836ff6875aaf49cb4f43df743d39f5b42e2 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/animation-frames/index.js @@ -0,0 +1 @@ +export * from "./animation-frames.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/context.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..13ef0701a076ebc92e0fca4225e84d74c6fe6ab1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/context.d.ts @@ -0,0 +1,42 @@ +export declare class Context { + #private; + /** + * @param name The name of the context. + * This is used for generating the context key and error messages. + */ + constructor(name: string); + /** + * The key used to get and set the context. + * + * It is not recommended to use this value directly. + * Instead, use the methods provided by this class. + */ + get key(): symbol; + /** + * Checks whether this has been set in the context of a parent component. + * + * Must be called during component initialisation. + */ + exists(): boolean; + /** + * Retrieves the context that belongs to the closest parent component. + * + * Must be called during component initialisation. + * + * @throws An error if the context does not exist. + */ + get(): TContext; + /** + * Retrieves the context that belongs to the closest parent component, + * or the given fallback value if the context does not exist. + * + * Must be called during component initialisation. + */ + getOr(fallback: TFallback): TContext | TFallback; + /** + * Associates the given value with the current component and returns it. + * + * Must be called during component initialisation. + */ + set(context: TContext): TContext; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/context.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/context.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9ad7b36b279079d9506ff0d1ff9053374f560f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/context.js @@ -0,0 +1,65 @@ +import { getContext, hasContext, setContext } from "svelte"; +export class Context { + #name; + #key; + /** + * @param name The name of the context. + * This is used for generating the context key and error messages. + */ + constructor(name) { + this.#name = name; + this.#key = Symbol(name); + } + /** + * The key used to get and set the context. + * + * It is not recommended to use this value directly. + * Instead, use the methods provided by this class. + */ + get key() { + return this.#key; + } + /** + * Checks whether this has been set in the context of a parent component. + * + * Must be called during component initialisation. + */ + exists() { + return hasContext(this.#key); + } + /** + * Retrieves the context that belongs to the closest parent component. + * + * Must be called during component initialisation. + * + * @throws An error if the context does not exist. + */ + get() { + const context = getContext(this.#key); + if (context === undefined) { + throw new Error(`Context "${this.#name}" not found`); + } + return context; + } + /** + * Retrieves the context that belongs to the closest parent component, + * or the given fallback value if the context does not exist. + * + * Must be called during component initialisation. + */ + getOr(fallback) { + const context = getContext(this.#key); + if (context === undefined) { + return fallback; + } + return context; + } + /** + * Associates the given value with the current component and returns it. + * + * Must be called during component initialisation. + */ + set(context) { + return setContext(this.#key, context); + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1244f57a741ab24941b2cc20e6c924b8650a1425 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/index.d.ts @@ -0,0 +1 @@ +export { Context } from "./context.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1244f57a741ab24941b2cc20e6c924b8650a1425 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/context/index.js @@ -0,0 +1 @@ +export { Context } from "./context.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/debounced.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/debounced.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c8898cc2b74bdcb5cded1492ef1a63c4b2fea3a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/debounced.svelte.d.ts @@ -0,0 +1,48 @@ +import type { Getter, MaybeGetter } from "../../internal/types.js"; +/** + * A wrapper over {@link useDebounce} that creates a debounced state. + * It takes a "getter" function which returns the state you want to debounce. + * Every time this state changes a timer (re)starts, the length of which is + * configurable with the `wait` arg. When the timer ends the `current` value + * is updated. + * + * @see https://runed.dev/docs/utilities/debounced + * + * @example + * + * + * + *
+ * + *

You searched for: {debounced.current}

+ *
+ */ +export declare class Debounced { + #private; + /** + * @param getter A function that returns the state to watch. + * @param wait The length of time to wait in ms, defaults to 250. + */ + constructor(getter: Getter, wait?: MaybeGetter); + /** + * Get the current value. + */ + get current(): T; + /** + * Cancel the latest timer. + */ + cancel(): void; + /** + * Run the debounced function immediately. + */ + updateImmediately(): Promise; + /** + * Set the `current` value without waiting. + */ + setImmediately(v: T): void; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/debounced.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/debounced.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..c8175e7ba884e052a42876235ba84e50584282c6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/debounced.svelte.js @@ -0,0 +1,71 @@ +import { useDebounce } from "../use-debounce/use-debounce.svelte.js"; +import { watch } from "../watch/watch.svelte.js"; +import { noop } from "../../internal/utils/function.js"; +/** + * A wrapper over {@link useDebounce} that creates a debounced state. + * It takes a "getter" function which returns the state you want to debounce. + * Every time this state changes a timer (re)starts, the length of which is + * configurable with the `wait` arg. When the timer ends the `current` value + * is updated. + * + * @see https://runed.dev/docs/utilities/debounced + * + * @example + * + * + * + *
+ * + *

You searched for: {debounced.current}

+ *
+ */ +export class Debounced { + #current = $state(); + #debounceFn; + /** + * @param getter A function that returns the state to watch. + * @param wait The length of time to wait in ms, defaults to 250. + */ + constructor(getter, wait = 250) { + this.#current = getter(); // immediately set the initial value + this.cancel = this.cancel.bind(this); + this.setImmediately = this.setImmediately.bind(this); + this.updateImmediately = this.updateImmediately.bind(this); + this.#debounceFn = useDebounce(() => { + this.#current = getter(); + }, wait); + watch(getter, () => { + this.#debounceFn().catch(noop); + }); + } + /** + * Get the current value. + */ + get current() { + return this.#current; + } + /** + * Cancel the latest timer. + */ + cancel() { + this.#debounceFn.cancel(); + } + /** + * Run the debounced function immediately. + */ + updateImmediately() { + return this.#debounceFn.runScheduledNow(); + } + /** + * Set the `current` value without waiting. + */ + setImmediately(v) { + this.cancel(); + this.#current = v; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d8afc470bd7bbd571ceca2fd1e1762ca9f0e86f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/index.d.ts @@ -0,0 +1 @@ +export * from "./debounced.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d8afc470bd7bbd571ceca2fd1e1762ca9f0e86f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/debounced/index.js @@ -0,0 +1 @@ +export * from "./debounced.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..809f63d1ec8db5cba918e1e3c39f7e0a95c6ed51 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.d.ts @@ -0,0 +1,31 @@ +import type { MaybeElementGetter, WritableProperties } from "../../internal/types.js"; +import type { ConfigurableWindow } from "../../internal/configurable-globals.js"; +type Rect = WritableProperties>; +export type ElementRectOptions = ConfigurableWindow & { + initialRect?: DOMRect; +}; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export declare class ElementRect { + #private; + constructor(node: MaybeElementGetter, options?: ElementRectOptions); + get x(): number; + get y(): number; + get width(): number; + get height(): number; + get top(): number; + get right(): number; + get bottom(): number; + get left(): number; + get current(): Rect; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..365dbabcf805856268b18570e7afa698334881d0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.js @@ -0,0 +1,85 @@ +import { extract } from "../extract/extract.svelte.js"; +import { useMutationObserver } from "../use-mutation-observer/use-mutation-observer.svelte.js"; +import { useResizeObserver } from "../use-resize-observer/use-resize-observer.svelte.js"; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export class ElementRect { + #rect = $state({ + x: 0, + y: 0, + width: 0, + height: 0, + top: 0, + right: 0, + bottom: 0, + left: 0, + }); + constructor(node, options = {}) { + this.#rect = { + width: options.initialRect?.width ?? 0, + height: options.initialRect?.height ?? 0, + x: options.initialRect?.x ?? 0, + y: options.initialRect?.y ?? 0, + top: options.initialRect?.top ?? 0, + right: options.initialRect?.right ?? 0, + bottom: options.initialRect?.bottom ?? 0, + left: options.initialRect?.left ?? 0, + }; + const el = $derived(extract(node)); + const update = () => { + if (!el) + return; + const rect = el.getBoundingClientRect(); + this.#rect.width = rect.width; + this.#rect.height = rect.height; + this.#rect.x = rect.x; + this.#rect.y = rect.y; + this.#rect.top = rect.top; + this.#rect.right = rect.right; + this.#rect.bottom = rect.bottom; + this.#rect.left = rect.left; + }; + useResizeObserver(() => el, update, { window: options.window }); + $effect(update); + useMutationObserver(() => el, update, { + attributeFilter: ["style", "class"], + window: options.window, + }); + } + get x() { + return this.#rect.x; + } + get y() { + return this.#rect.y; + } + get width() { + return this.#rect.width; + } + get height() { + return this.#rect.height; + } + get top() { + return this.#rect.top; + } + get right() { + return this.#rect.right; + } + get bottom() { + return this.#rect.bottom; + } + get left() { + return this.#rect.left; + } + get current() { + return this.#rect; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d66f20780675a7a48e8f8ed4aed017878527ef90 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/index.d.ts @@ -0,0 +1 @@ +export { ElementRect } from "./element-rect.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d66f20780675a7a48e8f8ed4aed017878527ef90 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-rect/index.js @@ -0,0 +1 @@ +export { ElementRect } from "./element-rect.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/element-size.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/element-size.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e9e92b9b82856967507656995d65c72d05ae628 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/element-size.svelte.d.ts @@ -0,0 +1,30 @@ +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +import type { MaybeElementGetter } from "../../internal/types.js"; +export type ElementSizeOptions = ConfigurableWindow & { + initialSize?: { + width: number; + height: number; + }; + box?: "content-box" | "border-box"; +}; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export declare class ElementSize { + #private; + constructor(node: MaybeElementGetter, options?: ElementSizeOptions); + get current(): { + width: number; + height: number; + }; + get width(): number; + get height(): number; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/element-size.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/element-size.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..4d021882c625f53785127d98ed6f8aba35608700 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/element-size.svelte.js @@ -0,0 +1,54 @@ +import { defaultWindow } from "../../internal/configurable-globals.js"; +import { get } from "../../internal/utils/get.js"; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export class ElementSize { + #size = $state({ + width: 0, + height: 0, + }); + constructor(node, options = { box: "border-box" }) { + const window = options.window ?? defaultWindow; + this.#size = { + width: options.initialSize?.width ?? 0, + height: options.initialSize?.height ?? 0, + }; + $effect(() => { + if (!window) + return; + const node$ = get(node); + if (!node$) + return; + const observer = new window.ResizeObserver((entries) => { + for (const entry of entries) { + const boxSize = options.box === "content-box" ? entry.contentBoxSize : entry.borderBoxSize; + const boxSizeArr = Array.isArray(boxSize) ? boxSize : [boxSize]; + this.#size.width = boxSizeArr.reduce((acc, size) => Math.max(acc, size.inlineSize), 0); + this.#size.height = boxSizeArr.reduce((acc, size) => Math.max(acc, size.blockSize), 0); + } + }); + observer.observe(node$); + return () => { + observer.disconnect(); + }; + }); + } + get current() { + return this.#size; + } + get width() { + return this.#size.width; + } + get height() { + return this.#size.height; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42f14866cbddb82cb71ea334737bc2e6cdec4f24 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/index.d.ts @@ -0,0 +1 @@ +export * from "./element-size.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/index.js new file mode 100644 index 0000000000000000000000000000000000000000..42f14866cbddb82cb71ea334737bc2e6cdec4f24 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/element-size/index.js @@ -0,0 +1 @@ +export * from "./element-size.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/extract.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/extract.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d076878a9ce1b7a4a69150e67d91ef778524bd4d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/extract.svelte.d.ts @@ -0,0 +1,6 @@ +import type { MaybeGetter } from "../../internal/types.js"; +/** + * Extracts the value from a getter or a value. + * Optionally, a default value can be provided. + */ +export declare function extract(value: MaybeGetter, defaultValue?: T): T; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/extract.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/extract.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..6ab11772c6cff1190c6b509d05d0304fa821a0c4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/extract.svelte.js @@ -0,0 +1,12 @@ +import { isFunction } from "../../internal/utils/is.js"; +/** + * Extracts the value from a getter or a value. + * Optionally, a default value can be provided. + */ +export function extract(value, defaultValue) { + if (isFunction(value)) { + const getter = value; + return getter() ?? defaultValue ?? getter(); + } + return value ?? defaultValue ?? value; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c8f3467b8e26bd2a0695afe904659812ddb39a6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/index.d.ts @@ -0,0 +1 @@ +export { extract } from "./extract.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1c8f3467b8e26bd2a0695afe904659812ddb39a6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/extract/index.js @@ -0,0 +1 @@ +export { extract } from "./extract.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3086815fb812b541d14022370e35783e2b8bd3e9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.d.ts @@ -0,0 +1,37 @@ +export type FSMLifecycleFn = (meta: LifecycleFnMeta) => void; +export type LifecycleFnMeta = { + from: StatesT | null; + to: StatesT; + event: EventsT | null; + args: unknown; +}; +export declare function isLifecycleFnMeta(meta: unknown): meta is LifecycleFnMeta; +export type FSMLifecycle = "_enter" | "_exit"; +export type ActionFn = (...args: unknown[]) => StatesT | void; +export type Action = StatesT | ActionFn; +export type StateHandler = { + [e in EventsT]?: Action; +} & { + [k in FSMLifecycle]?: FSMLifecycleFn; +}; +export type Transition = { + [s in StatesT]: StateHandler; +} & { + "*"?: StateHandler; +}; +/** + * Defines a strongly-typed finite state machine. + * + * @see {@link https://runed.dev/docs/utilities/finite-state-machine} + */ +export declare class FiniteStateMachine { + #private; + readonly states: Transition; + constructor(initial: StatesT, states: Transition); + /** Triggers a new event and returns the new state. */ + send(event: EventsT, ...args: unknown[]): StatesT; + /** Debounces the triggering of an event. */ + debounce(wait: number | undefined, event: EventsT, ...args: unknown[]): Promise; + /** The current state. */ + get current(): StatesT; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..88a721df614730b6a163c320d6912652c2c1d81d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.js @@ -0,0 +1,78 @@ +export function isLifecycleFnMeta(meta) { + return (!!meta && + typeof meta === "object" && + "to" in meta && + "from" in meta && + "event" in meta && + "args" in meta); +} +/** + * Defines a strongly-typed finite state machine. + * + * @see {@link https://runed.dev/docs/utilities/finite-state-machine} + */ +export class FiniteStateMachine { + #current = $state(); + states; + #timeout = {}; + constructor(initial, states) { + this.#current = initial; + this.states = states; + this.send = this.send.bind(this); + this.debounce = this.debounce.bind(this); + // synthetically trigger _enter for the initial state. + this.#dispatch("_enter", { from: null, to: initial, event: null, args: [] }); + } + #transition(newState, event, args) { + const metadata = { from: this.#current, to: newState, event, args }; + this.#dispatch("_exit", metadata); + this.#current = newState; + this.#dispatch("_enter", metadata); + } + #dispatch(event, ...args) { + const action = this.states[this.#current]?.[event] ?? this.states["*"]?.[event]; + if (action instanceof Function) { + if (event === "_enter" || event === "_exit") { + if (isLifecycleFnMeta(args[0])) { + action(args[0]); + } + else { + console.warn("Invalid metadata passed to lifecycle function of the FSM."); + } + } + else { + return action(...args); + } + } + else if (typeof action === "string") { + return action; + } + else if (event !== "_enter" && event !== "_exit") { + console.warn("No action defined for event", event, "in state", this.#current); + } + } + /** Triggers a new event and returns the new state. */ + send(event, ...args) { + const newState = this.#dispatch(event, ...args); + if (newState && newState !== this.#current) { + this.#transition(newState, event, args); + } + return this.#current; + } + /** Debounces the triggering of an event. */ + async debounce(wait = 500, event, ...args) { + if (this.#timeout[event]) { + clearTimeout(this.#timeout[event]); + } + return new Promise((resolve) => { + this.#timeout[event] = setTimeout(() => { + delete this.#timeout[event]; + resolve(this.send(event, ...args)); + }, wait); + }); + } + /** The current state. */ + get current() { + return this.#current; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8935ec7dcb34124cd0eb9adfd3b7ffe0978fddea --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/index.d.ts @@ -0,0 +1 @@ +export * from "./finite-state-machine.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8935ec7dcb34124cd0eb9adfd3b7ffe0978fddea --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/finite-state-machine/index.js @@ -0,0 +1 @@ +export * from "./finite-state-machine.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f9b63f9d3d4e42f7a928e742a3198bd956c25388 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/index.d.ts @@ -0,0 +1,24 @@ +export * from "./active-element/index.js"; +export * from "./on-click-outside/index.js"; +export * from "./use-debounce/index.js"; +export * from "./element-size/index.js"; +export * from "./use-event-listener/index.js"; +export * from "./is-idle/index.js"; +export * from "./is-mounted/index.js"; +export * from "./state-history/index.js"; +export * from "./previous/index.js"; +export * from "./watch/index.js"; +export * from "./debounced/index.js"; +export * from "./pressed-keys/index.js"; +export * from "./element-rect/index.js"; +export * from "./use-mutation-observer/index.js"; +export * from "./use-resize-observer/index.js"; +export * from "./animation-frames/index.js"; +export * from "./use-intersection-observer/index.js"; +export * from "./is-focus-within/index.js"; +export * from "./finite-state-machine/index.js"; +export * from "./persisted-state/index.js"; +export * from "./use-geolocation/index.js"; +export * from "./context/index.js"; +export * from "./is-in-viewport/index.js"; +export * from "./resource/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f9b63f9d3d4e42f7a928e742a3198bd956c25388 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/index.js @@ -0,0 +1,24 @@ +export * from "./active-element/index.js"; +export * from "./on-click-outside/index.js"; +export * from "./use-debounce/index.js"; +export * from "./element-size/index.js"; +export * from "./use-event-listener/index.js"; +export * from "./is-idle/index.js"; +export * from "./is-mounted/index.js"; +export * from "./state-history/index.js"; +export * from "./previous/index.js"; +export * from "./watch/index.js"; +export * from "./debounced/index.js"; +export * from "./pressed-keys/index.js"; +export * from "./element-rect/index.js"; +export * from "./use-mutation-observer/index.js"; +export * from "./use-resize-observer/index.js"; +export * from "./animation-frames/index.js"; +export * from "./use-intersection-observer/index.js"; +export * from "./is-focus-within/index.js"; +export * from "./finite-state-machine/index.js"; +export * from "./persisted-state/index.js"; +export * from "./use-geolocation/index.js"; +export * from "./context/index.js"; +export * from "./is-in-viewport/index.js"; +export * from "./resource/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee30c5d33feb57bc2be6db954e0208281862fa5f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/index.d.ts @@ -0,0 +1 @@ +export * from "./is-focus-within.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ee30c5d33feb57bc2be6db954e0208281862fa5f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/index.js @@ -0,0 +1 @@ +export * from "./is-focus-within.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4425797eec2ae230b6a6c0a723d11ddf8752fb59 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.d.ts @@ -0,0 +1,13 @@ +import type { MaybeElementGetter } from "../../internal/types.js"; +import { type ActiveElementOptions } from "../active-element/active-element.svelte.js"; +export interface IsFocusWithinOptions extends ActiveElementOptions { +} +/** + * Tracks whether the focus is within a target element. + * @see {@link https://runed.dev/docs/utilities/is-focus-within} + */ +export declare class IsFocusWithin { + #private; + constructor(node: MaybeElementGetter, options?: IsFocusWithinOptions); + readonly current: boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..ab8ef14858e33e8ec01f7772f7fa2f27a7083a1a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.js @@ -0,0 +1,20 @@ +import { ActiveElement, } from "../active-element/active-element.svelte.js"; +import { extract } from "../extract/extract.svelte.js"; +/** + * Tracks whether the focus is within a target element. + * @see {@link https://runed.dev/docs/utilities/is-focus-within} + */ +export class IsFocusWithin { + #node; + #activeElement; + constructor(node, options = {}) { + this.#node = node; + this.#activeElement = new ActiveElement(options); + } + current = $derived.by(() => { + const node = extract(this.#node); + if (node == null) + return false; + return node.contains(this.#activeElement.current); + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8229534a546fc78b44134172b38bc7248b9df70e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/index.d.ts @@ -0,0 +1 @@ +export * from "./is-idle.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8229534a546fc78b44134172b38bc7248b9df70e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/index.js @@ -0,0 +1 @@ +export * from "./is-idle.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d11b94947712c5363e6af2c8a7126746c8afa19 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.d.ts @@ -0,0 +1,38 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableDocument, type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export type IsIdleOptions = ConfigurableDocument & ConfigurableWindow & { + /** + * The events that should set the idle state to `true` + * + * @default ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel'] + */ + events?: MaybeGetter<(keyof WindowEventMap)[]>; + /** + * The timeout in milliseconds before the idle state is set to `true`. Defaults to 60 seconds. + * + * @default 60000 + */ + timeout?: MaybeGetter; + /** + * Detect document visibility changes + * + * @default false + */ + detectVisibilityChanges?: MaybeGetter; + /** + * The initial state of the idle property + * + * @default false + */ + initialState?: boolean; +}; +/** + * Tracks whether the user is being inactive. + * @see {@link https://runed.dev/docs/utilities/is-idle} + */ +export declare class IsIdle { + #private; + constructor(_options?: IsIdleOptions); + get lastActive(): number; + get current(): boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..0e7ed34ba654292dd6919cf885794cbee16f9eaa --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.js @@ -0,0 +1,63 @@ +import { extract } from "../extract/index.js"; +import { useDebounce } from "../use-debounce/index.js"; +import { useEventListener } from "../use-event-listener/use-event-listener.svelte.js"; +import { defaultWindow, } from "../../internal/configurable-globals.js"; +const DEFAULT_EVENTS = [ + "keypress", + "mousemove", + "touchmove", + "click", + "scroll", +]; +const DEFAULT_OPTIONS = { + events: DEFAULT_EVENTS, + initialState: false, + timeout: 60000, +}; +/** + * Tracks whether the user is being inactive. + * @see {@link https://runed.dev/docs/utilities/is-idle} + */ +export class IsIdle { + #current = $state(false); + #lastActive = $state(Date.now()); + constructor(_options) { + const opts = { + ...DEFAULT_OPTIONS, + ..._options, + }; + const window = opts.window ?? defaultWindow; + const document = opts.document ?? window?.document; + const timeout = $derived(extract(opts.timeout)); + const events = $derived(extract(opts.events)); + const detectVisibilityChanges = $derived(extract(opts.detectVisibilityChanges)); + this.#current = opts.initialState; + const debouncedReset = useDebounce(() => { + this.#current = true; + }, () => timeout); + debouncedReset(); + const handleActivity = () => { + this.#current = false; + this.#lastActive = Date.now(); + debouncedReset(); + }; + useEventListener(() => window, events, () => { + handleActivity(); + }, { passive: true }); + $effect(() => { + if (!detectVisibilityChanges || !document) + return; + useEventListener(document, ["visibilitychange"], () => { + if (document.hidden) + return; + handleActivity(); + }); + }); + } + get lastActive() { + return this.#lastActive; + } + get current() { + return this.#current; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0ee7bc8bc6c6289d25e84288ece423f17b64d70 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/index.d.ts @@ -0,0 +1 @@ +export * from "./is-in-viewport.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b0ee7bc8bc6c6289d25e84288ece423f17b64d70 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/index.js @@ -0,0 +1 @@ +export * from "./is-in-viewport.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5db751e2f592043031e451ceca94b9b3d6570ee5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.d.ts @@ -0,0 +1,14 @@ +import type { ConfigurableWindow } from "../../internal/configurable-globals.js"; +import type { MaybeElementGetter } from "../../internal/types.js"; +import { type UseIntersectionObserverOptions } from "../use-intersection-observer/use-intersection-observer.svelte.js"; +export type IsInViewportOptions = ConfigurableWindow & UseIntersectionObserverOptions; +/** + * Tracks if an element is visible within the current viewport. + * + * @see {@link https://runed.dev/docs/utilities/is-in-viewport} + */ +export declare class IsInViewport { + #private; + constructor(node: MaybeElementGetter, options?: IsInViewportOptions); + get current(): boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..873b9dcf5645dab56e0c979a70d0c45569cf4a73 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.js @@ -0,0 +1,25 @@ +import { useIntersectionObserver, } from "../use-intersection-observer/use-intersection-observer.svelte.js"; +/** + * Tracks if an element is visible within the current viewport. + * + * @see {@link https://runed.dev/docs/utilities/is-in-viewport} + */ +export class IsInViewport { + #isInViewport = $state(false); + constructor(node, options) { + useIntersectionObserver(node, (intersectionObserverEntries) => { + let isIntersecting = this.#isInViewport; + let latestTime = 0; + for (const entry of intersectionObserverEntries) { + if (entry.time >= latestTime) { + latestTime = entry.time; + isIntersecting = entry.isIntersecting; + } + } + this.#isInViewport = isIntersecting; + }, options); + } + get current() { + return this.#isInViewport; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c573eaaf0f24f0bbea130330c640886c1ee875e0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/index.d.ts @@ -0,0 +1 @@ +export * from "./is-mounted.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c573eaaf0f24f0bbea130330c640886c1ee875e0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/index.js @@ -0,0 +1 @@ +export * from "./is-mounted.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ce167152a074e1b8892da99fe63b5535db07102 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.d.ts @@ -0,0 +1,11 @@ +/** + * Returns an object with the mounted state of the component + * that invokes this function. + * + * @see {@link https://runed.dev/docs/utilities/is-mounted} + */ +export declare class IsMounted { + #private; + constructor(); + get current(): boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..eb7a3111f28955e3b92f131cd90a35526b93ccdd --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.js @@ -0,0 +1,21 @@ +import { untrack } from "svelte"; +/** + * Returns an object with the mounted state of the component + * that invokes this function. + * + * @see {@link https://runed.dev/docs/utilities/is-mounted} + */ +export class IsMounted { + #isMounted = $state(false); + constructor() { + $effect(() => { + untrack(() => (this.#isMounted = true)); + return () => { + this.#isMounted = false; + }; + }); + } + get current() { + return this.#isMounted; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e83b9fe4f3a1b0aca68648e60a91097b93ac7f33 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/index.d.ts @@ -0,0 +1 @@ +export * from "./on-click-outside.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e83b9fe4f3a1b0aca68648e60a91097b93ac7f33 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/index.js @@ -0,0 +1 @@ +export * from "./on-click-outside.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a451b7e0ac46aa665dd5a80b894616132c798da --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.d.ts @@ -0,0 +1,63 @@ +import { type ConfigurableDocument, type ConfigurableWindow } from "../../internal/configurable-globals.js"; +import type { MaybeElementGetter } from "../../internal/types.js"; +export type OnClickOutsideOptions = ConfigurableWindow & ConfigurableDocument & { + /** + * Whether the click outside handler is enabled by default or not. + * If set to false, the handler will not be active until enabled by + * calling the returned `start` function + * + * @default true + */ + immediate?: boolean; + /** + * Controls whether focus events from iframes trigger the callback. + * + * Since iframe click events don't bubble to the parent document, + * you may want to enable this if you need to detect when users + * interact with iframe content. + * + * @default false + */ + detectIframe?: boolean; +}; +/** + * A utility that calls a given callback when a click event occurs outside of + * a specified container element. + * + * @template T - The type of the container element, defaults to HTMLElement. + * @param {MaybeElementGetter} container - The container element or a getter function that returns the container element. + * @param {() => void} callback - The callback function to call when a click event occurs outside of the container. + * @param {OnClickOutsideOptions} [opts={}] - Optional configuration object. + * @param {ConfigurableDocument} [opts.document=defaultDocument] - The document object to use, defaults to the global document. + * @param {boolean} [opts.immediate=true] - Whether the click outside handler is enabled by default or not. + * @param {boolean} [opts.detectIframe=false] - Controls whether focus events from iframes trigger the callback. + * + * @example + * ```svelte + * + * + *
+ * Inside + *
+ * + * + * + * Enabled: {clickOutside.enabled} + *``` + * @see {@link https://runed.dev/docs/utilities/on-click-outside} + */ +export declare function onClickOutside(container: MaybeElementGetter, callback: (event: PointerEvent | FocusEvent) => void, opts?: OnClickOutsideOptions): { + /** Stop listening for click events outside the container. */ + stop: () => boolean; + /** Start listening for click events outside the container. */ + start: () => boolean; + /** Whether the click outside handler is currently enabled or not. */ + readonly enabled: boolean; +}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..f0676a36a12c980e729a2bc88b836b71635c5b39 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.js @@ -0,0 +1,182 @@ +import { defaultWindow, } from "../../internal/configurable-globals.js"; +import { getActiveElement, getOwnerDocument, isOrContainsTarget } from "../../internal/utils/dom.js"; +import { noop } from "../../internal/utils/function.js"; +import { isElement } from "../../internal/utils/is.js"; +import { sleep } from "../../internal/utils/sleep.js"; +import { on } from "svelte/events"; +import { extract } from "../extract/extract.svelte.js"; +import { useDebounce } from "../use-debounce/use-debounce.svelte.js"; +import { watch } from "../watch/watch.svelte.js"; +/** + * A utility that calls a given callback when a click event occurs outside of + * a specified container element. + * + * @template T - The type of the container element, defaults to HTMLElement. + * @param {MaybeElementGetter} container - The container element or a getter function that returns the container element. + * @param {() => void} callback - The callback function to call when a click event occurs outside of the container. + * @param {OnClickOutsideOptions} [opts={}] - Optional configuration object. + * @param {ConfigurableDocument} [opts.document=defaultDocument] - The document object to use, defaults to the global document. + * @param {boolean} [opts.immediate=true] - Whether the click outside handler is enabled by default or not. + * @param {boolean} [opts.detectIframe=false] - Controls whether focus events from iframes trigger the callback. + * + * @example + * ```svelte + * + * + *
+ * Inside + *
+ * + * + * + * Enabled: {clickOutside.enabled} + *``` + * @see {@link https://runed.dev/docs/utilities/on-click-outside} + */ +export function onClickOutside(container, callback, opts = {}) { + const { window = defaultWindow, immediate = true, detectIframe = false } = opts; + const document = opts.document ?? window?.document; + const node = $derived(extract(container)); + const nodeOwnerDocument = $derived(getOwnerDocument(node, document)); + let enabled = $state(immediate); + let pointerDownIntercepted = false; + let removeClickListener = noop; + let removeListeners = noop; + const handleClickOutside = useDebounce((e) => { + if (!node || !nodeOwnerDocument) { + removeClickListener(); + return; + } + if (pointerDownIntercepted === true || !isValidEvent(e, node, nodeOwnerDocument)) { + removeClickListener(); + return; + } + if (e.pointerType === "touch") { + /** + * If the pointer type is touch, we add a listener to wait for the click + * event that will follow the pointerdown event if the user interacts in a way + * that would trigger a click event. + * + * This prevents us from prematurely calling the callback if the user is simply + * scrolling or dragging the page. + */ + removeClickListener(); + removeClickListener = on(nodeOwnerDocument, "click", () => callback(e), { + once: true, + }); + } + else { + /** + * If the pointer type is not touch, we can directly call the callback function + * as the interaction is likely a mouse or pen input which does not require + * additional handling. + */ + callback(e); + } + }, 10); + function addListeners() { + if (!nodeOwnerDocument || !window || !node) + return noop; + const events = [ + /** + * CAPTURE INTERACTION START + * Mark the pointerdown event as intercepted to indicate that an interaction + * has started. This helps in distinguishing between valid and invalid events. + */ + on(nodeOwnerDocument, "pointerdown", (e) => { + if (isValidEvent(e, node, nodeOwnerDocument)) { + pointerDownIntercepted = true; + } + }, { capture: true }), + /** + * BUBBLE INTERACTION START + * Mark the pointerdown event as non-intercepted. Debounce `handleClickOutside` to + * avoid prematurely checking if other events were intercepted. + */ + on(nodeOwnerDocument, "pointerdown", (e) => { + pointerDownIntercepted = false; + handleClickOutside(e); + }), + ]; + if (detectIframe) { + events.push( + /** + * DETECT IFRAME INTERACTIONS + * + * We add a blur event listener to the window to detect when the user + * interacts with an iframe. If the active element is an iframe and it + * is not a descendant of the container, we call the callback function. + */ + on(window, "blur", async (e) => { + await sleep(); + const activeElement = getActiveElement(nodeOwnerDocument); + if (activeElement?.tagName === "IFRAME" && !isOrContainsTarget(node, activeElement)) { + callback(e); + } + })); + } + return () => { + for (const event of events) { + event(); + } + }; + } + function cleanup() { + pointerDownIntercepted = false; + handleClickOutside.cancel(); + removeClickListener(); + removeListeners(); + } + watch([() => enabled, () => node], ([enabled$, node$]) => { + if (enabled$ && node$) { + removeListeners(); + removeListeners = addListeners(); + } + else { + cleanup(); + } + }); + $effect(() => { + return () => { + cleanup(); + }; + }); + return { + /** Stop listening for click events outside the container. */ + stop: () => (enabled = false), + /** Start listening for click events outside the container. */ + start: () => (enabled = true), + /** Whether the click outside handler is currently enabled or not. */ + get enabled() { + return enabled; + }, + }; +} +function isValidEvent(e, container, defaultDocument) { + if ("button" in e && e.button > 0) + return false; + const target = e.target; + if (!isElement(target)) + return false; + const ownerDocument = getOwnerDocument(target, defaultDocument); + if (!ownerDocument) + return false; + // handle the case where a user may have pressed a pseudo element by + // checking the bounding rect of the container + if (target === container) { + const rect = container.getBoundingClientRect(); + const wasInsideClick = rect.top <= e.clientY && + e.clientY <= rect.top + rect.height && + rect.left <= e.clientX && + e.clientX <= rect.left + rect.width; + return !wasInsideClick; + } + return ownerDocument.documentElement.contains(target) && !isOrContainsTarget(container, target); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..062847f8f6ed8dbc4ff2d684a953e6b3bb67bce8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/index.d.ts @@ -0,0 +1 @@ +export * from "./persisted-state.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/index.js new file mode 100644 index 0000000000000000000000000000000000000000..062847f8f6ed8dbc4ff2d684a953e6b3bb67bce8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/index.js @@ -0,0 +1 @@ +export * from "./persisted-state.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84f1d33d88a8be3eb087c258f5fd49bceb1e4a98 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.d.ts @@ -0,0 +1,29 @@ +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +type Serializer = { + serialize: (value: T) => string; + deserialize: (value: string) => T | undefined; +}; +type StorageType = "local" | "session"; +type PersistedStateOptions = { + /** The storage type to use. Defaults to `local`. */ + storage?: StorageType; + /** The serializer to use. Defaults to `JSON.stringify` and `JSON.parse`. */ + serializer?: Serializer; + /** Whether to sync with the state changes from other tabs. Defaults to `true`. */ + syncTabs?: boolean; +} & ConfigurableWindow; +/** + * Creates reactive state that is persisted and synchronized across browser sessions and tabs using Web Storage. + * @param key The unique key used to store the state in the storage. + * @param initialValue The initial value of the state if not already present in the storage. + * @param options Configuration options including storage type, serializer for complex data types, and whether to sync state changes across tabs. + * + * @see {@link https://runed.dev/docs/utilities/persisted-state} + */ +export declare class PersistedState { + #private; + constructor(key: string, initialValue: T, options?: PersistedStateOptions); + get current(): T; + set current(newValue: T); +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..48ad7bef1502528edef9a3ef0a9bcc9f50fec24a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.js @@ -0,0 +1,107 @@ +import { defaultWindow } from "../../internal/configurable-globals.js"; +import { on } from "svelte/events"; +import { createSubscriber } from "svelte/reactivity"; +function getStorage(storageType, window) { + switch (storageType) { + case "local": + return window.localStorage; + case "session": + return window.sessionStorage; + } +} +/** + * Creates reactive state that is persisted and synchronized across browser sessions and tabs using Web Storage. + * @param key The unique key used to store the state in the storage. + * @param initialValue The initial value of the state if not already present in the storage. + * @param options Configuration options including storage type, serializer for complex data types, and whether to sync state changes across tabs. + * + * @see {@link https://runed.dev/docs/utilities/persisted-state} + */ +export class PersistedState { + #current; + #key; + #serializer; + #storage; + #subscribe; + #version = $state(0); + constructor(key, initialValue, options = {}) { + const { storage: storageType = "local", serializer = { serialize: JSON.stringify, deserialize: JSON.parse }, syncTabs = true, window = defaultWindow, } = options; + this.#current = initialValue; + this.#key = key; + this.#serializer = serializer; + if (window === undefined) + return; + const storage = getStorage(storageType, window); + this.#storage = storage; + const existingValue = storage.getItem(key); + if (existingValue !== null) { + this.#current = this.#deserialize(existingValue); + } + else { + this.#serialize(initialValue); + } + if (syncTabs && storageType === "local") { + this.#subscribe = createSubscriber(() => { + return on(window, "storage", this.#handleStorageEvent); + }); + } + } + get current() { + this.#subscribe?.(); + this.#version; + const root = this.#deserialize(this.#storage?.getItem(this.#key)) ?? this.#current; + const proxies = new WeakMap(); + const proxy = (value) => { + if (value === null || value?.constructor.name === "Date" || typeof value !== "object") { + return value; + } + let p = proxies.get(value); + if (!p) { + p = new Proxy(value, { + get: (target, property) => { + this.#version; + return proxy(Reflect.get(target, property)); + }, + set: (target, property, value) => { + this.#version += 1; + Reflect.set(target, property, value); + this.#serialize(root); + return true; + }, + }); + proxies.set(value, p); + } + return p; + }; + return proxy(root); + } + set current(newValue) { + this.#serialize(newValue); + this.#version += 1; + } + #handleStorageEvent = (event) => { + if (event.key !== this.#key || event.newValue === null) + return; + this.#current = this.#deserialize(event.newValue); + this.#version += 1; + }; + #deserialize(value) { + try { + return this.#serializer.deserialize(value); + } + catch (error) { + console.error(`Error when parsing "${value}" from persisted store "${this.#key}"`, error); + return; + } + } + #serialize(value) { + try { + if (value != undefined) { + this.#storage?.setItem(this.#key, this.#serializer.serialize(value)); + } + } + catch (error) { + console.error(`Error when writing value from persisted store "${this.#key}" to ${this.#storage}`, error); + } + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cb62f38dfe730ed6f31d39c6e3c8e45eaf46ed5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/index.d.ts @@ -0,0 +1 @@ +export { PressedKeys } from "./pressed-keys.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8cb62f38dfe730ed6f31d39c6e3c8e45eaf46ed5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/index.js @@ -0,0 +1 @@ +export { PressedKeys } from "./pressed-keys.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f662c8d2ecd14c02aacf7ed8a4db3d5b542153dd --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.d.ts @@ -0,0 +1,13 @@ +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export type PressedKeysOptions = ConfigurableWindow; +/** + * Tracks which keys are currently pressed. + * + * @see {@link https://runed.dev/docs/utilities/pressed-keys} + */ +export declare class PressedKeys { + #private; + constructor(options?: PressedKeysOptions); + has(...keys: string[]): boolean; + get all(): string[]; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..4ac6a0c7cee12d3976093d8a3e85fc5a3a607d4c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.js @@ -0,0 +1,33 @@ +import { defaultWindow } from "../../internal/configurable-globals.js"; +import { useEventListener } from "../use-event-listener/use-event-listener.svelte.js"; +/** + * Tracks which keys are currently pressed. + * + * @see {@link https://runed.dev/docs/utilities/pressed-keys} + */ +export class PressedKeys { + #pressedKeys = $state([]); + constructor(options = {}) { + const { window = defaultWindow } = options; + this.has = this.has.bind(this); + if (!window) + return; + useEventListener(window, "keydown", (e) => { + const key = e.key.toLowerCase(); + if (!this.#pressedKeys.includes(key)) { + this.#pressedKeys.push(key); + } + }); + useEventListener(window, "keyup", (e) => { + const key = e.key.toLowerCase(); + this.#pressedKeys = this.#pressedKeys.filter((k) => k !== key); + }); + } + has(...keys) { + const normalizedKeys = keys.map((key) => key.toLowerCase()); + return normalizedKeys.every((key) => this.#pressedKeys.includes(key)); + } + get all() { + return this.#pressedKeys; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c45eae4698060fb949ee0e56ccc6ea6a72f3603 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/index.d.ts @@ -0,0 +1 @@ +export * from "./previous.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9c45eae4698060fb949ee0e56ccc6ea6a72f3603 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/index.js @@ -0,0 +1 @@ +export * from "./previous.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/previous.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/previous.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a1f71c10b278cd680b1a66404792aa123c73c7fa --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/previous.svelte.d.ts @@ -0,0 +1,11 @@ +import type { Getter } from "../../internal/types.js"; +/** + * Holds the previous value of a getter. + * + * @see {@link https://runed.dev/docs/utilities/previous} + */ +export declare class Previous { + #private; + constructor(getter: Getter, initialValue?: T); + get current(): T | undefined; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/previous.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/previous.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..26b5028d521a36e7b639725b2d8bc41941b902b6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/previous/previous.svelte.js @@ -0,0 +1,19 @@ +import { watch } from "../watch/watch.svelte.js"; +/** + * Holds the previous value of a getter. + * + * @see {@link https://runed.dev/docs/utilities/previous} + */ +export class Previous { + #previous = $state(undefined); + constructor(getter, initialValue) { + if (initialValue !== undefined) + this.#previous = initialValue; + watch(() => getter(), (_, v) => { + this.#previous = v; + }); + } + get current() { + return this.#previous; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..78b847d046f4edd53bafb7c85f8deba71b4471be --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/index.d.ts @@ -0,0 +1 @@ +export * from "./resource.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/index.js new file mode 100644 index 0000000000000000000000000000000000000000..78b847d046f4edd53bafb7c85f8deba71b4471be --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/index.js @@ -0,0 +1 @@ +export * from "./resource.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/msw-handlers.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/msw-handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f55c8f8334a7767a6ac9046b28c4767e2032021a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/msw-handlers.d.ts @@ -0,0 +1,14 @@ +export type ResponseData = { + id: number; + name: string; + email: string; +}; +export type SearchResponseData = { + results: { + id: number; + title: string; + }[]; + page: number; + total: number; +}; +export declare const handlers: import("msw").HttpHandler[]; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/msw-handlers.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/msw-handlers.js new file mode 100644 index 0000000000000000000000000000000000000000..55c9a3e2e79e1a8c4d5854088c1b5ef3ecf7f497 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/msw-handlers.js @@ -0,0 +1,30 @@ +import { http, delay, HttpResponse } from "msw"; +export const handlers = [ + // Basic user endpoint + http.get("https://api.example.com/users/:id", async ({ params }) => { + await delay(50); + return HttpResponse.json({ + id: Number(params.id), + name: `User ${params.id}`, + email: `user${params.id}@example.com`, + }); + }), + // Search endpoint with query params + http.get("https://api.example.com/search", ({ request }) => { + const url = new URL(request.url); + const query = url.searchParams.get("q"); + const page = Number(url.searchParams.get("page")) || 1; + return HttpResponse.json({ + results: [ + { id: page * 1, title: `Result 1 for ${query}` }, + { id: page * 2, title: `Result 2 for ${query}` }, + ], + page, + total: 10, + }); + }), + // Endpoint that can fail + http.get("https://api.example.com/error-prone", () => { + return new HttpResponse(null, { status: 500 }); + }), +]; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/resource.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/resource.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..07a9414af2af0c7eb4cfb7f20b9564b18c3f8b30 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/resource.svelte.d.ts @@ -0,0 +1,147 @@ +import type { Getter } from "../../internal/types.js"; +/** + * Configuration options for the resource function + */ +export type ResourceOptions = { + /** Skip initial fetch when true */ + lazy?: boolean; + /** Only fetch once when true */ + once?: boolean; + /** Initial value for the resource */ + initialValue?: Data; + /** Debounce time in milliseconds */ + debounce?: number; + /** Throttle time in milliseconds */ + throttle?: number; +}; +/** + * Core state of a resource + */ +export type ResourceState = { + /** Current value of the resource */ + current: HasInitialValue extends true ? Data : Data | undefined; + /** Whether the resource is currently loading */ + loading: boolean; + /** Error if the fetch failed */ + error: Error | undefined; +}; +/** + * Return type of the resource function, extends ResourceState with additional methods + */ +export type ResourceReturn = ResourceState & { + /** Update the resource value directly */ + mutate: (value: Data) => void; + /** Re-run the fetcher with current values */ + refetch: (info?: RefetchInfo) => Promise; +}; +export type ResourceFetcherRefetchInfo = { + /** Previous data return from fetcher */ + data: Data | undefined; + /** Whether the fetcher is currently refetching or it can be the value you passed to refetch. */ + refetching: RefetchInfo | boolean; + /** A cleanup function that will be called when the source is invalidated and the fetcher is about to re-run */ + onCleanup: (fn: () => void) => void; + /** AbortSignal for cancelling fetch requests */ + signal: AbortSignal; +}; +export type ResourceFetcher = ( +/** Current value of the source */ +value: Source extends Array ? { + [K in keyof Source]: Source[K]; +} : Source, +/** Previous value of the source */ +previousValue: Source extends Array ? { + [K in keyof Source]: Source[K]; +} : Source | undefined, info: ResourceFetcherRefetchInfo) => Promise; +/** + * Creates a reactive resource that combines reactive dependency tracking with async data fetching. + * This version uses watch under the hood and runs after render. + * For pre-render execution, use resource.pre(). + * + * Features: + * - Automatic request cancellation when dependencies change + * - Built-in loading and error states + * - Support for initial values and lazy loading + * - Type-safe reactive dependencies + * + * @example + * ```typescript + * // Basic usage with automatic request cancellation + * const userResource = resource( + * () => userId, + * async (newId, prevId, { signal }) => { + * const res = await fetch(`/api/users/${newId}`, { signal }); + * return res.json(); + * } + * ); + * + * // Multiple dependencies + * const searchResource = resource( + * [() => query, () => page], + * async ([query, page], [prevQuery, prevPage], { signal }) => { + * const res = await fetch( + * `/api/search?q=${query}&page=${page}`, + * { signal } + * ); + * return res.json(); + * }, + * { lazy: true } + * ); + * + * // Custom cleanup with built-in request cancellation + * const streamResource = resource( + * () => streamId, + * async (id, prevId, { signal, onCleanup }) => { + * const eventSource = new EventSource(`/api/stream/${id}`); + * onCleanup(() => eventSource.close()); + * + * const res = await fetch(`/api/stream/${id}/init`, { signal }); + * return res.json(); + * } + * ); + * ``` + */ +export declare function resource>, RefetchInfo> = ResourceFetcher>(source: Getter, fetcher: Fetcher, options: ResourceOptions>> & { + initialValue: Awaited>; +}): ResourceReturn>, RefetchInfo, true>; +export declare function resource>, RefetchInfo> = ResourceFetcher>(source: Getter, fetcher: Fetcher, options?: Omit>>, "initialValue">): ResourceReturn>, RefetchInfo, false>; +export declare function resource, RefetchInfo = unknown, Fetcher extends ResourceFetcher>, RefetchInfo> = ResourceFetcher>(sources: { + [K in keyof Sources]: Getter; +}, fetcher: Fetcher, options: ResourceOptions>> & { + initialValue: Awaited>; +}): ResourceReturn>, RefetchInfo, true>; +export declare function resource, RefetchInfo = unknown, Fetcher extends ResourceFetcher>, RefetchInfo> = ResourceFetcher>(sources: { + [K in keyof Sources]: Getter; +}, fetcher: Fetcher, options?: Omit>>, "initialValue">): ResourceReturn>, RefetchInfo, false>; +export declare namespace resource { + var pre: typeof resourcePre; +} +/** + * Helper function to create a resource with pre-effect (runs before render). + * Uses watch.pre internally instead of watch for pre-render execution. + * Includes all features of the standard resource including automatic request cancellation. + * + * @example + * ```typescript + * // Pre-render resource with automatic cancellation + * const data = resource.pre( + * () => query, + * async (newQuery, prevQuery, { signal }) => { + * const res = await fetch(`/api/search?q=${newQuery}`, { signal }); + * return res.json(); + * } + * ); + * ``` + */ +export declare function resourcePre>, RefetchInfo> = ResourceFetcher>(source: Getter, fetcher: Fetcher, options: ResourceOptions>> & { + initialValue: Awaited>; +}): ResourceReturn>, RefetchInfo, true>; +export declare function resourcePre>, RefetchInfo> = ResourceFetcher>(source: Getter, fetcher: Fetcher, options?: Omit>>, "initialValue">): ResourceReturn>, RefetchInfo, false>; +export declare function resourcePre, RefetchInfo = unknown, Fetcher extends ResourceFetcher>, RefetchInfo> = ResourceFetcher>(sources: { + [K in keyof Sources]: Getter; +}, fetcher: Fetcher, options: ResourceOptions>> & { + initialValue: Awaited>; +}): ResourceReturn>, RefetchInfo, true>; +export declare function resourcePre, RefetchInfo = unknown, Fetcher extends ResourceFetcher>, RefetchInfo> = ResourceFetcher>(sources: { + [K in keyof Sources]: Getter; +}, fetcher: Fetcher, options?: Omit>>, "initialValue">): ResourceReturn>, RefetchInfo, false>; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/resource.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/resource.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..8630915c3422327ea55f4b80c8af661a323b0907 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/resource/resource.svelte.js @@ -0,0 +1,143 @@ +import { watch } from "../watch/index.js"; +// Helper functions for debounce and throttle +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function debounce(fn, delay) { + let timeoutId; + let lastResolve = null; + return (...args) => { + return new Promise((resolve) => { + if (lastResolve) { + lastResolve(undefined); + } + lastResolve = resolve; + clearTimeout(timeoutId); + timeoutId = setTimeout(async () => { + const result = await fn(...args); + if (lastResolve) { + lastResolve(result); + lastResolve = null; + } + }, delay); + }); + }; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function throttle(fn, delay) { + let lastRun = 0; + let lastPromise = null; + return (...args) => { + const now = Date.now(); + if (lastRun && now - lastRun < delay) { + return lastPromise ?? Promise.resolve(undefined); + } + lastRun = now; + lastPromise = fn(...args); + return lastPromise; + }; +} +function runResource(source, fetcher, options = {}, effectFn) { + const { lazy = false, once = false, initialValue, debounce: debounceTime, throttle: throttleTime, } = options; + // Create state + let current = $state(initialValue); + let loading = $state(false); + let error = $state(undefined); + let cleanupFns = $state([]); + // Helper function to run cleanup functions + const runCleanup = () => { + cleanupFns.forEach((fn) => fn()); + cleanupFns = []; + }; + // Helper function to register cleanup + const onCleanup = (fn) => { + cleanupFns = [...cleanupFns, fn]; + }; + // Create the base fetcher function + const baseFetcher = async (value, previousValue, refetching = false) => { + try { + loading = true; + error = undefined; + runCleanup(); + // Create new AbortController for this fetch + const controller = new AbortController(); + onCleanup(() => controller.abort()); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = await fetcher(value, previousValue, { + data: current, + refetching, + onCleanup, + signal: controller.signal, + }); + current = result; + return result; + } + catch (e) { + if (!(e instanceof DOMException && e.name === "AbortError")) { + error = e; + } + return undefined; + } + finally { + loading = false; + } + }; + // Apply debounce or throttle if specified + const runFetcher = debounceTime + ? debounce(baseFetcher, debounceTime) + : throttleTime + ? throttle(baseFetcher, throttleTime) + : baseFetcher; + // Setup effect + const sources = Array.isArray(source) ? source : [source]; + let prevValues; + effectFn((values, previousValues) => { + // Skip if once and already ran + if (once && prevValues) { + return; + } + // Skip if values haven't changed + if (prevValues && JSON.stringify(values) === JSON.stringify(prevValues)) { + return; + } + prevValues = values; + runFetcher(Array.isArray(source) ? values : values[0], Array.isArray(source) ? previousValues : previousValues?.[0]); + }, { lazy }); + return { + get current() { + return current; + }, + get loading() { + return loading; + }, + get error() { + return error; + }, + mutate: (value) => { + current = value; + }, + refetch: (info) => { + const values = sources.map((s) => s()); + return runFetcher(Array.isArray(source) ? values : values[0], Array.isArray(source) ? values : values[0], info ?? true); + }, + }; +} +// Implementation +export function resource(source, fetcher, options) { + return runResource(source, fetcher, options, (fn, options) => { + const sources = Array.isArray(source) ? source : [source]; + const getters = () => sources.map((s) => s()); + watch(getters, (values, previousValues) => { + fn(values, previousValues ?? []); + }, options); + }); +} +// Implementation +export function resourcePre(source, fetcher, options) { + return runResource(source, fetcher, options, (fn, options) => { + const sources = Array.isArray(source) ? source : [source]; + const getter = () => sources.map((s) => s()); + watch.pre(getter, (values, previousValues) => { + fn(values, previousValues ?? []); + }, options); + }); +} +resource.pre = resourcePre; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0c4565df2f2a7394e4f4d405d57cd1f7dde9020 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/index.d.ts @@ -0,0 +1 @@ +export * from "./state-history.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a0c4565df2f2a7394e4f4d405d57cd1f7dde9020 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/index.js @@ -0,0 +1 @@ +export * from "./state-history.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/state-history.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/state-history.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92e599f1fc4c058055a2a0892007465850f9f8cb --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/state-history.svelte.d.ts @@ -0,0 +1,23 @@ +import type { MaybeGetter, Setter } from "../../internal/types.js"; +type LogEvent = { + snapshot: T; + timestamp: number; +}; +type StateHistoryOptions = { + capacity?: MaybeGetter; +}; +/** + * Tracks the change history of a value, providing undo and redo capabilities. + * + * @see {@link https://runed.dev/docs/utilities/state-history} + */ +export declare class StateHistory { + #private; + log: LogEvent[]; + readonly canUndo: boolean; + readonly canRedo: boolean; + constructor(value: MaybeGetter, set: Setter, options?: StateHistoryOptions); + undo(): void; + redo(): void; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/state-history.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/state-history.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..85bef0990d17a64b87653ff064949987c17fac75 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/state-history/state-history.svelte.js @@ -0,0 +1,58 @@ +import { watch } from "../watch/watch.svelte.js"; +import { get } from "../../internal/utils/get.js"; +/** + * Tracks the change history of a value, providing undo and redo capabilities. + * + * @see {@link https://runed.dev/docs/utilities/state-history} + */ +export class StateHistory { + #redoStack = $state([]); + #ignoreUpdate = false; + #set; + log = $state([]); + canUndo = $derived(this.log.length > 1); + canRedo = $derived(this.#redoStack.length > 0); + constructor(value, set, options) { + this.#redoStack = []; + this.#set = set; + this.undo = this.undo.bind(this); + this.redo = this.redo.bind(this); + const addEvent = (event) => { + this.log.push(event); + const capacity$ = get(options?.capacity); + if (capacity$ && this.log.length > capacity$) { + this.log = this.log.slice(-capacity$); + } + }; + watch(() => get(value), (v) => { + if (this.#ignoreUpdate) { + this.#ignoreUpdate = false; + return; + } + addEvent({ snapshot: v, timestamp: new Date().getTime() }); + this.#redoStack = []; + }); + watch(() => get(options?.capacity), (c) => { + if (!c) + return; + this.log = this.log.slice(-c); + }); + } + undo() { + const [prev, curr] = this.log.slice(-2); + if (!curr || !prev) + return; + this.#ignoreUpdate = true; + this.#redoStack.push(curr); + this.log.pop(); + this.#set(prev.snapshot); + } + redo() { + const nextEvent = this.#redoStack.pop(); + if (!nextEvent) + return; + this.#ignoreUpdate = true; + this.log.push(nextEvent); + this.#set(nextEvent.snapshot); + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b167be0bb339c67a97696ea8f29ffb16b0cf98a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/index.d.ts @@ -0,0 +1 @@ +export * from "./use-debounce.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1b167be0bb339c67a97696ea8f29ffb16b0cf98a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/index.js @@ -0,0 +1 @@ +export * from "./use-debounce.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6574037817e9ce4de7184309e62ae665e24b6968 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.d.ts @@ -0,0 +1,25 @@ +import type { MaybeGetter } from "../../internal/types.js"; +type UseDebounceReturn = ((this: unknown, ...args: Args) => Promise) & { + cancel: () => void; + runScheduledNow: () => Promise; + pending: boolean; +}; +/** + * Function that takes a callback, and returns a debounced version of it. + * When calling the debounced function, it will wait for the specified time + * before calling the original callback. If the debounced function is called + * again before the time has passed, the timer will be reset. + * + * You can await the debounced function to get the value when it is eventually + * called. + * + * The second parameter is the time to wait before calling the original callback. + * Alternatively, it can also be a getter function that returns the time to wait. + * + * @see {@link https://runed.dev/docs/utilities/use-debounce} + * + * @param callback The callback to call when the time has passed. + * @param wait The length of time to wait in ms, defaults to 250. + */ +export declare function useDebounce(callback: (...args: Args) => Return, wait?: MaybeGetter): UseDebounceReturn; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..02e09183d6b9d4e37a2171372807b1a46dfcf81b --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.js @@ -0,0 +1,90 @@ +/** + * Function that takes a callback, and returns a debounced version of it. + * When calling the debounced function, it will wait for the specified time + * before calling the original callback. If the debounced function is called + * again before the time has passed, the timer will be reset. + * + * You can await the debounced function to get the value when it is eventually + * called. + * + * The second parameter is the time to wait before calling the original callback. + * Alternatively, it can also be a getter function that returns the time to wait. + * + * @see {@link https://runed.dev/docs/utilities/use-debounce} + * + * @param callback The callback to call when the time has passed. + * @param wait The length of time to wait in ms, defaults to 250. + */ +export function useDebounce(callback, wait = 250) { + let context = $state(null); + function debounced(...args) { + if (context) { + // Old context will be reused so callers awaiting the promise will get the + // new value + if (context.timeout) { + clearTimeout(context.timeout); + } + } + else { + // No old context, create a new one + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + context = { + timeout: null, + runner: null, + promise, + resolve: resolve, + reject: reject, + }; + } + context.runner = async () => { + // Grab the context and reset it + // -> new debounced calls will create a new context + if (!context) + return; + const ctx = context; + context = null; + try { + ctx.resolve(await callback.apply(this, args)); + } + catch (error) { + ctx.reject(error); + } + }; + context.timeout = setTimeout(context.runner, typeof wait === "function" ? wait() : wait); + return context.promise; + } + debounced.cancel = async () => { + if (!context || context.timeout === null) { + // Wait one event loop to see if something triggered the debounced function + await new Promise((resolve) => setTimeout(resolve, 0)); + if (!context || context.timeout === null) + return; + } + clearTimeout(context.timeout); + context.reject("Cancelled"); + context = null; + }; + debounced.runScheduledNow = async () => { + if (!context || !context.timeout) { + // Wait one event loop to see if something triggered the debounced function + await new Promise((resolve) => setTimeout(resolve, 0)); + if (!context || !context.timeout) + return; + } + clearTimeout(context.timeout); + context.timeout = null; + await context.runner?.(); + }; + Object.defineProperty(debounced, "pending", { + enumerable: true, + get() { + return !!context?.timeout; + }, + }); + return debounced; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e5c0750c18a6e474dc17b914744f8171656f789 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/index.d.ts @@ -0,0 +1 @@ +export * from "./use-event-listener.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e5c0750c18a6e474dc17b914744f8171656f789 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/index.js @@ -0,0 +1 @@ +export * from "./use-event-listener.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b1ad3a5e55e40fa40abf21b376d009ba61ba23b --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts @@ -0,0 +1,51 @@ +import type { MaybeGetter } from "../../internal/types.js"; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: Window, event: WindowEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: Document, event: DocumentEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: TElement, event: HTMLElementEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: MediaQueryList, event: MediaQueryListEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: EventListener, options?: AddEventListenerOptions): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..9b0d63d149c5bd5cc52f0cb6b794e4725a223c5a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js @@ -0,0 +1,18 @@ +import { extract } from "../extract/extract.svelte.js"; +import { on } from "svelte/events"; +export function useEventListener(_target, _events, handler, options) { + $effect(() => { + const target = extract(_target); + const events = extract(_events); + if (target === undefined || target === null) + return; + if (Array.isArray(events)) { + for (const event of events) { + $effect(() => on(target, event, handler, options)); + } + } + else { + return on(target, events, handler, options); + } + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..17cc63e7f2e569664aa659e76dcef850cd75df88 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/index.d.ts @@ -0,0 +1 @@ +export * from "./use-geolocation.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/index.js new file mode 100644 index 0000000000000000000000000000000000000000..17cc63e7f2e569664aa659e76dcef850cd75df88 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/index.js @@ -0,0 +1 @@ +export * from "./use-geolocation.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ae0d88349aa12bce2eca22a77f003b5f4e983ac --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts @@ -0,0 +1,27 @@ +import { type ConfigurableNavigator } from "../../internal/configurable-globals.js"; +export type UseGeolocationOptions = Partial & { + /** + * Whether to start the watcher immediately upon creation. If set to `false`, the watcher + * will only start tracking the position when `resume()` is called. + * + * @defaultValue true + */ + immediate?: boolean; +} & ConfigurableNavigator; +export type UseGeolocationPosition = Omit & { + coords: Omit; +}; +export type UseGeolocationReturn = { + readonly isSupported: boolean; + readonly position: UseGeolocationPosition; + readonly error: GeolocationPositionError | null; + readonly isPaused: boolean; + resume: () => void; + pause: () => void; +}; +/** + * Reactive access to the browser's [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API). + * + * @see https://runed.dev/docs/utilities/use-geolocation + */ +export declare function useGeolocation(options?: UseGeolocationOptions): UseGeolocationReturn; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..9eba5e2fae69d022cac15d2c8435fc992948bf72 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js @@ -0,0 +1,71 @@ +import { defaultNavigator, } from "../../internal/configurable-globals.js"; +/** + * Reactive access to the browser's [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API). + * + * @see https://runed.dev/docs/utilities/use-geolocation + */ +export function useGeolocation(options = {}) { + const { enableHighAccuracy = true, maximumAge = 30000, timeout = 27000, immediate = true, navigator = defaultNavigator, } = options; + const isSupported = Boolean(navigator); + let error = $state.raw(null); + let position = $state({ + timestamp: 0, + coords: { + accuracy: 0, + latitude: Number.POSITIVE_INFINITY, + longitude: Number.POSITIVE_INFINITY, + altitude: null, + altitudeAccuracy: null, + heading: null, + speed: null, + }, + }); + let isPaused = $state(false); + function updatePosition(_position) { + error = null; + position.timestamp = _position.timestamp; + position.coords.accuracy = _position.coords.accuracy; + position.coords.altitude = _position.coords.altitude; + position.coords.altitudeAccuracy = _position.coords.altitudeAccuracy; + position.coords.heading = _position.coords.heading; + position.coords.latitude = _position.coords.latitude; + position.coords.longitude = _position.coords.longitude; + position.coords.speed = _position.coords.speed; + } + let watcher; + function resume() { + if (!navigator) + return; + watcher = navigator.geolocation.watchPosition(updatePosition, (err) => (error = err), { + enableHighAccuracy, + maximumAge, + timeout, + }); + isPaused = false; + } + function pause() { + if (watcher && navigator) { + navigator.geolocation.clearWatch(watcher); + } + isPaused = true; + } + $effect(() => { + if (immediate) + resume(); + return () => pause(); + }); + return { + get isSupported() { + return isSupported; + }, + position, + get error() { + return error; + }, + get isPaused() { + return isPaused; + }, + resume, + pause, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d972de5d99c4a3c9cab2abb66769e5f3f0c69cd8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts @@ -0,0 +1 @@ +export * from "./use-intersection-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d972de5d99c4a3c9cab2abb66769e5f3f0c69cd8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/index.js @@ -0,0 +1 @@ +export * from "./use-intersection-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57dba73ebc3a855eb8b5c26b447ac600bc46d66e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts @@ -0,0 +1,28 @@ +import type { MaybeElementGetter, MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface UseIntersectionObserverOptions extends Omit, ConfigurableWindow { + /** + * Whether to start the observer immediately upon creation. If set to `false`, the observer + * will only start observing when `resume()` is called. + * + * @defaultValue true + */ + immediate?: boolean; + /** + * The root document/element to use as the bounding box for the intersection. + */ + root?: MaybeElementGetter; +} +/** + * Watch for intersection changes of a target element. + * + * @see https://runed.dev/docs/utilities/useIntersectionObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver IntersectionObserver MDN + */ +export declare function useIntersectionObserver(target: MaybeGetter, callback: IntersectionObserverCallback, options?: UseIntersectionObserverOptions): { + readonly isActive: boolean; + stop: () => void; + pause(): void; + resume(): void; +}; +export type UseIntersectionObserverReturn = ReturnType; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..dfa5e4f6c93f80fce0f1a16ee3ee311d04216fbc --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js @@ -0,0 +1,49 @@ +import { extract } from "../extract/extract.svelte.js"; +import { get } from "../../internal/utils/get.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Watch for intersection changes of a target element. + * + * @see https://runed.dev/docs/utilities/useIntersectionObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver IntersectionObserver MDN + */ +export function useIntersectionObserver(target, callback, options = {}) { + const { root, rootMargin = "0px", threshold = 0.1, immediate = true, window = defaultWindow, } = options; + let isActive = $state(immediate); + let observer; + const targets = $derived.by(() => { + const value = extract(target); + return new Set(value ? (Array.isArray(value) ? value : [value]) : []); + }); + const stop = $effect.root(() => { + $effect(() => { + if (!targets.size || !isActive || !window) + return; + observer = new window.IntersectionObserver(callback, { + rootMargin, + root: get(root), + threshold, + }); + for (const el of targets) + observer.observe(el); + return () => { + observer?.disconnect(); + }; + }); + }); + $effect(() => { + return stop; + }); + return { + get isActive() { + return isActive; + }, + stop, + pause() { + isActive = false; + }, + resume() { + isActive = true; + }, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a9360150f5f5a38cf0110017aa3f1ccd8fb6734 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts @@ -0,0 +1 @@ +export * from "./use-mutation-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8a9360150f5f5a38cf0110017aa3f1ccd8fb6734 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/index.js @@ -0,0 +1 @@ +export * from "./use-mutation-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4f1a3c918d520792ca8074b7dcc8fd15442b82d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts @@ -0,0 +1,15 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface UseMutationObserverOptions extends MutationObserverInit, ConfigurableWindow { +} +/** + * Watch for changes being made to the DOM tree. + * + * @see https://runed.dev/docs/utilities/useMutationObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN + */ +export declare function useMutationObserver(target: MaybeGetter, callback: MutationCallback, options?: UseMutationObserverOptions): { + stop: () => void; + takeRecords(): MutationRecord[] | undefined; +}; +export type UseMutationObserverReturn = ReturnType; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..768f03cc6b3b5b4cbb9fe23763289b19ddc43f96 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js @@ -0,0 +1,38 @@ +import { extract } from "../extract/extract.svelte.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Watch for changes being made to the DOM tree. + * + * @see https://runed.dev/docs/utilities/useMutationObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN + */ +export function useMutationObserver(target, callback, options = {}) { + const { window = defaultWindow } = options; + let observer; + const targets = $derived.by(() => { + const value = extract(target); + return new Set(value ? (Array.isArray(value) ? value : [value]) : []); + }); + const stop = $effect.root(() => { + $effect(() => { + if (!targets.size || !window) + return; + observer = new window.MutationObserver(callback); + for (const el of targets) + observer.observe(el, options); + return () => { + observer?.disconnect(); + observer = undefined; + }; + }); + }); + $effect(() => { + return stop; + }); + return { + stop, + takeRecords() { + return observer?.takeRecords(); + }, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..532ba69de8269827446ce0d82bb285a491be3788 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts @@ -0,0 +1 @@ +export { useResizeObserver } from "./use-resize-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..532ba69de8269827446ce0d82bb285a491be3788 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/index.js @@ -0,0 +1 @@ +export { useResizeObserver } from "./use-resize-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84d0e1dd7155560149472040f3f249b60d78f1c4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts @@ -0,0 +1,39 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface ResizeObserverSize { + readonly inlineSize: number; + readonly blockSize: number; +} +export interface ResizeObserverEntry { + readonly target: Element; + readonly contentRect: DOMRectReadOnly; + readonly borderBoxSize?: ReadonlyArray; + readonly contentBoxSize?: ReadonlyArray; + readonly devicePixelContentBoxSize?: ReadonlyArray; +} +export type ResizeObserverCallback = (entries: ReadonlyArray, observer: ResizeObserver) => void; +export interface UseResizeObserverOptions extends ConfigurableWindow { + /** + * Sets which box model the observer will observe changes to. Possible values + * are `content-box` (the default), `border-box` and `device-pixel-content-box`. + * + * @default 'content-box' + */ + box?: ResizeObserverBoxOptions; +} +declare class ResizeObserver { + constructor(callback: ResizeObserverCallback); + disconnect(): void; + observe(target: Element, options?: UseResizeObserverOptions): void; + unobserve(target: Element): void; +} +/** + * Reports changes to the dimensions of an Element's content or the border-box + * + * @see https://runed.dev/docs/utilities/useResizeObserver + */ +export declare function useResizeObserver(target: MaybeGetter, callback: ResizeObserverCallback, options?: UseResizeObserverOptions): { + stop: () => void; +}; +export type UseResizeObserverReturn = ReturnType; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..177ab31cb0707d7a1a3e4c279dee50b50295f348 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js @@ -0,0 +1,34 @@ +import { extract } from "../extract/extract.svelte.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Reports changes to the dimensions of an Element's content or the border-box + * + * @see https://runed.dev/docs/utilities/useResizeObserver + */ +export function useResizeObserver(target, callback, options = {}) { + const { window = defaultWindow } = options; + let observer; + const targets = $derived.by(() => { + const value = extract(target); + return new Set(value ? (Array.isArray(value) ? value : [value]) : []); + }); + const stop = $effect.root(() => { + $effect(() => { + if (!targets.size || !window) + return; + observer = new window.ResizeObserver(callback); + for (const el of targets) + observer.observe(el, options); + return () => { + observer?.disconnect(); + observer = undefined; + }; + }); + }); + $effect(() => { + return stop; + }); + return { + stop, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58ed11fdce466c67f4ad5d6196d54e9e4f9046b9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/index.d.ts @@ -0,0 +1 @@ +export * from "./watch.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/index.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..58ed11fdce466c67f4ad5d6196d54e9e4f9046b9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/index.js @@ -0,0 +1 @@ +export * from "./watch.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b1e67b2afd2c3ee9c4b928af0c87194355b11e1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts @@ -0,0 +1,36 @@ +import type { Getter } from "../../internal/types.js"; +export type WatchOptions = { + /** + * If `true`, the effect doesn't run until one of the `sources` changes. + * + * @default false + */ + lazy?: boolean; +}; +export declare function watch>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: { + [K in keyof T]: T[K] | undefined; +}) => void | VoidFunction, options?: WatchOptions): void; +export declare function watch(source: Getter, effect: (value: T, previousValue: T | undefined) => void | VoidFunction, options?: WatchOptions): void; +export declare namespace watch { + var pre: typeof watchPre; +} +declare function watchPre>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: { + [K in keyof T]: T[K] | undefined; +}) => void | VoidFunction, options?: WatchOptions): void; +declare function watchPre(source: Getter, effect: (value: T, previousValue: T | undefined) => void | VoidFunction, options?: WatchOptions): void; +export declare function watchOnce>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: T) => void | VoidFunction): void; +export declare function watchOnce(source: Getter, effect: (value: T, previousValue: T) => void | VoidFunction): void; +export declare namespace watchOnce { + var pre: typeof watchOncePre; +} +declare function watchOncePre>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: T) => void | VoidFunction): void; +declare function watchOncePre(source: Getter, effect: (value: T, previousValue: T) => void | VoidFunction): void; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/watch.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/watch.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..5c01891565e1ed7f238e23e5240e3edcaa283d6c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/dist/utilities/watch/watch.svelte.js @@ -0,0 +1,69 @@ +import { untrack } from "svelte"; +function runEffect(flush, effect) { + switch (flush) { + case "post": + $effect(effect); + break; + case "pre": + $effect.pre(effect); + break; + } +} +function runWatcher(sources, flush, effect, options = {}) { + const { lazy = false } = options; + // Run the effect immediately if `lazy` is `false`. + let active = !lazy; + // On the first run, if the dependencies are an array, pass an empty array + // to the previous value instead of `undefined` to allow destructuring. + // + // watch(() => [a, b], ([a, b], [prevA, prevB]) => { ... }); + let previousValues = Array.isArray(sources) + ? [] + : undefined; + runEffect(flush, () => { + const values = Array.isArray(sources) ? sources.map((source) => source()) : sources(); + if (!active) { + active = true; + previousValues = values; + return; + } + const cleanup = untrack(() => effect(values, previousValues)); + previousValues = values; + return cleanup; + }); +} +function runWatcherOnce(sources, flush, effect) { + const cleanupRoot = $effect.root(() => { + let stop = false; + runWatcher(sources, flush, (values, previousValues) => { + if (stop) { + cleanupRoot(); + return; + } + // Since `lazy` is `true`, `previousValues` is always defined. + const cleanup = effect(values, previousValues); + stop = true; + return cleanup; + }, + // Running the effect immediately just once makes no sense at all. + // That's just `onMount` with extra steps. + { lazy: true }); + }); + $effect(() => { + return cleanupRoot; + }); +} +export function watch(sources, effect, options) { + runWatcher(sources, "post", effect, options); +} +function watchPre(sources, effect, options) { + runWatcher(sources, "pre", effect, options); +} +watch.pre = watchPre; +export function watchOnce(source, effect) { + runWatcherOnce(source, "post", effect); +} +function watchOncePre(source, effect) { + runWatcherOnce(source, "pre", effect); +} +watchOnce.pre = watchOncePre; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/runed/package.json b/tools/ui/node_modules/mode-watcher/node_modules/runed/package.json new file mode 100644 index 0000000000000000000000000000000000000000..55e8787a6e3c8dd3a56d4980871b7b218148ad91 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/runed/package.json @@ -0,0 +1,75 @@ +{ + "name": "runed", + "version": "0.25.0", + "type": "module", + "svelte": "./dist/index.js", + "types": "./dist/index.d.ts", + "contributors": [ + { + "name": "Thomas G. Lopes", + "url": "https://thomasglopes.com" + }, + { + "name": "Hunter Johnston", + "url": "https://x.com/huntabyte" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/svecosystem/runed", + "directory": "packages/runed" + }, + "funding": [ + "https://github.com/sponsors/huntabyte", + "https://github.com/sponsors/tglide" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "svelte": "./dist/index.js" + } + }, + "files": [ + "dist", + "!dist/**/*.test.*", + "!dist/**/*.spec.*" + ], + "peerDependencies": { + "svelte": "^5.7.0" + }, + "devDependencies": { + "@sveltejs/kit": "^2.5.3", + "@sveltejs/package": "^2.3.0", + "@sveltejs/vite-plugin-svelte": "4.0.0-next.7", + "@testing-library/dom": "^10.2.0", + "@testing-library/jest-dom": "^6.4.6", + "@testing-library/svelte": "^5.2.0", + "@testing-library/user-event": "^14.5.2", + "@types/node": "^20.10.6", + "@vitest/coverage-v8": "^1.5.1", + "@vitest/ui": "^1.6.0", + "jsdom": "^24.0.0", + "msw": "^2.7.0", + "publint": "^0.1.9", + "resize-observer-polyfill": "^1.5.1", + "svelte": "^5.11.0", + "svelte-check": "^4.1.1", + "tslib": "^2.4.1", + "typescript": "^5.0.0", + "vite": "^5.0.3", + "vitest": "^1.5.1" + }, + "dependencies": { + "esm-env": "^1.0.0" + }, + "scripts": { + "dev": "pnpm sync && pnpm watch", + "build": "pnpm package", + "package": "svelte-kit sync && svelte-package && publint", + "test": "vitest --run", + "test:watch": "vitest --watch", + "test:ui": "vitest --watch --ui", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "watch": "svelte-kit sync && svelte-package --watch" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/LICENSE b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..66fd878694f2e19172751731c8b903e5a047e7ef --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024 Hunter Johnston +Copyright (c) 2024 Thomas G. Lopes + +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. diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/README.md b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c99955a0468e1f566b7a29f6120383cebae15fa4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/README.md @@ -0,0 +1,423 @@ +# Svelte Toolbelt + +Utilities for Svelte 5 that I find useful and will use in the various projects I work on. It's maintained by me, for me. + +For more robust and feature-rich utilities, I recommend checking out/using [runed](https://runed.dev). + +## Installation + +```bash +npm install svelte-toolbelt +``` + +## Box + +### `box` + +Initializes a writable boxed state. + +```svelte + + + +``` + +### `box.with` + +Creates reactive state using getter and setter functions. If a setter function is provided, the box +is writable. If not, the box is readonly. + +Useful for passing synced reactive values across boundaries. + +```svelte + + + +``` + +### `box.from` + +Creates a box from an existing box, a getter function, or a static value. + +Useful for receiving arguments that may or may not be reactive. + +```svelte + +``` + +### `box.flatten` + +Transforms any boxes within an object to reactive properties, removing the need to access each +property with `.current`. + +```ts +const count = box(1); +const flat = box.flatten({ + count, + double: box.with(() => count.current * 2), + increment() { + count.current++; + } +}); + +console.log(flat.count); // 1 +console.log(flat.double); // 2 +flat.increment(); +console.log(flat.count); // 2 +``` + +### `box.readonly` + +Creates a readonly box from a writable box that remains in sync with the original box. + +```ts +const count = box(1); +const readonlyCount = box.readonly(count); +console.log(readonlyCount.current); // 1 +count.current++; +console.log(readonlyCount.current); // 2 + +readonlyCount.current = 3; // Error: Cannot assign to read only property 'value' of object +``` + +### `box.isBox` + +Checks if a value is a `Box`. + +```ts +const count = box(1); +console.log(box.isBox(count)); // true +console.log(box.isBox(1)); // false +``` + +### `box.isWritableBox` + +Checks if a value is a `WritableBox`. + +```ts +const count = box(1); +const double = box.with(() => count.current * 2); +console.log(box.isWritableBox(count)); // true +console.log(box.isWritableBox(double)); // false +``` + +### `unbox` + +Unboxes the value from a box. + +```ts +const count = box(1); +const double = box.with(() => count.current * 2); +console.log(unbox(double)); // 2 +``` + +## Utils + +### `afterSleep` + +Executes a callback after a specified number of milliseconds. + +```ts +afterSleep(1000, () => console.log("Hello, world!")); +``` + +### `afterTick` + +Executes a callback after the next tick. + +```ts +afterTick(() => console.log("Hello, world!")); +``` + +### `composeHandlers` + +Composes event handlers into a single function that can be called with an event. + +If the previous handler cancels the event using `event.preventDefault()`, the handlers +that follow will not be called. + +```ts +import { composeHandlers } from "svelte-toolbelt"; +const handler1 = () => console.log("Handler 1"); +const handler2 = () => console.log("Handler 2"); +const composedHandler = composeHandlers(handler1, handler2); +const event = new MouseEvent("click", { cancelable: true }); +console.log(composedHandler(event)); // Handler 1, Handler 2 +``` + +### `cssToStyleObj` + +Converts a CSS string to a style object. + +```ts +const css = "color: red; font-size: 16px;"; +const styleObj = cssToStyleObj(css); +console.log(styleObj); // { color: "red", fontSize: "16px" } +``` + +### `executeCallbacks` + +Executes an array of callback functions with the same arguments. + +```ts +const callback1 = () => console.log("Callback 1"); +const callback2 = () => console.log("Callback 2"); +console.log(executeCallbacks(callback1, callback2)); // Callback 1, Callback 2 +``` + +### `addEventListener` + +Adds an event listener to the specified target element(s) for the given event(s), and returns a function to remove it. + +```ts +import { addEventListener } from "svelte-toolbelt"; +const target = document.getElementById("my-element"); +const event = "click"; +const handler = () => console.log("Clicked!"); +const removeListener = addEventListener(target, event, handler); + +// Later, remove the listener +removeListener(); +``` + +### `mergeProps` + +Merges props into a single object. + +```ts +import { mergeProps } from "svelte-toolbelt"; +const props1 = { a: 1 }; +const props2 = { b: 2 }; +const result = mergeProps(props1, props2); +console.log(result); // { a: 1, b: 2 } +``` + +#### Event Handlers + +Event handlers are chained in the order they're passed. If a handler calls `event.preventDefault()`, subsequent handlers in the chain are not executed. + +```ts +const props1 = { onclick: (e: MouseEvent) => console.log("First click") }; +const props2 = { onclick: (e: MouseEvent) => console.log("Second click") }; + +const mergedProps = mergeProps(props1, props2); +mergedProps.onclick(new MouseEvent("click")); // Logs: "First click" then "Second click" +``` + +If `preventDefault()` is called: + +```ts +const props1 = { onclick: (e: MouseEvent) => console.log("First click") }; +const props2 = { + onclick: (e: MouseEvent) => { + console.log("Second click"); + e.preventDefault(); + } +}; +const props3 = { onclick: (e: MouseEvent) => console.log("Third click") }; + +const mergedProps = mergeProps(props1, props2, props3); +mergedProps.onclick(new MouseEvent("click")); // Logs: "First click" then "Second click" only +``` + +Since `props2` called `event.preventDefault()`, `props3`'s `onclick` handler will not be called. + +#### Non-Event Handler Functions + +Non-event handler functions are also chained, but without the ability to prevent subsequent functions from executing: + +```ts +const props1 = { doSomething: () => console.log("Action 1") }; +const props2 = { doSomething: () => console.log("Action 2") }; + +const mergedProps = mergeProps(props1, props2); +mergedProps.doSomething(); // Logs: "Action 1" then "Action 2" +``` + +#### Classes + +Class names are merged using [`clsx`](https://www.npmjs.com/package/clsx): + +```ts +const props1 = { class: "text-lg font-bold" }; +const props2 = { class: ["bg-blue-500", "hover:bg-blue-600"] }; + +const mergedProps = mergeProps(props1, props2); +console.log(mergedProps.class); // "text-lg font-bold bg-blue-500 hover:bg-blue-600" +``` + +#### Styles + +Style objects and strings are merged, with later properties overriding earlier ones: + +```ts +const props1 = { style: { color: "red", fontSize: "16px" } }; +const props2 = { style: "background-color: blue; font-weight: bold;" }; + +const mergedProps = mergeProps(props1, props2); +console.log(mergedProps.style); +// "color: red; font-size: 16px; background-color: blue; font-weight: bold;" +``` + +```ts +import { mergeProps } from "bits-ui"; + +const props1 = { style: "--foo: red" }; +const props2 = { style: { "--foo": "green", color: "blue" } }; + +const mergedProps = mergeProps(props1, props2); + +console.log(mergedProps.style); // "--foo: green; color: blue;" +``` + +### `onDestroyEffect` + +Executes a callback when a component is destroyed. + +### `onMountEffect` + +Executes a callback when a component is mounted. + +### `styleToString` + +Converts a style object to a CSS string. + +```ts +const style = { color: "red", fontSize: "16px" }; +const css = styleToString(style); +console.log(css); // "color: red; font-size: 16px;" +``` + +### `srOnlyStyles` + +An object of styles that can be used to hide content from the DOM but still be accessible to screen readers. + +```ts +export const srOnlyStyles: StyleProperties = { + position: "absolute", + width: "1px", + height: "1px", + padding: "0", + margin: "-1px", + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + borderWidth: "0", + transform: "translateX(-100%)" +}; +``` + +### `srOnlyStylesString` + +A string representation of `srOnlyStyles`. + +### `useRefById` + +Finds the node with the given boxed `id` and sets it to the boxed `ref`. Reactive using `$effect` to ensure when the `id` or `deps` change, an update is triggered and the node is re-found. + +#### Props + +```ts +type UseRefByIdProps = { + /** + * The ID of the node to find. + */ + id: Box; + + /** + * The ref to set the node to. + */ + ref: WritableBox; + + /** + * A reactive condition that will cause the node to be set. + */ + deps?: Getter; + + /** + * A callback fired when the ref changes. + */ + onRefChange?: (node: HTMLElement | null) => void; + + /** + * A function that returns the root node to search for the element by ID. + * Defaults to `() => (typeof document !== "undefined" ? document : undefined) + */ + getRootNode?: Getter; +}; +``` + +### `useOnChange` + +A simple helper function to react to changes to reactive state. This is useful for syncing a read-only dependency that may change with some writable state in your app. + +```svelte + +``` diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/box/box.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/box/box.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7b8365b0fb81f172b16abb18ad3c3e461c38a03e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/box/box.svelte.d.ts @@ -0,0 +1,106 @@ +import type { Expand, Getter, MaybeBoxOrGetter } from "../types.js"; +declare const BoxSymbol: unique symbol; +declare const isWritableSymbol: unique symbol; +export type ReadableBox = { + readonly [BoxSymbol]: true; + readonly current: T; +}; +export type WritableBox = ReadableBox & { + readonly [isWritableSymbol]: true; + current: T; +}; +/** + * Creates a writable box. + * + * @returns A box with a `current` property which can be set to a new value. + * Useful to pass state to other functions. + * + * @see {@link https://runed.dev/docs/functions/box} + */ +export declare function box(): WritableBox; +/** + * Creates a writable box with an initial value. + * + * @param initialValue The initial value of the box. + * @returns A box with a `current` property which can be set to a new value. + * Useful to pass state to other functions. + * + * @see {@link https://runed.dev/docs/functions/box} + */ +export declare function box(initialValue: T): WritableBox; +export declare namespace box { + export var from: typeof boxFrom; + var _a: typeof boxWith; + export var flatten: typeof boxFlatten; + export var readonly: typeof toReadonlyBox; + export var isBox: (value: unknown) => value is ReadableBox; + export var isWritableBox: (value: unknown) => value is WritableBox; + export { _a as with }; +} +/** + * Creates a readonly box + * + * @param getter Function to get the value of the box + * @returns A box with a `current` property whose value is the result of the getter. + * Useful to pass state to other functions. + * + * @see {@link https://runed.dev/docs/functions/box} + */ +declare function boxWith(getter: () => T): ReadableBox; +/** + * Creates a writable box + * + * @param getter Function to get the value of the box + * @param setter Function to set the value of the box + * @returns A box with a `current` property which can be set to a new value. + * Useful to pass state to other functions. + * + * @see {@link https://runed.dev/docs/functions/box} + */ +declare function boxWith(getter: () => T, setter: (v: T) => void): WritableBox; +/** + * Creates a box from either a static value, a box, or a getter function. + * Useful when you want to receive any of these types of values and generate a boxed version of it. + * + * @returns A box with a `current` property whose value. + * + * @see {@link https://runed.dev/docs/functions/box} + */ +declare function boxFrom(value: T | WritableBox): WritableBox; +declare function boxFrom(value: ReadableBox): ReadableBox; +declare function boxFrom(value: Getter): ReadableBox; +declare function boxFrom(value: MaybeBoxOrGetter): ReadableBox; +declare function boxFrom(value: T): WritableBox; +type GetKeys = { + [K in keyof T]: T[K] extends U ? K : never; +}[keyof T]; +type RemoveValues = Omit>; +type BoxFlatten> = Expand ? T : never; +}, never> & RemoveValues<{ + readonly [K in keyof R]: R[K] extends WritableBox ? never : R[K] extends ReadableBox ? T : never; +}, never>> & RemoveValues<{ + [K in keyof R]: R[K] extends ReadableBox ? never : R[K]; +}, never>; +/** + * Function that gets an object of boxes, and returns an object of reactive values + * + * @example + * const count = box(0) + * const flat = box.flatten({ count, double: box.with(() => count.current) }) + * // type of flat is { count: number, readonly double: number } + * + * @see {@link https://runed.dev/docs/functions/box} + */ +declare function boxFlatten>(boxes: R): BoxFlatten; +/** + * Function that converts a box to a readonly box. + * + * @example + * const count = box(0) // WritableBox + * const countReadonly = box.readonly(count) // ReadableBox + * + * @see {@link https://runed.dev/docs/functions/box} + */ +declare function toReadonlyBox(b: ReadableBox): ReadableBox; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/box/box.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/box/box.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..060108fc0c7071f8f2ccfc19b87c6a945e131b35 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/box/box.svelte.js @@ -0,0 +1,121 @@ +import { isFunction, isObject } from "../utils/is.js"; +const BoxSymbol = Symbol("box"); +const isWritableSymbol = Symbol("is-writable"); +/** + * @returns Whether the value is a Box + * + * @see {@link https://runed.dev/docs/functions/box} + */ +function isBox(value) { + return isObject(value) && BoxSymbol in value; +} +/** + * @returns Whether the value is a WritableBox + * + * @see {@link https://runed.dev/docs/functions/box} + */ +function isWritableBox(value) { + return box.isBox(value) && isWritableSymbol in value; +} +export function box(initialValue) { + let current = $state(initialValue); + return { + [BoxSymbol]: true, + [isWritableSymbol]: true, + get current() { + return current; + }, + set current(v) { + current = v; + } + }; +} +function boxWith(getter, setter) { + const derived = $derived.by(getter); + if (setter) { + return { + [BoxSymbol]: true, + [isWritableSymbol]: true, + get current() { + return derived; + }, + set current(v) { + setter(v); + } + }; + } + return { + [BoxSymbol]: true, + get current() { + return getter(); + } + }; +} +function boxFrom(value) { + if (box.isBox(value)) + return value; + if (isFunction(value)) + return box.with(value); + return box(value); +} +/** + * Function that gets an object of boxes, and returns an object of reactive values + * + * @example + * const count = box(0) + * const flat = box.flatten({ count, double: box.with(() => count.current) }) + * // type of flat is { count: number, readonly double: number } + * + * @see {@link https://runed.dev/docs/functions/box} + */ +function boxFlatten(boxes) { + return Object.entries(boxes).reduce((acc, [key, b]) => { + if (!box.isBox(b)) { + return Object.assign(acc, { [key]: b }); + } + if (box.isWritableBox(b)) { + Object.defineProperty(acc, key, { + get() { + return b.current; + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set(v) { + b.current = v; + } + }); + } + else { + Object.defineProperty(acc, key, { + get() { + return b.current; + } + }); + } + return acc; + }, {}); +} +/** + * Function that converts a box to a readonly box. + * + * @example + * const count = box(0) // WritableBox + * const countReadonly = box.readonly(count) // ReadableBox + * + * @see {@link https://runed.dev/docs/functions/box} + */ +function toReadonlyBox(b) { + if (!box.isWritableBox(b)) + return b; + return { + [BoxSymbol]: true, + get current() { + return b.current; + } + }; +} +box.from = boxFrom; +box.with = boxWith; +box.flatten = boxFlatten; +box.readonly = toReadonlyBox; +box.isBox = isBox; +box.isWritableBox = isWritableBox; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/css.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/css.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f1c32200edc3932d029a13deea7b853d6bcd8f0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/css.d.ts @@ -0,0 +1,10 @@ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import type * as CSS from "csstype"; + +declare module "csstype" { + interface Properties { + // Allow any CSS Custom Properties + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [index: `--${string}`]: any; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f688752079032cc694738e78e3c27a82f0737e69 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/index.d.ts @@ -0,0 +1,18 @@ +export * from "./box/box.svelte.js"; +export * from "./unbox/unbox.svelte.js"; +export * from "./types.js"; +export * from "./utils/compose-handlers.js"; +export * from "./utils/css-to-style-obj.js"; +export * from "./utils/execute-callbacks.js"; +export * from "./utils/events.js"; +export * from "./utils/merge-props.js"; +export * from "./utils/style.js"; +export * from "./utils/use-ref-by-id.svelte.js"; +export * from "./utils/strings.js"; +export * from "./utils/on-destroy-effect.svelte.js"; +export * from "./utils/after-sleep.js"; +export * from "./utils/after-tick.js"; +export * from "./utils/style-to-css.js"; +export * from "./utils/on-mount-effect.svelte.js"; +export * from "./utils/use-on-change.svelte.js"; +export * from "./utils/env.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f688752079032cc694738e78e3c27a82f0737e69 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/index.js @@ -0,0 +1,18 @@ +export * from "./box/box.svelte.js"; +export * from "./unbox/unbox.svelte.js"; +export * from "./types.js"; +export * from "./utils/compose-handlers.js"; +export * from "./utils/css-to-style-obj.js"; +export * from "./utils/execute-callbacks.js"; +export * from "./utils/events.js"; +export * from "./utils/merge-props.js"; +export * from "./utils/style.js"; +export * from "./utils/use-ref-by-id.svelte.js"; +export * from "./utils/strings.js"; +export * from "./utils/on-destroy-effect.svelte.js"; +export * from "./utils/after-sleep.js"; +export * from "./utils/after-tick.js"; +export * from "./utils/style-to-css.js"; +export * from "./utils/on-mount-effect.svelte.js"; +export * from "./utils/use-on-change.svelte.js"; +export * from "./utils/env.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/types.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..868a439b22cc08cc1d3b9874e59987adb1d75a33 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/types.d.ts @@ -0,0 +1,89 @@ +import type { Snippet } from "svelte"; +import type * as CSS from "csstype"; +import type { ReadableBox, WritableBox } from "./box/box.svelte.js"; +export type FunctionArgs = (...args: Args) => Return; +export type Getter = () => T; +export type MaybeGetter = T | Getter; +export type MaybeBoxOrGetter = T | Getter | ReadableBox; +export type BoxOrGetter = Getter | ReadableBox; +export type Box = ReadableBox | WritableBox; +export type Expand = T extends infer U ? { + [K in keyof U]: U[K]; +} : never; +/** + * Given a Record type T, returns a type that represents the same type, but with + * all values wrapped in a `ReadableBox`. + */ +export type ReadableBoxedValues = { + [K in keyof T]: ReadableBox; +}; +/** + * Given a Record type T, returns a type that represents the same type, but with + * all values wrapped in a `WritableBox`. + */ +export type WritableBoxedValues = { + [K in keyof T]: WritableBox; +}; +export type WithChild< +/** + * The props that the component accepts. + */ +Props extends Record = {}, +/** + * The props that are passed to the `child` and `children` snippets. The `ElementProps` are + * merged with these props for the `child` snippet. + */ +SnippetProps extends Record = { + _default: never; +}, +/** + * The underlying DOM element being rendered. You can bind to this prop to + * programatically interact with the element. + */ +Ref = HTMLElement> = Omit & { + child?: SnippetProps extends { + _default: never; + } ? Snippet<[{ + props: Record; + }]> : Snippet<[SnippetProps & { + props: Record; + }]>; + children?: SnippetProps extends { + _default: never; + } ? Snippet : Snippet<[SnippetProps]>; + style?: string | null | undefined; + ref?: Ref | null | undefined; +}; +export type WithChildren = Props & { + children?: Snippet | undefined; +}; +/** + * Constructs a new type by omitting properties from type + * 'T' that exist in type 'U'. + * + * @template T - The base object type from which properties will be omitted. + * @template U - The object type whose properties will be omitted from 'T'. + * @example + * type Result = Without<{ a: number; b: string; }, { b: string; }>; + * // Result type will be { a: number; } + */ +export type Without = Omit; +export type WithRefProps = T & ReadableBoxedValues<{ + id: string; +}> & WritableBoxedValues<{ + ref: HTMLElement | null; +}>; +export type WithoutChild = T extends { + child?: any; +} ? Omit : T; +export type WithoutChildrenOrChild = WithoutChildren>; +export type WithoutChildren = T extends { + children?: any; +} ? Omit : T; +export type WithElementRef = T & { + ref?: U | null; +}; +export type StyleProperties = CSS.Properties & { + [str: `--${string}`]: any; +}; +export type AnyFn = (...args: any[]) => any; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/types.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/types.js @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/unbox/unbox.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/unbox/unbox.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..143d44a55449fd9abea9dbde8d3a44ac15766652 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/unbox/unbox.svelte.d.ts @@ -0,0 +1,2 @@ +import type { MaybeBoxOrGetter } from "../types.js"; +export declare function unbox(value: MaybeBoxOrGetter): T; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/unbox/unbox.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/unbox/unbox.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..63ad7e76be37e5ff0e719f2b59edcff859024ca7 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/unbox/unbox.svelte.js @@ -0,0 +1,12 @@ +import { box } from "../box/box.svelte.js"; +import { isFunction } from "../utils/is.js"; +export function unbox(value) { + if (box.isBox(value)) { + return value.current; + } + if (isFunction(value)) { + const getter = value; + return getter(); + } + return value; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-sleep.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-sleep.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e7848b9133b875172d49aca67fd6ff2a71e8baa --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-sleep.d.ts @@ -0,0 +1,4 @@ +/** + * A utility function that executes a callback after a specified number of milliseconds. + */ +export declare function afterSleep(ms: number, cb: () => void): NodeJS.Timeout; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-sleep.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-sleep.js new file mode 100644 index 0000000000000000000000000000000000000000..18aecad0714ba6b6dce0ae281cdf31e7f60501c3 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-sleep.js @@ -0,0 +1,6 @@ +/** + * A utility function that executes a callback after a specified number of milliseconds. + */ +export function afterSleep(ms, cb) { + return setTimeout(cb, ms); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-tick.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-tick.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d33245c480c7f6b41cd949844755c12679ce41a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-tick.d.ts @@ -0,0 +1,2 @@ +import type { AnyFn } from "../types.js"; +export declare function afterTick(fn: AnyFn): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-tick.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-tick.js new file mode 100644 index 0000000000000000000000000000000000000000..54c10cace190c7183b9cc6d97738e5d4c162f7e0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/after-tick.js @@ -0,0 +1,4 @@ +import { tick } from "svelte"; +export function afterTick(fn) { + tick().then(fn); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/compose-handlers.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/compose-handlers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcbfdcb2b0249433b1b284dbc696d224fe0c4b66 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/compose-handlers.d.ts @@ -0,0 +1,8 @@ +import type { EventCallback } from "./events.js"; +import type { ReadableBox } from "../box/box.svelte.js"; +/** + * Composes event handlers into a single function that can be called with an event. + * If the previous handler cancels the event using `event.preventDefault()`, the handlers + * that follow will not be called. + */ +export declare function composeHandlers(...handlers: Array | ReadableBox> | undefined>): (e: E) => void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/compose-handlers.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/compose-handlers.js new file mode 100644 index 0000000000000000000000000000000000000000..58f3173709f95dd0ca1679b5df292c4ed5dd8de8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/compose-handlers.js @@ -0,0 +1,21 @@ +/** + * Composes event handlers into a single function that can be called with an event. + * If the previous handler cancels the event using `event.preventDefault()`, the handlers + * that follow will not be called. + */ +export function composeHandlers(...handlers) { + return function (e) { + for (const handler of handlers) { + if (!handler) + continue; + if (e.defaultPrevented) + return; + if (typeof handler === "function") { + handler.call(this, e); + } + else { + handler.current?.call(this, e); + } + } + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/css-to-style-obj.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/css-to-style-obj.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1733b3a156c377b927e89f94ecc2ffb10f802b7d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/css-to-style-obj.d.ts @@ -0,0 +1,2 @@ +import type { StyleProperties } from "../types.js"; +export declare function cssToStyleObj(css: string | null | undefined): StyleProperties; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/css-to-style-obj.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/css-to-style-obj.js new file mode 100644 index 0000000000000000000000000000000000000000..7437b6f0ae736bdc66777d913650e4624359997f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/css-to-style-obj.js @@ -0,0 +1,23 @@ +import parse from "style-to-object"; +import { camelCase, pascalCase } from "./strings.js"; +export function cssToStyleObj(css) { + if (!css) + return {}; + const styleObj = {}; + function iterator(name, value) { + if (name.startsWith("-moz-") || + name.startsWith("-webkit-") || + name.startsWith("-ms-") || + name.startsWith("-o-")) { + styleObj[pascalCase(name)] = value; + return; + } + if (name.startsWith("--")) { + styleObj[name] = value; + return; + } + styleObj[camelCase(name)] = value; + } + parse(css, iterator); + return styleObj; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/env.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20f3328aa37bc77cfc1f923e851b846da1da872d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/env.d.ts @@ -0,0 +1,19 @@ +type NodeType = Element | Window | Node | Document | null | undefined; +export declare function getDocument(node: NodeType): Document; +export declare function getDocumentElement(node: NodeType): HTMLElement; +export declare function getWindow(node: Node | ShadowRoot | Document | null | undefined): Window & typeof globalThis; +export declare function getActiveElement(rootNode: Document | ShadowRoot): HTMLElement | null; +export type EnvironmentStateProps = { + getRootNode?: () => Document | ShadowRoot | Node; +}; +export declare class EnvironmentState { + readonly props: EnvironmentStateProps; + constructor(props?: EnvironmentStateProps); + getRootNode(): Document | ShadowRoot; + getDoc(): Document; + getWin(): Window & typeof globalThis; + getActiveElement(): HTMLElement | null; + isActiveElement(node: HTMLElement | null | undefined): boolean; + getById(id: string): T | null; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/env.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/env.js new file mode 100644 index 0000000000000000000000000000000000000000..2708503ff62e624bdbf73716ed8be8061debcee6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/env.js @@ -0,0 +1,55 @@ +import { isDocument, isHTMLElement, isShadowRoot, isWindow } from "./is.js"; +export function getDocument(node) { + if (isDocument(node)) + return node; + if (isWindow(node)) + return node.document; + return node?.ownerDocument ?? document; +} +export function getDocumentElement(node) { + return getDocument(node).documentElement; +} +export function getWindow(node) { + if (isShadowRoot(node)) + return getWindow(node.host); + if (isDocument(node)) + return node.defaultView ?? window; + if (isHTMLElement(node)) + return node.ownerDocument?.defaultView ?? window; + return window; +} +export function getActiveElement(rootNode) { + let activeElement = rootNode.activeElement; + while (activeElement?.shadowRoot) { + const node = activeElement.shadowRoot.activeElement; + if (node === activeElement) + break; + else + activeElement = node; + } + return activeElement; +} +export class EnvironmentState { + props; + constructor(props = {}) { + this.props = props; + } + getRootNode() { + return (this.props?.getRootNode?.() ?? document); + } + getDoc() { + return getDocument(this.getRootNode()); + } + getWin() { + return this.getDoc().defaultView ?? window; + } + getActiveElement() { + return getActiveElement(this.getRootNode()); + } + isActiveElement(node) { + return node === this.getActiveElement(); + } + getById(id) { + return this.getRootNode().getElementById(id); + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/events.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0abee033fc1d7bfe33b098f40a417327d315e3c5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/events.d.ts @@ -0,0 +1,7 @@ +type Arrayable = T | T[]; +export type EventCallback = (event: E) => void; +type GeneralEventListener = (evt: E) => unknown; +export declare function addEventListener(target: Window, event: Arrayable, handler: (this: Window, ev: WindowEventMap[E]) => unknown, options?: boolean | AddEventListenerOptions): VoidFunction; +export declare function addEventListener(target: Document, event: Arrayable, handler: (this: Document, ev: DocumentEventMap[E]) => unknown, options?: boolean | AddEventListenerOptions): VoidFunction; +export declare function addEventListener(target: EventTarget, event: Arrayable, handler: GeneralEventListener, options?: boolean | AddEventListenerOptions): VoidFunction; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/events.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/events.js new file mode 100644 index 0000000000000000000000000000000000000000..d7ccc40bc75bcbdc42966bc8ef5df190850f32db --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/events.js @@ -0,0 +1,17 @@ +/** + * Adds an event listener to the specified target element(s) for the given event(s), and returns a function to remove it. + * @param target The target element(s) to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * @returns A function that removes the event listener from the target element(s). + */ +export function addEventListener(target, event, handler, options) { + const events = Array.isArray(event) ? event : [event]; + // Add the event listener to each specified event for the target element(s). + events.forEach((_event) => target.addEventListener(_event, handler, options)); + // Return a function that removes the event listener from the target element(s). + return () => { + events.forEach((_event) => target.removeEventListener(_event, handler, options)); + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/execute-callbacks.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/execute-callbacks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf742d7f168dbbd891f66c64bcc33a84c84a2dbb --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/execute-callbacks.d.ts @@ -0,0 +1,7 @@ +/** + * Executes an array of callback functions with the same arguments. + * @template T The types of the arguments that the callback functions take. + * @param callbacks array of callback functions to execute. + * @returns A new function that executes all of the original callback functions with the same arguments. + */ +export declare function executeCallbacks(...callbacks: T): (...args: unknown[]) => void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/execute-callbacks.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/execute-callbacks.js new file mode 100644 index 0000000000000000000000000000000000000000..4097d0e38a25168bc792e510469c41b09e3b3942 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/execute-callbacks.js @@ -0,0 +1,15 @@ +/** + * Executes an array of callback functions with the same arguments. + * @template T The types of the arguments that the callback functions take. + * @param callbacks array of callback functions to execute. + * @returns A new function that executes all of the original callback functions with the same arguments. + */ +export function executeCallbacks(...callbacks) { + return (...args) => { + for (const callback of callbacks) { + if (typeof callback === "function") { + callback(...args); + } + } + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/is.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/is.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ecc46009bb79ca32ce6b1bc32051a6bae54ec63f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/is.d.ts @@ -0,0 +1,11 @@ +import type { ClassValue } from "clsx"; +export declare function isFunction(value: unknown): value is (...args: unknown[]) => unknown; +export declare function isObject(value: unknown): value is Record; +export declare function isClassValue(value: unknown): value is ClassValue; +export declare function isHTMLElement(v: unknown): v is HTMLElement; +export declare function isDocument(v: unknown): v is Document; +export declare function isWindow(v: unknown): v is Window; +export declare function getNodeName(node: Node | Window): string; +export declare function isRootElement(node: Node): boolean; +export declare function isNode(v: unknown): v is Node; +export declare function isShadowRoot(v: unknown): v is ShadowRoot; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/is.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/is.js new file mode 100644 index 0000000000000000000000000000000000000000..6c902868c148938d7939cd1935e9ba54efb06f30 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/is.js @@ -0,0 +1,51 @@ +export function isFunction(value) { + return typeof value === "function"; +} +export function isObject(value) { + return value !== null && typeof value === "object"; +} +const CLASS_VALUE_PRIMITIVE_TYPES = ["string", "number", "bigint", "boolean"]; +export function isClassValue(value) { + // handle primitive types + if (value === null || value === undefined) + return true; + if (CLASS_VALUE_PRIMITIVE_TYPES.includes(typeof value)) + return true; + // handle arrays (ClassArray) + if (Array.isArray(value)) + return value.every((item) => isClassValue(item)); + // handle objects (ClassDictionary) + if (typeof value === "object") { + // ensure it's a plain object and not some other object type + if (Object.getPrototypeOf(value) !== Object.prototype) + return false; + return true; + } + return false; +} +const ELEMENT_NODE = 1; +const DOCUMENT_NODE = 9; +const DOCUMENT_FRAGMENT_NODE = 11; +export function isHTMLElement(v) { + return isObject(v) && v.nodeType === ELEMENT_NODE && typeof v.nodeName === "string"; +} +export function isDocument(v) { + return isObject(v) && v.nodeType === DOCUMENT_NODE; +} +export function isWindow(v) { + return isObject(v) && v === v.window; +} +export function getNodeName(node) { + if (isHTMLElement(node)) + return node.localName || ""; + return "#document"; +} +export function isRootElement(node) { + return ["html", "body", "#document"].includes(getNodeName(node)); +} +export function isNode(v) { + return isObject(v) && v.nodeType !== undefined; +} +export function isShadowRoot(v) { + return isNode(v) && v.nodeType === DOCUMENT_FRAGMENT_NODE && "host" in v; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/merge-props.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/merge-props.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0b8e4bc868792992d503cc56f3ef82cf2d6503f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/merge-props.d.ts @@ -0,0 +1,22 @@ +type Props = Record; +type PropsArg = Props | null | undefined; +type TupleTypes = { + [P in keyof T]: T[P]; +} extends { + [key: number]: infer V; +} ? NullToObject : never; +type NullToObject = T extends null | undefined ? {} : T; +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +/** + * Given a list of prop objects, merges them into a single object. + * - Automatically composes event handlers (e.g. `onclick`, `oninput`, etc.) + * - Chains regular functions with the same name so they are called in order + * - Merges class strings with `clsx` + * - Merges style objects and converts them to strings + * - Handles a bug with Svelte where setting the `hidden` attribute to `false` doesn't remove it + * - Overrides other values with the last one + */ +export declare function mergeProps(...args: T): UnionToIntersection> & { + style?: string; +}; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/merge-props.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/merge-props.js new file mode 100644 index 0000000000000000000000000000000000000000..65012c966d2001989ce6a9023bc5728559ee6855 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/merge-props.js @@ -0,0 +1,117 @@ +/** + * Modified from https://github.com/adobe/react-spectrum/blob/main/packages/%40react-aria/utils/src/mergeProps.ts (see NOTICE.txt for source) + */ +import { clsx } from "clsx"; +import { composeHandlers } from "./compose-handlers.js"; +import { cssToStyleObj } from "./css-to-style-obj.js"; +import { isClassValue } from "./is.js"; +import { executeCallbacks } from "./execute-callbacks.js"; +import { styleToString } from "./style.js"; +function isEventHandler(key) { + // we check if the 3rd character is uppercase to avoid merging our own + // custom callbacks like `onValueChange` and strictly merge native event handlers + return key.length > 2 && key.startsWith("on") && key[2] === key[2]?.toLowerCase(); +} +/** + * Given a list of prop objects, merges them into a single object. + * - Automatically composes event handlers (e.g. `onclick`, `oninput`, etc.) + * - Chains regular functions with the same name so they are called in order + * - Merges class strings with `clsx` + * - Merges style objects and converts them to strings + * - Handles a bug with Svelte where setting the `hidden` attribute to `false` doesn't remove it + * - Overrides other values with the last one + */ +export function mergeProps(...args) { + const result = { ...args[0] }; + for (let i = 1; i < args.length; i++) { + const props = args[i]; + for (const key in props) { + const a = result[key]; + const b = props[key]; + const aIsFunction = typeof a === "function"; + const bIsFunction = typeof b === "function"; + // compose event handlers + if (aIsFunction && typeof bIsFunction && isEventHandler(key)) { + // handle merging of event handlers + const aHandler = a; + const bHandler = b; + result[key] = composeHandlers(aHandler, bHandler); + } + else if (aIsFunction && bIsFunction) { + // chain non-event handler functions + result[key] = executeCallbacks(a, b); + } + else if (key === "class") { + // handle merging acceptable class values from clsx + const aIsClassValue = isClassValue(a); + const bIsClassValue = isClassValue(b); + if (aIsClassValue && bIsClassValue) { + result[key] = clsx(a, b); + } + else if (aIsClassValue) { + result[key] = clsx(a); + } + else if (bIsClassValue) { + result[key] = clsx(b); + } + } + else if (key === "style") { + const aIsObject = typeof a === "object"; + const bIsObject = typeof b === "object"; + const aIsString = typeof a === "string"; + const bIsString = typeof b === "string"; + if (aIsObject && bIsObject) { + // both are style objects, merge them + result[key] = { ...a, ...b }; + } + else if (aIsObject && bIsString) { + // a is style object, b is string, convert b to style object and merge + const parsedStyle = cssToStyleObj(b); + result[key] = { ...a, ...parsedStyle }; + } + else if (aIsString && bIsObject) { + // a is string, b is style object, convert a to style object and merge + const parsedStyle = cssToStyleObj(a); + result[key] = { ...parsedStyle, ...b }; + } + else if (aIsString && bIsString) { + // both are strings, convert both to objects and merge + const parsedStyleA = cssToStyleObj(a); + const parsedStyleB = cssToStyleObj(b); + result[key] = { ...parsedStyleA, ...parsedStyleB }; + } + else if (aIsObject) { + result[key] = a; + } + else if (bIsObject) { + result[key] = b; + } + else if (aIsString) { + result[key] = a; + } + else if (bIsString) { + result[key] = b; + } + } + else { + // override other values + result[key] = b !== undefined ? b : a; + } + } + } + // convert style object to string + if (typeof result.style === "object") { + result.style = styleToString(result.style).replaceAll("\n", " "); + } + // handle weird svelte bug where `hidden` is not removed when set to `false` + if (result.hidden !== true) { + result.hidden = undefined; + delete result.hidden; + } + // handle weird svelte bug where `disabled` is not removed when set to `false` + if (result.disabled !== true) { + result.disabled = undefined; + delete result.disabled; + } + return result; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-destroy-effect.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-destroy-effect.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..73dc36a4ff369fcabcbf85781dcf4d8b7622b5fd --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-destroy-effect.svelte.d.ts @@ -0,0 +1 @@ +export declare function onDestroyEffect(fn: () => void): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-destroy-effect.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-destroy-effect.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..50977a8c7ef82704c05d31a474279c68ab2b09fc --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-destroy-effect.svelte.js @@ -0,0 +1,7 @@ +export function onDestroyEffect(fn) { + $effect(() => { + return () => { + fn(); + }; + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-mount-effect.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-mount-effect.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..412f05d1018b50a7c7defbc71db2f711aafbf940 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-mount-effect.svelte.d.ts @@ -0,0 +1 @@ +export declare function onMountEffect(fn: () => void): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-mount-effect.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-mount-effect.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..0e691694de3ba017eabdf9f8c2dbf4dc6826f1b8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/on-mount-effect.svelte.js @@ -0,0 +1,7 @@ +import { untrack } from "svelte"; +export function onMountEffect(fn) { + $effect(() => { + const cleanup = untrack(() => fn()); + return cleanup; + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/strings.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/strings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d776770dd64712c6623365933f600871f0c784b8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/strings.d.ts @@ -0,0 +1,3 @@ +export declare function pascalCase(str?: string): string; +export declare function camelCase(str?: string): string; +export declare function kebabCase(str?: string): string; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/strings.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/strings.js new file mode 100644 index 0000000000000000000000000000000000000000..c0cb77d923c44065b3e3f725cfdd988593a9c388 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/strings.js @@ -0,0 +1,70 @@ +const NUMBER_CHAR_RE = /\d/; +const STR_SPLITTERS = ["-", "_", "/", "."]; +function isUppercase(char = "") { + if (NUMBER_CHAR_RE.test(char)) + return undefined; + return char !== char.toLowerCase(); +} +function splitByCase(str) { + const parts = []; + let buff = ""; + let previousUpper; + let previousSplitter; + for (const char of str) { + // Splitter + const isSplitter = STR_SPLITTERS.includes(char); + if (isSplitter === true) { + parts.push(buff); + buff = ""; + previousUpper = undefined; + continue; + } + const isUpper = isUppercase(char); + if (previousSplitter === false) { + // Case rising edge + if (previousUpper === false && isUpper === true) { + parts.push(buff); + buff = char; + previousUpper = isUpper; + continue; + } + // Case falling edge + if (previousUpper === true && isUpper === false && buff.length > 1) { + const lastChar = buff.at(-1); + parts.push(buff.slice(0, Math.max(0, buff.length - 1))); + buff = lastChar + char; + previousUpper = isUpper; + continue; + } + } + // Normal char + buff += char; + previousUpper = isUpper; + previousSplitter = isSplitter; + } + parts.push(buff); + return parts; +} +export function pascalCase(str) { + if (!str) + return ""; + return splitByCase(str) + .map((p) => upperFirst(p)) + .join(""); +} +export function camelCase(str) { + return lowerFirst(pascalCase(str || "")); +} +export function kebabCase(str) { + return str + ? splitByCase(str) + .map((p) => p.toLowerCase()) + .join("-") + : ""; +} +function upperFirst(str) { + return str ? str[0].toUpperCase() + str.slice(1) : ""; +} +function lowerFirst(str) { + return str ? str[0].toLowerCase() + str.slice(1) : ""; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style-to-css.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style-to-css.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb3236b94cb4f74be7d9602dcf83a7fb83c53f69 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style-to-css.d.ts @@ -0,0 +1 @@ +export declare function styleToCSS(styleObj: object): string; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style-to-css.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style-to-css.js new file mode 100644 index 0000000000000000000000000000000000000000..3f88ac5070ebe6409134bedca46d7bd06e47f26c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style-to-css.js @@ -0,0 +1,23 @@ +function createParser(matcher, replacer) { + const regex = RegExp(matcher, "g"); + return (str) => { + // throw an error if not a string + if (typeof str !== "string") { + throw new TypeError(`expected an argument of type string, but got ${typeof str}`); + } + // if no match between string and matcher + if (!str.match(regex)) + return str; + // executes the replacer function for each match + return str.replace(regex, replacer); + }; +} +const camelToKebab = createParser(/[A-Z]/, (match) => `-${match.toLowerCase()}`); +export function styleToCSS(styleObj) { + if (!styleObj || typeof styleObj !== "object" || Array.isArray(styleObj)) { + throw new TypeError(`expected an argument of type object, but got ${typeof styleObj}`); + } + return Object.keys(styleObj) + .map((property) => `${camelToKebab(property)}: ${styleObj[property]};`) + .join("\n"); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b3b8048f3969c427fa557be07076d0f834aa8d9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style.d.ts @@ -0,0 +1,4 @@ +import type { StyleProperties } from "../types.js"; +export declare function styleToString(style?: StyleProperties): string; +export declare const srOnlyStyles: StyleProperties; +export declare const srOnlyStylesString: string; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style.js new file mode 100644 index 0000000000000000000000000000000000000000..915e79e9d8bca9b2dcf1be3f37c32daea24dd759 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/style.js @@ -0,0 +1,17 @@ +import { styleToCSS } from "./style-to-css.js"; +export function styleToString(style = {}) { + return styleToCSS(style).replace("\n", " "); +} +export const srOnlyStyles = { + position: "absolute", + width: "1px", + height: "1px", + padding: "0", + margin: "-1px", + overflow: "hidden", + clip: "rect(0, 0, 0, 0)", + whiteSpace: "nowrap", + borderWidth: "0", + transform: "translateX(-100%)" +}; +export const srOnlyStylesString = styleToString(srOnlyStyles); diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-on-change.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-on-change.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c9fa4805e9bac567fec0183fedcb6f2453b473b --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-on-change.svelte.d.ts @@ -0,0 +1,12 @@ +import type { Getter } from "../types.js"; +/** + * Simple helper function to sync a read-only dependency with writable state. This only syncs + * in one direction, from the dependency to the state. If you need to sync both directions, you + * should use the `box.with(() => dep, (v) => (dep = v))` pattern. + * + * @param getDep - A getter that returns the value that may change and whose new value will be + * passed to the `onChange` function passed as the second argument. + * @param onChange - A function that accepts a new value to react to or keep other state in sync + * with the dependency. + */ +export declare function useOnChange(getDep: Getter, onChange: (value: T) => void): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-on-change.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-on-change.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..e0e3704ec4cdc8e47353722bacb3755ed439eb25 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-on-change.svelte.js @@ -0,0 +1,14 @@ +import { watch } from "runed"; +/** + * Simple helper function to sync a read-only dependency with writable state. This only syncs + * in one direction, from the dependency to the state. If you need to sync both directions, you + * should use the `box.with(() => dep, (v) => (dep = v))` pattern. + * + * @param getDep - A getter that returns the value that may change and whose new value will be + * passed to the `onChange` function passed as the second argument. + * @param onChange - A function that accepts a new value to react to or keep other state in sync + * with the dependency. + */ +export function useOnChange(getDep, onChange) { + watch(getDep, onChange); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe72c393f074ab48a5f4b70b87b321c8f5498534 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.d.ts @@ -0,0 +1,32 @@ +import type { WritableBox } from "../box/box.svelte.js"; +import type { Box, Getter } from "../types.js"; +type UseRefByIdProps = { + /** + * The ID of the node to find. + */ + id: Box; + /** + * The ref to set the node to. + */ + ref: WritableBox; + /** + * A reactive condition that will cause the node to be set. + */ + deps?: Getter; + /** + * A callback fired when the ref changes. + */ + onRefChange?: (node: HTMLElement | null) => void; + /** + * A function that returns the root node to search for the element by ID. + * Defaults to `() => document`. + */ + getRootNode?: Getter; +}; +/** + * Finds the node with that ID and sets it to the boxed node. + * Reactive using `$effect` to ensure when the ID or deps change, + * an update is triggered and new node is found. + */ +export declare function useRefById({ id, ref, deps, onRefChange, getRootNode }: UseRefByIdProps): void; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..1629d0ed5fedc12a3edc6e012a36b559dcc447b7 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/utils/use-ref-by-id.svelte.js @@ -0,0 +1,22 @@ +import { watch } from "runed"; +import { onDestroyEffect } from "./on-destroy-effect.svelte.js"; +/** + * Finds the node with that ID and sets it to the boxed node. + * Reactive using `$effect` to ensure when the ID or deps change, + * an update is triggered and new node is found. + */ +export function useRefById({ id, ref, deps = () => true, onRefChange, getRootNode }) { + watch([() => id.current, deps], ([_id]) => { + const rootNode = getRootNode?.() ?? document; + const node = rootNode?.getElementById(_id); + if (node) + ref.current = node; + else + ref.current = null; + onRefChange?.(ref.current); + }); + onDestroyEffect(() => { + ref.current = null; + onRefChange?.(null); + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/watch/watch.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/watch/watch.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..68c4d06eb15afb2e7c3faed8c7510489849575f8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/watch/watch.svelte.d.ts @@ -0,0 +1,14 @@ +import type { Box } from "../types.js"; +type WatcherCallback = (curr: T, prev: T) => void | Promise | (() => void) | (() => Promise); +type WatchOptions = { + /** + * Whether to eagerly run the watcher before the state is updated. + */ + immediate?: boolean; + /** + * Whether to run the watcher only once. + */ + once?: boolean; +}; +export declare function watch(box: Box, callback: WatcherCallback, options?: WatchOptions): () => void; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/watch/watch.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/watch/watch.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..a3fd326c1a83ccd6793ae2fc7c04533186623ef6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/dist/watch/watch.svelte.js @@ -0,0 +1,26 @@ +import { untrack } from "svelte"; +export function watch(box, callback, options = {}) { + let prev = $state(box.current); + let ranOnce = false; + const watchEffect = $effect.root(() => { + $effect.pre(() => { + if (prev === box.current || !options.immediate) + return; + if (options.once && ranOnce) + return; + callback(box.current, untrack(() => prev)); + untrack(() => (prev = box.current)); + ranOnce = true; + }); + $effect(() => { + if (prev === box.current || options.immediate) + return; + if (options.once && ranOnce) + return; + callback(box.current, untrack(() => prev)); + untrack(() => (prev = box.current)); + ranOnce = true; + }); + }); + return watchEffect; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/LICENSE b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..66fd878694f2e19172751731c8b903e5a047e7ef --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024 Hunter Johnston +Copyright (c) 2024 Thomas G. Lopes + +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. diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/README.md b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e4ab80d0d815794acb89d6ac08a089c56e52e8c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/README.md @@ -0,0 +1,32 @@ +# Runed + + + +[![npm version](https://flat.badgen.net/npm/v/runed?color=green)](https://npmjs.com/package/runed) +[![npm downloads](https://flat.badgen.net/npm/dm/runed?color=green)](https://npmjs.com/package/runed) +[![license](https://flat.badgen.net/github/license/svecosystem/runed?color=green)](https://github.com/svecosystem/runed/blob/main/LICENSE) + + + +Runed provides utilities to power your applications using the magic of +[Svelte Runes](https://svelte.dev/blog/runes). + +## Features + + + +## Installation + +Runed will be published to NPM once Svelte 5 is released. + +## License + + + +Published under the [MIT](https://github.com/svecosystem/runed/blob/main/LICENSE) license. Made by +[@tglide](https://github.com/tglide), [@huntabyte](https://github.com/huntabyte) and +[community](https://github.com/svecosystem/runed/graphs/contributors) 💛

+ + + + diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01d2be1985ff9683c407139778042b081afe4785 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/index.d.ts @@ -0,0 +1 @@ +export * from "./utilities/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..01d2be1985ff9683c407139778042b081afe4785 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/index.js @@ -0,0 +1 @@ +export * from "./utilities/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/configurable-globals.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/configurable-globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43192a8559eeae16bd2e59c3c9d792dee826cf0e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/configurable-globals.d.ts @@ -0,0 +1,23 @@ +export type ConfigurableWindow = { + /** Provide a custom `window` object to use in place of the global `window` object. */ + window?: typeof globalThis & Window; +}; +export type ConfigurableDocument = { + /** Provide a custom `document` object to use in place of the global `document` object. */ + document?: Document; +}; +export type ConfigurableDocumentOrShadowRoot = { + document?: DocumentOrShadowRoot; +}; +export type ConfigurableNavigator = { + /** Provide a custom `navigator` object to use in place of the global `navigator` object. */ + navigator?: Navigator; +}; +export type ConfigurableLocation = { + /** Provide a custom `location` object to use in place of the global `location` object. */ + location?: Location; +}; +export declare const defaultWindow: (Window & typeof globalThis) | undefined; +export declare const defaultDocument: Document | undefined; +export declare const defaultNavigator: Navigator | undefined; +export declare const defaultLocation: Location | undefined; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/configurable-globals.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/configurable-globals.js new file mode 100644 index 0000000000000000000000000000000000000000..c1c0765bbdf51e98ae17c2292910dc2524576670 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/configurable-globals.js @@ -0,0 +1,5 @@ +import { BROWSER } from "esm-env"; +export const defaultWindow = BROWSER && typeof window !== "undefined" ? window : undefined; +export const defaultDocument = BROWSER && typeof window !== "undefined" ? window.document : undefined; +export const defaultNavigator = BROWSER && typeof window !== "undefined" ? window.navigator : undefined; +export const defaultLocation = BROWSER && typeof window !== "undefined" ? window.location : undefined; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/types.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0292b0429a1bab2f3e93f35202ac6e388e6975ca --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/types.d.ts @@ -0,0 +1,11 @@ +export type Getter = () => T; +export type MaybeGetter = T | Getter; +export type MaybeElementGetter = MaybeGetter; +export type MaybeElement = HTMLElement | SVGElement | undefined | null; +export type Setter = (value: T) => void; +export type Expand = T extends infer U ? { + [K in keyof U]: U[K]; +} : never; +export type WritableProperties = { + -readonly [P in keyof T]: T[P]; +}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/types.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/types.js @@ -0,0 +1 @@ +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/array.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..858ea9088717041ac6d9bf8289969ab6f5f8f631 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/array.d.ts @@ -0,0 +1,5 @@ +/** + * Get nth item of Array. Negative for backward + */ +export declare function at(array: readonly T[], index: number): T | undefined; +export declare function last(array: readonly T[]): T | undefined; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/array.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/array.js new file mode 100644 index 0000000000000000000000000000000000000000..bcd82395afd8936a384049aa09c3928097a4cbc0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/array.js @@ -0,0 +1,14 @@ +/** + * Get nth item of Array. Negative for backward + */ +export function at(array, index) { + const len = array.length; + if (!len) + return undefined; + if (index < 0) + index += len; + return array[index]; +} +export function last(array) { + return array[array.length - 1]; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/browser.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5431041d4afccbb9c64cf6ecfa5331731de9c18 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/browser.d.ts @@ -0,0 +1 @@ +export { BROWSER as browser } from "esm-env"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/browser.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..e5431041d4afccbb9c64cf6ecfa5331731de9c18 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/browser.js @@ -0,0 +1 @@ +export { BROWSER as browser } from "esm-env"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/dom.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/dom.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..97809a965b1fd0d6847e831a722bb883e073e9f5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/dom.d.ts @@ -0,0 +1,25 @@ +/** + * Handles getting the active element in a document or shadow root. + * If the active element is within a shadow root, it will traverse the shadow root + * to find the active element. + * If not, it will return the active element in the document. + * + * @param document A document or shadow root to get the active element from. + * @returns The active element in the document or shadow root. + */ +export declare function getActiveElement(document: DocumentOrShadowRoot): Element | null; +/** + * Returns the owner document of a given element. + * + * @param node The element to get the owner document from. + * @returns + */ +export declare function getOwnerDocument(node: Element | null | undefined, fallback?: Document | undefined): Document | undefined; +/** + * Checks if an element is or is contained by another element. + * + * @param node The element to check if it or its descendants contain the target element. + * @param target The element to check if it is contained by the node. + * @returns + */ +export declare function isOrContainsTarget(node: Element, target: Element): boolean; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/dom.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..e0fb6b7eb0e341aafc81d069d8a249aeb36d96ee --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/dom.js @@ -0,0 +1,40 @@ +import { defaultDocument } from "../configurable-globals.js"; +/** + * Handles getting the active element in a document or shadow root. + * If the active element is within a shadow root, it will traverse the shadow root + * to find the active element. + * If not, it will return the active element in the document. + * + * @param document A document or shadow root to get the active element from. + * @returns The active element in the document or shadow root. + */ +export function getActiveElement(document) { + let activeElement = document.activeElement; + while (activeElement?.shadowRoot) { + const node = activeElement.shadowRoot.activeElement; + if (node === activeElement) + break; + else + activeElement = node; + } + return activeElement; +} +/** + * Returns the owner document of a given element. + * + * @param node The element to get the owner document from. + * @returns + */ +export function getOwnerDocument(node, fallback = defaultDocument) { + return node?.ownerDocument ?? fallback; +} +/** + * Checks if an element is or is contained by another element. + * + * @param node The element to check if it or its descendants contain the target element. + * @param target The element to check if it is contained by the node. + * @returns + */ +export function isOrContainsTarget(node, target) { + return node === target || node.contains(target); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/function.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/function.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..940809c20c17e42210afda39714ae2410ed566d6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/function.d.ts @@ -0,0 +1 @@ +export declare function noop(): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/function.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/function.js new file mode 100644 index 0000000000000000000000000000000000000000..510c075494c057a30a1add2e9cc2fffbcfa43478 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/function.js @@ -0,0 +1 @@ +export function noop() { } diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/get.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/get.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3f946aab0136e40ab48412e77659632fdde4a4b4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/get.d.ts @@ -0,0 +1,2 @@ +import type { MaybeGetter } from "../types.js"; +export declare function get(value: MaybeGetter): T; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/get.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/get.js new file mode 100644 index 0000000000000000000000000000000000000000..7039f0e1f8baf1eaa6b1c670057bd7ef6c2f7f7c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/get.js @@ -0,0 +1,7 @@ +import { isFunction } from "./is.js"; +export function get(value) { + if (isFunction(value)) { + return value(); + } + return value; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/is.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/is.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56b733898063f7e543c8927c890a4b8d7bee292f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/is.d.ts @@ -0,0 +1,3 @@ +export declare function isFunction(value: unknown): value is (...args: unknown[]) => unknown; +export declare function isObject(value: unknown): value is Record; +export declare function isElement(value: unknown): value is Element; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/is.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/is.js new file mode 100644 index 0000000000000000000000000000000000000000..4f248e7350be7e5e212232073ade3ddd4d6c06e5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/is.js @@ -0,0 +1,9 @@ +export function isFunction(value) { + return typeof value === "function"; +} +export function isObject(value) { + return value !== null && typeof value === "object"; +} +export function isElement(value) { + return value instanceof Element; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/sleep.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/sleep.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5045cf22bb7e10a6229c8026cae8e99cf1243878 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/sleep.d.ts @@ -0,0 +1 @@ +export declare function sleep(ms?: number): Promise; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/sleep.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/sleep.js new file mode 100644 index 0000000000000000000000000000000000000000..eda75dce940fe106313c547d7ca40e343f04a1ab --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/internal/utils/sleep.js @@ -0,0 +1,3 @@ +export async function sleep(ms = 0) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/test/util.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/test/util.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..324b31676c949abbff26966ddfb128411ce97ff1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/test/util.svelte.d.ts @@ -0,0 +1,3 @@ +export declare function testWithEffect(name: string, fn: () => void | Promise): void; +export declare function effectRootScope(fn: () => void | Promise): void | Promise; +export declare function vitestSetTimeoutWrapper(fn: () => void, timeout: number): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/test/util.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/test/util.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..e9c5a27051de7036750535198cd3de80ade57a0c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/test/util.svelte.js @@ -0,0 +1,22 @@ +import { test, vi } from "vitest"; +export function testWithEffect(name, fn) { + test(name, () => effectRootScope(fn)); +} +export function effectRootScope(fn) { + let promise; + const cleanup = $effect.root(() => { + promise = fn(); + }); + if (promise instanceof Promise) { + return promise.finally(cleanup); + } + else { + cleanup(); + } +} +export function vitestSetTimeoutWrapper(fn, timeout) { + setTimeout(() => { + fn(); + }, timeout + 1); + vi.advanceTimersByTime(timeout); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/active-element.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/active-element.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e608e7a58f93a7d879892c48fa787b799bff83b4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/active-element.svelte.d.ts @@ -0,0 +1,18 @@ +import { type ConfigurableDocumentOrShadowRoot, type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface ActiveElementOptions extends ConfigurableDocumentOrShadowRoot, ConfigurableWindow { +} +export declare class ActiveElement { + #private; + constructor(options?: ActiveElementOptions); + get current(): Element | null; +} +/** + * An object holding a reactive value that is equal to `document.activeElement`. + * It automatically listens for changes, keeping the reference up to date. + * + * If you wish to use a custom document or shadowRoot, you should use + * [useActiveElement](https://runed.dev/docs/utilities/active-element) instead. + * + * @see {@link https://runed.dev/docs/utilities/active-element} + */ +export declare const activeElement: ActiveElement; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/active-element.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/active-element.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..c6c84c0e0b48a61717dad9955e3632d16413b253 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/active-element.svelte.js @@ -0,0 +1,38 @@ +import { defaultWindow, } from "../../internal/configurable-globals.js"; +import { getActiveElement } from "../../internal/utils/dom.js"; +import { on } from "svelte/events"; +import { createSubscriber } from "svelte/reactivity"; +export class ActiveElement { + #document; + #subscribe; + constructor(options = {}) { + const { window = defaultWindow, document = window?.document } = options; + if (window === undefined) + return; + this.#document = document; + this.#subscribe = createSubscriber((update) => { + const cleanupFocusIn = on(window, "focusin", update); + const cleanupFocusOut = on(window, "focusout", update); + return () => { + cleanupFocusIn(); + cleanupFocusOut(); + }; + }); + } + get current() { + this.#subscribe?.(); + if (!this.#document) + return null; + return getActiveElement(this.#document); + } +} +/** + * An object holding a reactive value that is equal to `document.activeElement`. + * It automatically listens for changes, keeping the reference up to date. + * + * If you wish to use a custom document or shadowRoot, you should use + * [useActiveElement](https://runed.dev/docs/utilities/active-element) instead. + * + * @see {@link https://runed.dev/docs/utilities/active-element} + */ +export const activeElement = new ActiveElement(); diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2088da81b429c7c55d0862fc3c07f20edc4c3400 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/index.d.ts @@ -0,0 +1 @@ +export * from "./active-element.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2088da81b429c7c55d0862fc3c07f20edc4c3400 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/active-element/index.js @@ -0,0 +1 @@ +export * from "./active-element.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a41ddd48612e4f24e5c6e2dae6f3ba482bc2dceb --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.d.ts @@ -0,0 +1,40 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +type RafCallbackParams = { + /** The number of milliseconds since the last frame. */ + delta: number; + /** + * Time elapsed since the creation of the web page. + * See {@link https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin Time origin}. + */ + timestamp: DOMHighResTimeStamp; +}; +export type AnimationFramesOptions = ConfigurableWindow & { + /** + * Start calling requestAnimationFrame immediately. + * + * @default true + */ + immediate?: boolean; + /** + * Limit the number of frames per second. + * Set to `0` to disable + * + * @default 0 + */ + fpsLimit?: MaybeGetter; +}; +/** + * Wrapper over {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame}, + * with controls for pausing and resuming the animation, reactive tracking and optional limiting of fps, and utilities. + */ +export declare class AnimationFrames { + #private; + constructor(callback: (params: RafCallbackParams) => void, options?: AnimationFramesOptions); + start(): void; + stop(): void; + toggle(): void; + get fps(): number; + get running(): boolean; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..5af8aa5f524fb6c51c8f855c4e90c634e92e0b0f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/animation-frames.svelte.js @@ -0,0 +1,72 @@ +import { untrack } from "svelte"; +import { extract } from "../extract/index.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Wrapper over {@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame requestAnimationFrame}, + * with controls for pausing and resuming the animation, reactive tracking and optional limiting of fps, and utilities. + */ +export class AnimationFrames { + #callback; + #fpsLimitOption = 0; + #fpsLimit = $derived(extract(this.#fpsLimitOption) ?? 0); + #previousTimestamp = null; + #frame = null; + #fps = $state(0); + #running = $state(false); + #window = defaultWindow; + constructor(callback, options = {}) { + if (options.window) + this.#window = options.window; + this.#fpsLimitOption = options.fpsLimit; + this.#callback = callback; + this.start = this.start.bind(this); + this.stop = this.stop.bind(this); + this.toggle = this.toggle.bind(this); + $effect(() => { + if (options.immediate ?? true) { + untrack(this.start); + } + return this.stop; + }); + } + #loop(timestamp) { + if (!this.#running || !this.#window) + return; + if (this.#previousTimestamp === null) { + this.#previousTimestamp = timestamp; + } + const delta = timestamp - this.#previousTimestamp; + const fps = 1000 / delta; + if (this.#fpsLimit && fps > this.#fpsLimit) { + this.#frame = this.#window.requestAnimationFrame(this.#loop.bind(this)); + return; + } + this.#fps = fps; + this.#previousTimestamp = timestamp; + this.#callback({ delta, timestamp }); + this.#frame = this.#window.requestAnimationFrame(this.#loop.bind(this)); + } + start() { + if (!this.#window) + return; + this.#running = true; + this.#previousTimestamp = 0; + this.#frame = this.#window.requestAnimationFrame(this.#loop.bind(this)); + } + stop() { + if (!this.#frame || !this.#window) + return; + this.#running = false; + this.#window.cancelAnimationFrame(this.#frame); + this.#frame = null; + } + toggle() { + this.#running ? this.stop() : this.start(); + } + get fps() { + return !this.#running ? 0 : this.#fps; + } + get running() { + return this.#running; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9620b836ff6875aaf49cb4f43df743d39f5b42e2 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/index.d.ts @@ -0,0 +1 @@ +export * from "./animation-frames.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9620b836ff6875aaf49cb4f43df743d39f5b42e2 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/animation-frames/index.js @@ -0,0 +1 @@ +export * from "./animation-frames.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/context.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..13ef0701a076ebc92e0fca4225e84d74c6fe6ab1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/context.d.ts @@ -0,0 +1,42 @@ +export declare class Context { + #private; + /** + * @param name The name of the context. + * This is used for generating the context key and error messages. + */ + constructor(name: string); + /** + * The key used to get and set the context. + * + * It is not recommended to use this value directly. + * Instead, use the methods provided by this class. + */ + get key(): symbol; + /** + * Checks whether this has been set in the context of a parent component. + * + * Must be called during component initialisation. + */ + exists(): boolean; + /** + * Retrieves the context that belongs to the closest parent component. + * + * Must be called during component initialisation. + * + * @throws An error if the context does not exist. + */ + get(): TContext; + /** + * Retrieves the context that belongs to the closest parent component, + * or the given fallback value if the context does not exist. + * + * Must be called during component initialisation. + */ + getOr(fallback: TFallback): TContext | TFallback; + /** + * Associates the given value with the current component and returns it. + * + * Must be called during component initialisation. + */ + set(context: TContext): TContext; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/context.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/context.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9ad7b36b279079d9506ff0d1ff9053374f560f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/context.js @@ -0,0 +1,65 @@ +import { getContext, hasContext, setContext } from "svelte"; +export class Context { + #name; + #key; + /** + * @param name The name of the context. + * This is used for generating the context key and error messages. + */ + constructor(name) { + this.#name = name; + this.#key = Symbol(name); + } + /** + * The key used to get and set the context. + * + * It is not recommended to use this value directly. + * Instead, use the methods provided by this class. + */ + get key() { + return this.#key; + } + /** + * Checks whether this has been set in the context of a parent component. + * + * Must be called during component initialisation. + */ + exists() { + return hasContext(this.#key); + } + /** + * Retrieves the context that belongs to the closest parent component. + * + * Must be called during component initialisation. + * + * @throws An error if the context does not exist. + */ + get() { + const context = getContext(this.#key); + if (context === undefined) { + throw new Error(`Context "${this.#name}" not found`); + } + return context; + } + /** + * Retrieves the context that belongs to the closest parent component, + * or the given fallback value if the context does not exist. + * + * Must be called during component initialisation. + */ + getOr(fallback) { + const context = getContext(this.#key); + if (context === undefined) { + return fallback; + } + return context; + } + /** + * Associates the given value with the current component and returns it. + * + * Must be called during component initialisation. + */ + set(context) { + return setContext(this.#key, context); + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1244f57a741ab24941b2cc20e6c924b8650a1425 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/index.d.ts @@ -0,0 +1 @@ +export { Context } from "./context.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1244f57a741ab24941b2cc20e6c924b8650a1425 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/context/index.js @@ -0,0 +1 @@ +export { Context } from "./context.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/debounced.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/debounced.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c8898cc2b74bdcb5cded1492ef1a63c4b2fea3a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/debounced.svelte.d.ts @@ -0,0 +1,48 @@ +import type { Getter, MaybeGetter } from "../../internal/types.js"; +/** + * A wrapper over {@link useDebounce} that creates a debounced state. + * It takes a "getter" function which returns the state you want to debounce. + * Every time this state changes a timer (re)starts, the length of which is + * configurable with the `wait` arg. When the timer ends the `current` value + * is updated. + * + * @see https://runed.dev/docs/utilities/debounced + * + * @example + * + * + * + *
+ * + *

You searched for: {debounced.current}

+ *
+ */ +export declare class Debounced { + #private; + /** + * @param getter A function that returns the state to watch. + * @param wait The length of time to wait in ms, defaults to 250. + */ + constructor(getter: Getter, wait?: MaybeGetter); + /** + * Get the current value. + */ + get current(): T; + /** + * Cancel the latest timer. + */ + cancel(): void; + /** + * Run the debounced function immediately. + */ + updateImmediately(): Promise; + /** + * Set the `current` value without waiting. + */ + setImmediately(v: T): void; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/debounced.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/debounced.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..c8175e7ba884e052a42876235ba84e50584282c6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/debounced.svelte.js @@ -0,0 +1,71 @@ +import { useDebounce } from "../use-debounce/use-debounce.svelte.js"; +import { watch } from "../watch/watch.svelte.js"; +import { noop } from "../../internal/utils/function.js"; +/** + * A wrapper over {@link useDebounce} that creates a debounced state. + * It takes a "getter" function which returns the state you want to debounce. + * Every time this state changes a timer (re)starts, the length of which is + * configurable with the `wait` arg. When the timer ends the `current` value + * is updated. + * + * @see https://runed.dev/docs/utilities/debounced + * + * @example + * + * + * + *
+ * + *

You searched for: {debounced.current}

+ *
+ */ +export class Debounced { + #current = $state(); + #debounceFn; + /** + * @param getter A function that returns the state to watch. + * @param wait The length of time to wait in ms, defaults to 250. + */ + constructor(getter, wait = 250) { + this.#current = getter(); // immediately set the initial value + this.cancel = this.cancel.bind(this); + this.setImmediately = this.setImmediately.bind(this); + this.updateImmediately = this.updateImmediately.bind(this); + this.#debounceFn = useDebounce(() => { + this.#current = getter(); + }, wait); + watch(getter, () => { + this.#debounceFn().catch(noop); + }); + } + /** + * Get the current value. + */ + get current() { + return this.#current; + } + /** + * Cancel the latest timer. + */ + cancel() { + this.#debounceFn.cancel(); + } + /** + * Run the debounced function immediately. + */ + updateImmediately() { + return this.#debounceFn.runScheduledNow(); + } + /** + * Set the `current` value without waiting. + */ + setImmediately(v) { + this.cancel(); + this.#current = v; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d8afc470bd7bbd571ceca2fd1e1762ca9f0e86f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/index.d.ts @@ -0,0 +1 @@ +export * from "./debounced.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d8afc470bd7bbd571ceca2fd1e1762ca9f0e86f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/debounced/index.js @@ -0,0 +1 @@ +export * from "./debounced.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..809f63d1ec8db5cba918e1e3c39f7e0a95c6ed51 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.d.ts @@ -0,0 +1,31 @@ +import type { MaybeElementGetter, WritableProperties } from "../../internal/types.js"; +import type { ConfigurableWindow } from "../../internal/configurable-globals.js"; +type Rect = WritableProperties>; +export type ElementRectOptions = ConfigurableWindow & { + initialRect?: DOMRect; +}; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export declare class ElementRect { + #private; + constructor(node: MaybeElementGetter, options?: ElementRectOptions); + get x(): number; + get y(): number; + get width(): number; + get height(): number; + get top(): number; + get right(): number; + get bottom(): number; + get left(): number; + get current(): Rect; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..365dbabcf805856268b18570e7afa698334881d0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/element-rect.svelte.js @@ -0,0 +1,85 @@ +import { extract } from "../extract/extract.svelte.js"; +import { useMutationObserver } from "../use-mutation-observer/use-mutation-observer.svelte.js"; +import { useResizeObserver } from "../use-resize-observer/use-resize-observer.svelte.js"; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export class ElementRect { + #rect = $state({ + x: 0, + y: 0, + width: 0, + height: 0, + top: 0, + right: 0, + bottom: 0, + left: 0, + }); + constructor(node, options = {}) { + this.#rect = { + width: options.initialRect?.width ?? 0, + height: options.initialRect?.height ?? 0, + x: options.initialRect?.x ?? 0, + y: options.initialRect?.y ?? 0, + top: options.initialRect?.top ?? 0, + right: options.initialRect?.right ?? 0, + bottom: options.initialRect?.bottom ?? 0, + left: options.initialRect?.left ?? 0, + }; + const el = $derived(extract(node)); + const update = () => { + if (!el) + return; + const rect = el.getBoundingClientRect(); + this.#rect.width = rect.width; + this.#rect.height = rect.height; + this.#rect.x = rect.x; + this.#rect.y = rect.y; + this.#rect.top = rect.top; + this.#rect.right = rect.right; + this.#rect.bottom = rect.bottom; + this.#rect.left = rect.left; + }; + useResizeObserver(() => el, update, { window: options.window }); + $effect(update); + useMutationObserver(() => el, update, { + attributeFilter: ["style", "class"], + window: options.window, + }); + } + get x() { + return this.#rect.x; + } + get y() { + return this.#rect.y; + } + get width() { + return this.#rect.width; + } + get height() { + return this.#rect.height; + } + get top() { + return this.#rect.top; + } + get right() { + return this.#rect.right; + } + get bottom() { + return this.#rect.bottom; + } + get left() { + return this.#rect.left; + } + get current() { + return this.#rect; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d66f20780675a7a48e8f8ed4aed017878527ef90 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/index.d.ts @@ -0,0 +1 @@ +export { ElementRect } from "./element-rect.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d66f20780675a7a48e8f8ed4aed017878527ef90 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-rect/index.js @@ -0,0 +1 @@ +export { ElementRect } from "./element-rect.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/element-size.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/element-size.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e9e92b9b82856967507656995d65c72d05ae628 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/element-size.svelte.d.ts @@ -0,0 +1,30 @@ +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +import type { MaybeElementGetter } from "../../internal/types.js"; +export type ElementSizeOptions = ConfigurableWindow & { + initialSize?: { + width: number; + height: number; + }; + box?: "content-box" | "border-box"; +}; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export declare class ElementSize { + #private; + constructor(node: MaybeElementGetter, options?: ElementSizeOptions); + get current(): { + width: number; + height: number; + }; + get width(): number; + get height(): number; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/element-size.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/element-size.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..4d021882c625f53785127d98ed6f8aba35608700 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/element-size.svelte.js @@ -0,0 +1,54 @@ +import { defaultWindow } from "../../internal/configurable-globals.js"; +import { get } from "../../internal/utils/get.js"; +/** + * Returns a reactive value holding the size of `node`. + * + * Accepts an `options` object with the following properties: + * - `initialSize`: The initial size of the element. Defaults to `{ width: 0, height: 0 }`. + * - `box`: The box model to use. Can be either `"content-box"` or `"border-box"`. Defaults to `"border-box"`. + * + * @returns an object with `width` and `height` properties. + * + * @see {@link https://runed.dev/docs/utilities/element-size} + */ +export class ElementSize { + #size = $state({ + width: 0, + height: 0, + }); + constructor(node, options = { box: "border-box" }) { + const window = options.window ?? defaultWindow; + this.#size = { + width: options.initialSize?.width ?? 0, + height: options.initialSize?.height ?? 0, + }; + $effect(() => { + if (!window) + return; + const node$ = get(node); + if (!node$) + return; + const observer = new window.ResizeObserver((entries) => { + for (const entry of entries) { + const boxSize = options.box === "content-box" ? entry.contentBoxSize : entry.borderBoxSize; + const boxSizeArr = Array.isArray(boxSize) ? boxSize : [boxSize]; + this.#size.width = boxSizeArr.reduce((acc, size) => Math.max(acc, size.inlineSize), 0); + this.#size.height = boxSizeArr.reduce((acc, size) => Math.max(acc, size.blockSize), 0); + } + }); + observer.observe(node$); + return () => { + observer.disconnect(); + }; + }); + } + get current() { + return this.#size; + } + get width() { + return this.#size.width; + } + get height() { + return this.#size.height; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..42f14866cbddb82cb71ea334737bc2e6cdec4f24 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/index.d.ts @@ -0,0 +1 @@ +export * from "./element-size.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/index.js new file mode 100644 index 0000000000000000000000000000000000000000..42f14866cbddb82cb71ea334737bc2e6cdec4f24 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/element-size/index.js @@ -0,0 +1 @@ +export * from "./element-size.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/extract.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/extract.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d076878a9ce1b7a4a69150e67d91ef778524bd4d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/extract.svelte.d.ts @@ -0,0 +1,6 @@ +import type { MaybeGetter } from "../../internal/types.js"; +/** + * Extracts the value from a getter or a value. + * Optionally, a default value can be provided. + */ +export declare function extract(value: MaybeGetter, defaultValue?: T): T; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/extract.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/extract.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..6ab11772c6cff1190c6b509d05d0304fa821a0c4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/extract.svelte.js @@ -0,0 +1,12 @@ +import { isFunction } from "../../internal/utils/is.js"; +/** + * Extracts the value from a getter or a value. + * Optionally, a default value can be provided. + */ +export function extract(value, defaultValue) { + if (isFunction(value)) { + const getter = value; + return getter() ?? defaultValue ?? getter(); + } + return value ?? defaultValue ?? value; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c8f3467b8e26bd2a0695afe904659812ddb39a6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/index.d.ts @@ -0,0 +1 @@ +export { extract } from "./extract.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1c8f3467b8e26bd2a0695afe904659812ddb39a6 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/extract/index.js @@ -0,0 +1 @@ +export { extract } from "./extract.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3086815fb812b541d14022370e35783e2b8bd3e9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.d.ts @@ -0,0 +1,37 @@ +export type FSMLifecycleFn = (meta: LifecycleFnMeta) => void; +export type LifecycleFnMeta = { + from: StatesT | null; + to: StatesT; + event: EventsT | null; + args: unknown; +}; +export declare function isLifecycleFnMeta(meta: unknown): meta is LifecycleFnMeta; +export type FSMLifecycle = "_enter" | "_exit"; +export type ActionFn = (...args: unknown[]) => StatesT | void; +export type Action = StatesT | ActionFn; +export type StateHandler = { + [e in EventsT]?: Action; +} & { + [k in FSMLifecycle]?: FSMLifecycleFn; +}; +export type Transition = { + [s in StatesT]: StateHandler; +} & { + "*"?: StateHandler; +}; +/** + * Defines a strongly-typed finite state machine. + * + * @see {@link https://runed.dev/docs/utilities/finite-state-machine} + */ +export declare class FiniteStateMachine { + #private; + readonly states: Transition; + constructor(initial: StatesT, states: Transition); + /** Triggers a new event and returns the new state. */ + send(event: EventsT, ...args: unknown[]): StatesT; + /** Debounces the triggering of an event. */ + debounce(wait: number | undefined, event: EventsT, ...args: unknown[]): Promise; + /** The current state. */ + get current(): StatesT; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..88a721df614730b6a163c320d6912652c2c1d81d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/finite-state-machine.svelte.js @@ -0,0 +1,78 @@ +export function isLifecycleFnMeta(meta) { + return (!!meta && + typeof meta === "object" && + "to" in meta && + "from" in meta && + "event" in meta && + "args" in meta); +} +/** + * Defines a strongly-typed finite state machine. + * + * @see {@link https://runed.dev/docs/utilities/finite-state-machine} + */ +export class FiniteStateMachine { + #current = $state(); + states; + #timeout = {}; + constructor(initial, states) { + this.#current = initial; + this.states = states; + this.send = this.send.bind(this); + this.debounce = this.debounce.bind(this); + // synthetically trigger _enter for the initial state. + this.#dispatch("_enter", { from: null, to: initial, event: null, args: [] }); + } + #transition(newState, event, args) { + const metadata = { from: this.#current, to: newState, event, args }; + this.#dispatch("_exit", metadata); + this.#current = newState; + this.#dispatch("_enter", metadata); + } + #dispatch(event, ...args) { + const action = this.states[this.#current]?.[event] ?? this.states["*"]?.[event]; + if (action instanceof Function) { + if (event === "_enter" || event === "_exit") { + if (isLifecycleFnMeta(args[0])) { + action(args[0]); + } + else { + console.warn("Invalid metadata passed to lifecycle function of the FSM."); + } + } + else { + return action(...args); + } + } + else if (typeof action === "string") { + return action; + } + else if (event !== "_enter" && event !== "_exit") { + console.warn("No action defined for event", event, "in state", this.#current); + } + } + /** Triggers a new event and returns the new state. */ + send(event, ...args) { + const newState = this.#dispatch(event, ...args); + if (newState && newState !== this.#current) { + this.#transition(newState, event, args); + } + return this.#current; + } + /** Debounces the triggering of an event. */ + async debounce(wait = 500, event, ...args) { + if (this.#timeout[event]) { + clearTimeout(this.#timeout[event]); + } + return new Promise((resolve) => { + this.#timeout[event] = setTimeout(() => { + delete this.#timeout[event]; + resolve(this.send(event, ...args)); + }, wait); + }); + } + /** The current state. */ + get current() { + return this.#current; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8935ec7dcb34124cd0eb9adfd3b7ffe0978fddea --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/index.d.ts @@ -0,0 +1 @@ +export * from "./finite-state-machine.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8935ec7dcb34124cd0eb9adfd3b7ffe0978fddea --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/finite-state-machine/index.js @@ -0,0 +1 @@ +export * from "./finite-state-machine.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b36e79dfc232999e2b641db542b2da41f8341a1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/index.d.ts @@ -0,0 +1,23 @@ +export * from "./active-element/index.js"; +export * from "./on-click-outside/index.js"; +export * from "./use-debounce/index.js"; +export * from "./element-size/index.js"; +export * from "./use-event-listener/index.js"; +export * from "./is-idle/index.js"; +export * from "./is-mounted/index.js"; +export * from "./state-history/index.js"; +export * from "./previous/index.js"; +export * from "./watch/index.js"; +export * from "./debounced/index.js"; +export * from "./pressed-keys/index.js"; +export * from "./element-rect/index.js"; +export * from "./use-mutation-observer/index.js"; +export * from "./use-resize-observer/index.js"; +export * from "./animation-frames/index.js"; +export * from "./use-intersection-observer/index.js"; +export * from "./is-focus-within/index.js"; +export * from "./finite-state-machine/index.js"; +export * from "./persisted-state/index.js"; +export * from "./use-geolocation/index.js"; +export * from "./context/index.js"; +export * from "./is-in-viewport/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2b36e79dfc232999e2b641db542b2da41f8341a1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/index.js @@ -0,0 +1,23 @@ +export * from "./active-element/index.js"; +export * from "./on-click-outside/index.js"; +export * from "./use-debounce/index.js"; +export * from "./element-size/index.js"; +export * from "./use-event-listener/index.js"; +export * from "./is-idle/index.js"; +export * from "./is-mounted/index.js"; +export * from "./state-history/index.js"; +export * from "./previous/index.js"; +export * from "./watch/index.js"; +export * from "./debounced/index.js"; +export * from "./pressed-keys/index.js"; +export * from "./element-rect/index.js"; +export * from "./use-mutation-observer/index.js"; +export * from "./use-resize-observer/index.js"; +export * from "./animation-frames/index.js"; +export * from "./use-intersection-observer/index.js"; +export * from "./is-focus-within/index.js"; +export * from "./finite-state-machine/index.js"; +export * from "./persisted-state/index.js"; +export * from "./use-geolocation/index.js"; +export * from "./context/index.js"; +export * from "./is-in-viewport/index.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee30c5d33feb57bc2be6db954e0208281862fa5f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/index.d.ts @@ -0,0 +1 @@ +export * from "./is-focus-within.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ee30c5d33feb57bc2be6db954e0208281862fa5f --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/index.js @@ -0,0 +1 @@ +export * from "./is-focus-within.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4425797eec2ae230b6a6c0a723d11ddf8752fb59 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.d.ts @@ -0,0 +1,13 @@ +import type { MaybeElementGetter } from "../../internal/types.js"; +import { type ActiveElementOptions } from "../active-element/active-element.svelte.js"; +export interface IsFocusWithinOptions extends ActiveElementOptions { +} +/** + * Tracks whether the focus is within a target element. + * @see {@link https://runed.dev/docs/utilities/is-focus-within} + */ +export declare class IsFocusWithin { + #private; + constructor(node: MaybeElementGetter, options?: IsFocusWithinOptions); + readonly current: boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..ab8ef14858e33e8ec01f7772f7fa2f27a7083a1a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-focus-within/is-focus-within.svelte.js @@ -0,0 +1,20 @@ +import { ActiveElement, } from "../active-element/active-element.svelte.js"; +import { extract } from "../extract/extract.svelte.js"; +/** + * Tracks whether the focus is within a target element. + * @see {@link https://runed.dev/docs/utilities/is-focus-within} + */ +export class IsFocusWithin { + #node; + #activeElement; + constructor(node, options = {}) { + this.#node = node; + this.#activeElement = new ActiveElement(options); + } + current = $derived.by(() => { + const node = extract(this.#node); + if (node == null) + return false; + return node.contains(this.#activeElement.current); + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8229534a546fc78b44134172b38bc7248b9df70e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/index.d.ts @@ -0,0 +1 @@ +export * from "./is-idle.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8229534a546fc78b44134172b38bc7248b9df70e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/index.js @@ -0,0 +1 @@ +export * from "./is-idle.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d11b94947712c5363e6af2c8a7126746c8afa19 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.d.ts @@ -0,0 +1,38 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableDocument, type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export type IsIdleOptions = ConfigurableDocument & ConfigurableWindow & { + /** + * The events that should set the idle state to `true` + * + * @default ['mousemove', 'mousedown', 'resize', 'keydown', 'touchstart', 'wheel'] + */ + events?: MaybeGetter<(keyof WindowEventMap)[]>; + /** + * The timeout in milliseconds before the idle state is set to `true`. Defaults to 60 seconds. + * + * @default 60000 + */ + timeout?: MaybeGetter; + /** + * Detect document visibility changes + * + * @default false + */ + detectVisibilityChanges?: MaybeGetter; + /** + * The initial state of the idle property + * + * @default false + */ + initialState?: boolean; +}; +/** + * Tracks whether the user is being inactive. + * @see {@link https://runed.dev/docs/utilities/is-idle} + */ +export declare class IsIdle { + #private; + constructor(_options?: IsIdleOptions); + get lastActive(): number; + get current(): boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..0e7ed34ba654292dd6919cf885794cbee16f9eaa --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-idle/is-idle.svelte.js @@ -0,0 +1,63 @@ +import { extract } from "../extract/index.js"; +import { useDebounce } from "../use-debounce/index.js"; +import { useEventListener } from "../use-event-listener/use-event-listener.svelte.js"; +import { defaultWindow, } from "../../internal/configurable-globals.js"; +const DEFAULT_EVENTS = [ + "keypress", + "mousemove", + "touchmove", + "click", + "scroll", +]; +const DEFAULT_OPTIONS = { + events: DEFAULT_EVENTS, + initialState: false, + timeout: 60000, +}; +/** + * Tracks whether the user is being inactive. + * @see {@link https://runed.dev/docs/utilities/is-idle} + */ +export class IsIdle { + #current = $state(false); + #lastActive = $state(Date.now()); + constructor(_options) { + const opts = { + ...DEFAULT_OPTIONS, + ..._options, + }; + const window = opts.window ?? defaultWindow; + const document = opts.document ?? window?.document; + const timeout = $derived(extract(opts.timeout)); + const events = $derived(extract(opts.events)); + const detectVisibilityChanges = $derived(extract(opts.detectVisibilityChanges)); + this.#current = opts.initialState; + const debouncedReset = useDebounce(() => { + this.#current = true; + }, () => timeout); + debouncedReset(); + const handleActivity = () => { + this.#current = false; + this.#lastActive = Date.now(); + debouncedReset(); + }; + useEventListener(() => window, events, () => { + handleActivity(); + }, { passive: true }); + $effect(() => { + if (!detectVisibilityChanges || !document) + return; + useEventListener(document, ["visibilitychange"], () => { + if (document.hidden) + return; + handleActivity(); + }); + }); + } + get lastActive() { + return this.#lastActive; + } + get current() { + return this.#current; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0ee7bc8bc6c6289d25e84288ece423f17b64d70 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/index.d.ts @@ -0,0 +1 @@ +export * from "./is-in-viewport.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b0ee7bc8bc6c6289d25e84288ece423f17b64d70 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/index.js @@ -0,0 +1 @@ +export * from "./is-in-viewport.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5db751e2f592043031e451ceca94b9b3d6570ee5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.d.ts @@ -0,0 +1,14 @@ +import type { ConfigurableWindow } from "../../internal/configurable-globals.js"; +import type { MaybeElementGetter } from "../../internal/types.js"; +import { type UseIntersectionObserverOptions } from "../use-intersection-observer/use-intersection-observer.svelte.js"; +export type IsInViewportOptions = ConfigurableWindow & UseIntersectionObserverOptions; +/** + * Tracks if an element is visible within the current viewport. + * + * @see {@link https://runed.dev/docs/utilities/is-in-viewport} + */ +export declare class IsInViewport { + #private; + constructor(node: MaybeElementGetter, options?: IsInViewportOptions); + get current(): boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..873b9dcf5645dab56e0c979a70d0c45569cf4a73 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-in-viewport/is-in-viewport.svelte.js @@ -0,0 +1,25 @@ +import { useIntersectionObserver, } from "../use-intersection-observer/use-intersection-observer.svelte.js"; +/** + * Tracks if an element is visible within the current viewport. + * + * @see {@link https://runed.dev/docs/utilities/is-in-viewport} + */ +export class IsInViewport { + #isInViewport = $state(false); + constructor(node, options) { + useIntersectionObserver(node, (intersectionObserverEntries) => { + let isIntersecting = this.#isInViewport; + let latestTime = 0; + for (const entry of intersectionObserverEntries) { + if (entry.time >= latestTime) { + latestTime = entry.time; + isIntersecting = entry.isIntersecting; + } + } + this.#isInViewport = isIntersecting; + }, options); + } + get current() { + return this.#isInViewport; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c573eaaf0f24f0bbea130330c640886c1ee875e0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/index.d.ts @@ -0,0 +1 @@ +export * from "./is-mounted.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c573eaaf0f24f0bbea130330c640886c1ee875e0 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/index.js @@ -0,0 +1 @@ +export * from "./is-mounted.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ce167152a074e1b8892da99fe63b5535db07102 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.d.ts @@ -0,0 +1,11 @@ +/** + * Returns an object with the mounted state of the component + * that invokes this function. + * + * @see {@link https://runed.dev/docs/utilities/is-mounted} + */ +export declare class IsMounted { + #private; + constructor(); + get current(): boolean; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..eb7a3111f28955e3b92f131cd90a35526b93ccdd --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/is-mounted/is-mounted.svelte.js @@ -0,0 +1,21 @@ +import { untrack } from "svelte"; +/** + * Returns an object with the mounted state of the component + * that invokes this function. + * + * @see {@link https://runed.dev/docs/utilities/is-mounted} + */ +export class IsMounted { + #isMounted = $state(false); + constructor() { + $effect(() => { + untrack(() => (this.#isMounted = true)); + return () => { + this.#isMounted = false; + }; + }); + } + get current() { + return this.#isMounted; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e83b9fe4f3a1b0aca68648e60a91097b93ac7f33 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/index.d.ts @@ -0,0 +1 @@ +export * from "./on-click-outside.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e83b9fe4f3a1b0aca68648e60a91097b93ac7f33 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/index.js @@ -0,0 +1 @@ +export * from "./on-click-outside.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a451b7e0ac46aa665dd5a80b894616132c798da --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.d.ts @@ -0,0 +1,63 @@ +import { type ConfigurableDocument, type ConfigurableWindow } from "../../internal/configurable-globals.js"; +import type { MaybeElementGetter } from "../../internal/types.js"; +export type OnClickOutsideOptions = ConfigurableWindow & ConfigurableDocument & { + /** + * Whether the click outside handler is enabled by default or not. + * If set to false, the handler will not be active until enabled by + * calling the returned `start` function + * + * @default true + */ + immediate?: boolean; + /** + * Controls whether focus events from iframes trigger the callback. + * + * Since iframe click events don't bubble to the parent document, + * you may want to enable this if you need to detect when users + * interact with iframe content. + * + * @default false + */ + detectIframe?: boolean; +}; +/** + * A utility that calls a given callback when a click event occurs outside of + * a specified container element. + * + * @template T - The type of the container element, defaults to HTMLElement. + * @param {MaybeElementGetter} container - The container element or a getter function that returns the container element. + * @param {() => void} callback - The callback function to call when a click event occurs outside of the container. + * @param {OnClickOutsideOptions} [opts={}] - Optional configuration object. + * @param {ConfigurableDocument} [opts.document=defaultDocument] - The document object to use, defaults to the global document. + * @param {boolean} [opts.immediate=true] - Whether the click outside handler is enabled by default or not. + * @param {boolean} [opts.detectIframe=false] - Controls whether focus events from iframes trigger the callback. + * + * @example + * ```svelte + * + * + *
+ * Inside + *
+ * + * + * + * Enabled: {clickOutside.enabled} + *``` + * @see {@link https://runed.dev/docs/utilities/on-click-outside} + */ +export declare function onClickOutside(container: MaybeElementGetter, callback: (event: PointerEvent | FocusEvent) => void, opts?: OnClickOutsideOptions): { + /** Stop listening for click events outside the container. */ + stop: () => boolean; + /** Start listening for click events outside the container. */ + start: () => boolean; + /** Whether the click outside handler is currently enabled or not. */ + readonly enabled: boolean; +}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..f0676a36a12c980e729a2bc88b836b71635c5b39 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/on-click-outside/on-click-outside.svelte.js @@ -0,0 +1,182 @@ +import { defaultWindow, } from "../../internal/configurable-globals.js"; +import { getActiveElement, getOwnerDocument, isOrContainsTarget } from "../../internal/utils/dom.js"; +import { noop } from "../../internal/utils/function.js"; +import { isElement } from "../../internal/utils/is.js"; +import { sleep } from "../../internal/utils/sleep.js"; +import { on } from "svelte/events"; +import { extract } from "../extract/extract.svelte.js"; +import { useDebounce } from "../use-debounce/use-debounce.svelte.js"; +import { watch } from "../watch/watch.svelte.js"; +/** + * A utility that calls a given callback when a click event occurs outside of + * a specified container element. + * + * @template T - The type of the container element, defaults to HTMLElement. + * @param {MaybeElementGetter} container - The container element or a getter function that returns the container element. + * @param {() => void} callback - The callback function to call when a click event occurs outside of the container. + * @param {OnClickOutsideOptions} [opts={}] - Optional configuration object. + * @param {ConfigurableDocument} [opts.document=defaultDocument] - The document object to use, defaults to the global document. + * @param {boolean} [opts.immediate=true] - Whether the click outside handler is enabled by default or not. + * @param {boolean} [opts.detectIframe=false] - Controls whether focus events from iframes trigger the callback. + * + * @example + * ```svelte + * + * + *
+ * Inside + *
+ * + * + * + * Enabled: {clickOutside.enabled} + *``` + * @see {@link https://runed.dev/docs/utilities/on-click-outside} + */ +export function onClickOutside(container, callback, opts = {}) { + const { window = defaultWindow, immediate = true, detectIframe = false } = opts; + const document = opts.document ?? window?.document; + const node = $derived(extract(container)); + const nodeOwnerDocument = $derived(getOwnerDocument(node, document)); + let enabled = $state(immediate); + let pointerDownIntercepted = false; + let removeClickListener = noop; + let removeListeners = noop; + const handleClickOutside = useDebounce((e) => { + if (!node || !nodeOwnerDocument) { + removeClickListener(); + return; + } + if (pointerDownIntercepted === true || !isValidEvent(e, node, nodeOwnerDocument)) { + removeClickListener(); + return; + } + if (e.pointerType === "touch") { + /** + * If the pointer type is touch, we add a listener to wait for the click + * event that will follow the pointerdown event if the user interacts in a way + * that would trigger a click event. + * + * This prevents us from prematurely calling the callback if the user is simply + * scrolling or dragging the page. + */ + removeClickListener(); + removeClickListener = on(nodeOwnerDocument, "click", () => callback(e), { + once: true, + }); + } + else { + /** + * If the pointer type is not touch, we can directly call the callback function + * as the interaction is likely a mouse or pen input which does not require + * additional handling. + */ + callback(e); + } + }, 10); + function addListeners() { + if (!nodeOwnerDocument || !window || !node) + return noop; + const events = [ + /** + * CAPTURE INTERACTION START + * Mark the pointerdown event as intercepted to indicate that an interaction + * has started. This helps in distinguishing between valid and invalid events. + */ + on(nodeOwnerDocument, "pointerdown", (e) => { + if (isValidEvent(e, node, nodeOwnerDocument)) { + pointerDownIntercepted = true; + } + }, { capture: true }), + /** + * BUBBLE INTERACTION START + * Mark the pointerdown event as non-intercepted. Debounce `handleClickOutside` to + * avoid prematurely checking if other events were intercepted. + */ + on(nodeOwnerDocument, "pointerdown", (e) => { + pointerDownIntercepted = false; + handleClickOutside(e); + }), + ]; + if (detectIframe) { + events.push( + /** + * DETECT IFRAME INTERACTIONS + * + * We add a blur event listener to the window to detect when the user + * interacts with an iframe. If the active element is an iframe and it + * is not a descendant of the container, we call the callback function. + */ + on(window, "blur", async (e) => { + await sleep(); + const activeElement = getActiveElement(nodeOwnerDocument); + if (activeElement?.tagName === "IFRAME" && !isOrContainsTarget(node, activeElement)) { + callback(e); + } + })); + } + return () => { + for (const event of events) { + event(); + } + }; + } + function cleanup() { + pointerDownIntercepted = false; + handleClickOutside.cancel(); + removeClickListener(); + removeListeners(); + } + watch([() => enabled, () => node], ([enabled$, node$]) => { + if (enabled$ && node$) { + removeListeners(); + removeListeners = addListeners(); + } + else { + cleanup(); + } + }); + $effect(() => { + return () => { + cleanup(); + }; + }); + return { + /** Stop listening for click events outside the container. */ + stop: () => (enabled = false), + /** Start listening for click events outside the container. */ + start: () => (enabled = true), + /** Whether the click outside handler is currently enabled or not. */ + get enabled() { + return enabled; + }, + }; +} +function isValidEvent(e, container, defaultDocument) { + if ("button" in e && e.button > 0) + return false; + const target = e.target; + if (!isElement(target)) + return false; + const ownerDocument = getOwnerDocument(target, defaultDocument); + if (!ownerDocument) + return false; + // handle the case where a user may have pressed a pseudo element by + // checking the bounding rect of the container + if (target === container) { + const rect = container.getBoundingClientRect(); + const wasInsideClick = rect.top <= e.clientY && + e.clientY <= rect.top + rect.height && + rect.left <= e.clientX && + e.clientX <= rect.left + rect.width; + return !wasInsideClick; + } + return ownerDocument.documentElement.contains(target) && !isOrContainsTarget(container, target); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..062847f8f6ed8dbc4ff2d684a953e6b3bb67bce8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/index.d.ts @@ -0,0 +1 @@ +export * from "./persisted-state.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/index.js new file mode 100644 index 0000000000000000000000000000000000000000..062847f8f6ed8dbc4ff2d684a953e6b3bb67bce8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/index.js @@ -0,0 +1 @@ +export * from "./persisted-state.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..934df6db4201b30fcf6d6dfbb9767686affac197 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.d.ts @@ -0,0 +1,29 @@ +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +type Serializer = { + serialize: (value: T) => string; + deserialize: (value: string) => T; +}; +type StorageType = "local" | "session"; +type PersistedStateOptions = { + /** The storage type to use. Defaults to `local`. */ + storage?: StorageType; + /** The serializer to use. Defaults to `JSON.stringify` and `JSON.parse`. */ + serializer?: Serializer; + /** Whether to sync with the state changes from other tabs. Defaults to `true`. */ + syncTabs?: boolean; +} & ConfigurableWindow; +/** + * Creates reactive state that is persisted and synchronized across browser sessions and tabs using Web Storage. + * @param key The unique key used to store the state in the storage. + * @param initialValue The initial value of the state if not already present in the storage. + * @param options Configuration options including storage type, serializer for complex data types, and whether to sync state changes across tabs. + * + * @see {@link https://runed.dev/docs/utilities/persisted-state} + */ +export declare class PersistedState { + #private; + constructor(key: string, initialValue: T, options?: PersistedStateOptions); + get current(): T; + set current(newValue: T); +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..4352f0258466954bf2d481b60f4f275b2bbae085 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/persisted-state/persisted-state.svelte.js @@ -0,0 +1,74 @@ +import { defaultWindow } from "../../internal/configurable-globals.js"; +import { on } from "svelte/events"; +import { createSubscriber } from "svelte/reactivity"; +function getStorage(storageType, window) { + switch (storageType) { + case "local": + return window.localStorage; + case "session": + return window.sessionStorage; + } +} +/** + * Creates reactive state that is persisted and synchronized across browser sessions and tabs using Web Storage. + * @param key The unique key used to store the state in the storage. + * @param initialValue The initial value of the state if not already present in the storage. + * @param options Configuration options including storage type, serializer for complex data types, and whether to sync state changes across tabs. + * + * @see {@link https://runed.dev/docs/utilities/persisted-state} + */ +export class PersistedState { + #current = $state(); + #key; + #serializer; + #storage; + #subscribe; + constructor(key, initialValue, options = {}) { + const { storage: storageType = "local", serializer = { serialize: JSON.stringify, deserialize: JSON.parse }, syncTabs = true, window = defaultWindow, } = options; + this.#current = initialValue; + this.#key = key; + this.#serializer = serializer; + if (window === undefined) + return; + const storage = getStorage(storageType, window); + this.#storage = storage; + const existingValue = storage.getItem(key); + if (existingValue !== null) { + this.#deserialize(existingValue); + } + if (syncTabs && storageType === "local") { + this.#subscribe = createSubscriber(() => { + return on(window, "storage", this.#handleStorageEvent); + }); + } + } + get current() { + this.#subscribe?.(); + return this.#current; + } + set current(newValue) { + this.#current = newValue; + this.#serialize(newValue); + } + #handleStorageEvent = (event) => { + if (event.key !== this.#key || event.newValue === null) + return; + this.#deserialize(event.newValue); + }; + #deserialize(value) { + try { + this.#current = this.#serializer.deserialize(value); + } + catch (error) { + console.error(`Error when parsing "${value}" from persisted store "${this.#key}"`, error); + } + } + #serialize(value) { + try { + this.#storage?.setItem(this.#key, this.#serializer.serialize(value)); + } + catch (error) { + console.error(`Error when writing value from persisted store "${this.#key}" to ${this.#storage}`, error); + } + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8cb62f38dfe730ed6f31d39c6e3c8e45eaf46ed5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/index.d.ts @@ -0,0 +1 @@ +export { PressedKeys } from "./pressed-keys.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8cb62f38dfe730ed6f31d39c6e3c8e45eaf46ed5 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/index.js @@ -0,0 +1 @@ +export { PressedKeys } from "./pressed-keys.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f662c8d2ecd14c02aacf7ed8a4db3d5b542153dd --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.d.ts @@ -0,0 +1,13 @@ +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export type PressedKeysOptions = ConfigurableWindow; +/** + * Tracks which keys are currently pressed. + * + * @see {@link https://runed.dev/docs/utilities/pressed-keys} + */ +export declare class PressedKeys { + #private; + constructor(options?: PressedKeysOptions); + has(...keys: string[]): boolean; + get all(): string[]; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..4ac6a0c7cee12d3976093d8a3e85fc5a3a607d4c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/pressed-keys/pressed-keys.svelte.js @@ -0,0 +1,33 @@ +import { defaultWindow } from "../../internal/configurable-globals.js"; +import { useEventListener } from "../use-event-listener/use-event-listener.svelte.js"; +/** + * Tracks which keys are currently pressed. + * + * @see {@link https://runed.dev/docs/utilities/pressed-keys} + */ +export class PressedKeys { + #pressedKeys = $state([]); + constructor(options = {}) { + const { window = defaultWindow } = options; + this.has = this.has.bind(this); + if (!window) + return; + useEventListener(window, "keydown", (e) => { + const key = e.key.toLowerCase(); + if (!this.#pressedKeys.includes(key)) { + this.#pressedKeys.push(key); + } + }); + useEventListener(window, "keyup", (e) => { + const key = e.key.toLowerCase(); + this.#pressedKeys = this.#pressedKeys.filter((k) => k !== key); + }); + } + has(...keys) { + const normalizedKeys = keys.map((key) => key.toLowerCase()); + return normalizedKeys.every((key) => this.#pressedKeys.includes(key)); + } + get all() { + return this.#pressedKeys; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c45eae4698060fb949ee0e56ccc6ea6a72f3603 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/index.d.ts @@ -0,0 +1 @@ +export * from "./previous.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9c45eae4698060fb949ee0e56ccc6ea6a72f3603 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/index.js @@ -0,0 +1 @@ +export * from "./previous.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/previous.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/previous.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a089e1ea75d987341b2bc3884608204b1b87ba2 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/previous.svelte.d.ts @@ -0,0 +1,11 @@ +import type { Getter } from "../../internal/types.js"; +/** + * Holds the previous value of a getter. + * + * @see {@link https://runed.dev/docs/utilities/previous} + */ +export declare class Previous { + #private; + constructor(getter: Getter); + get current(): T | undefined; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/previous.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/previous.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..f1b89b2033d3d89ee39bbc71efe6f0b285c56f70 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/previous/previous.svelte.js @@ -0,0 +1,18 @@ +/** + * Holds the previous value of a getter. + * + * @see {@link https://runed.dev/docs/utilities/previous} + */ +export class Previous { + #previous = $state(undefined); + #curr; + constructor(getter) { + $effect(() => { + this.#previous = this.#curr; + this.#curr = getter(); + }); + } + get current() { + return this.#previous; + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0c4565df2f2a7394e4f4d405d57cd1f7dde9020 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/index.d.ts @@ -0,0 +1 @@ +export * from "./state-history.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a0c4565df2f2a7394e4f4d405d57cd1f7dde9020 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/index.js @@ -0,0 +1 @@ +export * from "./state-history.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/state-history.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/state-history.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92e599f1fc4c058055a2a0892007465850f9f8cb --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/state-history.svelte.d.ts @@ -0,0 +1,23 @@ +import type { MaybeGetter, Setter } from "../../internal/types.js"; +type LogEvent = { + snapshot: T; + timestamp: number; +}; +type StateHistoryOptions = { + capacity?: MaybeGetter; +}; +/** + * Tracks the change history of a value, providing undo and redo capabilities. + * + * @see {@link https://runed.dev/docs/utilities/state-history} + */ +export declare class StateHistory { + #private; + log: LogEvent[]; + readonly canUndo: boolean; + readonly canRedo: boolean; + constructor(value: MaybeGetter, set: Setter, options?: StateHistoryOptions); + undo(): void; + redo(): void; +} +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/state-history.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/state-history.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..85bef0990d17a64b87653ff064949987c17fac75 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/state-history/state-history.svelte.js @@ -0,0 +1,58 @@ +import { watch } from "../watch/watch.svelte.js"; +import { get } from "../../internal/utils/get.js"; +/** + * Tracks the change history of a value, providing undo and redo capabilities. + * + * @see {@link https://runed.dev/docs/utilities/state-history} + */ +export class StateHistory { + #redoStack = $state([]); + #ignoreUpdate = false; + #set; + log = $state([]); + canUndo = $derived(this.log.length > 1); + canRedo = $derived(this.#redoStack.length > 0); + constructor(value, set, options) { + this.#redoStack = []; + this.#set = set; + this.undo = this.undo.bind(this); + this.redo = this.redo.bind(this); + const addEvent = (event) => { + this.log.push(event); + const capacity$ = get(options?.capacity); + if (capacity$ && this.log.length > capacity$) { + this.log = this.log.slice(-capacity$); + } + }; + watch(() => get(value), (v) => { + if (this.#ignoreUpdate) { + this.#ignoreUpdate = false; + return; + } + addEvent({ snapshot: v, timestamp: new Date().getTime() }); + this.#redoStack = []; + }); + watch(() => get(options?.capacity), (c) => { + if (!c) + return; + this.log = this.log.slice(-c); + }); + } + undo() { + const [prev, curr] = this.log.slice(-2); + if (!curr || !prev) + return; + this.#ignoreUpdate = true; + this.#redoStack.push(curr); + this.log.pop(); + this.#set(prev.snapshot); + } + redo() { + const nextEvent = this.#redoStack.pop(); + if (!nextEvent) + return; + this.#ignoreUpdate = true; + this.log.push(nextEvent); + this.#set(nextEvent.snapshot); + } +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b167be0bb339c67a97696ea8f29ffb16b0cf98a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/index.d.ts @@ -0,0 +1 @@ +export * from "./use-debounce.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1b167be0bb339c67a97696ea8f29ffb16b0cf98a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/index.js @@ -0,0 +1 @@ +export * from "./use-debounce.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6574037817e9ce4de7184309e62ae665e24b6968 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.d.ts @@ -0,0 +1,25 @@ +import type { MaybeGetter } from "../../internal/types.js"; +type UseDebounceReturn = ((this: unknown, ...args: Args) => Promise) & { + cancel: () => void; + runScheduledNow: () => Promise; + pending: boolean; +}; +/** + * Function that takes a callback, and returns a debounced version of it. + * When calling the debounced function, it will wait for the specified time + * before calling the original callback. If the debounced function is called + * again before the time has passed, the timer will be reset. + * + * You can await the debounced function to get the value when it is eventually + * called. + * + * The second parameter is the time to wait before calling the original callback. + * Alternatively, it can also be a getter function that returns the time to wait. + * + * @see {@link https://runed.dev/docs/utilities/use-debounce} + * + * @param callback The callback to call when the time has passed. + * @param wait The length of time to wait in ms, defaults to 250. + */ +export declare function useDebounce(callback: (...args: Args) => Return, wait?: MaybeGetter): UseDebounceReturn; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..02e09183d6b9d4e37a2171372807b1a46dfcf81b --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-debounce/use-debounce.svelte.js @@ -0,0 +1,90 @@ +/** + * Function that takes a callback, and returns a debounced version of it. + * When calling the debounced function, it will wait for the specified time + * before calling the original callback. If the debounced function is called + * again before the time has passed, the timer will be reset. + * + * You can await the debounced function to get the value when it is eventually + * called. + * + * The second parameter is the time to wait before calling the original callback. + * Alternatively, it can also be a getter function that returns the time to wait. + * + * @see {@link https://runed.dev/docs/utilities/use-debounce} + * + * @param callback The callback to call when the time has passed. + * @param wait The length of time to wait in ms, defaults to 250. + */ +export function useDebounce(callback, wait = 250) { + let context = $state(null); + function debounced(...args) { + if (context) { + // Old context will be reused so callers awaiting the promise will get the + // new value + if (context.timeout) { + clearTimeout(context.timeout); + } + } + else { + // No old context, create a new one + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + context = { + timeout: null, + runner: null, + promise, + resolve: resolve, + reject: reject, + }; + } + context.runner = async () => { + // Grab the context and reset it + // -> new debounced calls will create a new context + if (!context) + return; + const ctx = context; + context = null; + try { + ctx.resolve(await callback.apply(this, args)); + } + catch (error) { + ctx.reject(error); + } + }; + context.timeout = setTimeout(context.runner, typeof wait === "function" ? wait() : wait); + return context.promise; + } + debounced.cancel = async () => { + if (!context || context.timeout === null) { + // Wait one event loop to see if something triggered the debounced function + await new Promise((resolve) => setTimeout(resolve, 0)); + if (!context || context.timeout === null) + return; + } + clearTimeout(context.timeout); + context.reject("Cancelled"); + context = null; + }; + debounced.runScheduledNow = async () => { + if (!context || !context.timeout) { + // Wait one event loop to see if something triggered the debounced function + await new Promise((resolve) => setTimeout(resolve, 0)); + if (!context || !context.timeout) + return; + } + clearTimeout(context.timeout); + context.timeout = null; + await context.runner?.(); + }; + Object.defineProperty(debounced, "pending", { + enumerable: true, + get() { + return !!context?.timeout; + }, + }); + return debounced; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e5c0750c18a6e474dc17b914744f8171656f789 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/index.d.ts @@ -0,0 +1 @@ +export * from "./use-event-listener.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e5c0750c18a6e474dc17b914744f8171656f789 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/index.js @@ -0,0 +1 @@ +export * from "./use-event-listener.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b1ad3a5e55e40fa40abf21b376d009ba61ba23b --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.d.ts @@ -0,0 +1,51 @@ +import type { MaybeGetter } from "../../internal/types.js"; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: Window, event: WindowEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: Document, event: DocumentEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: TElement, event: HTMLElementEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: (this: MediaQueryList, event: MediaQueryListEventMap[TEvent]) => unknown, options?: AddEventListenerOptions): void; +/** + * Adds an event listener to the specified target element for the given event(s), and returns a function to remove it. + * @param target The target element to add the event listener to. + * @param event The event(s) to listen for. + * @param handler The function to be called when the event is triggered. + * @param options An optional object that specifies characteristics about the event listener. + * + * @see {@link https://runed.dev/docs/utilities/use-event-listener} + */ +export declare function useEventListener(target: MaybeGetter, event: MaybeGetter, handler: EventListener, options?: AddEventListenerOptions): void; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..9b0d63d149c5bd5cc52f0cb6b794e4725a223c5a --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-event-listener/use-event-listener.svelte.js @@ -0,0 +1,18 @@ +import { extract } from "../extract/extract.svelte.js"; +import { on } from "svelte/events"; +export function useEventListener(_target, _events, handler, options) { + $effect(() => { + const target = extract(_target); + const events = extract(_events); + if (target === undefined || target === null) + return; + if (Array.isArray(events)) { + for (const event of events) { + $effect(() => on(target, event, handler, options)); + } + } + else { + return on(target, events, handler, options); + } + }); +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..17cc63e7f2e569664aa659e76dcef850cd75df88 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/index.d.ts @@ -0,0 +1 @@ +export * from "./use-geolocation.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/index.js new file mode 100644 index 0000000000000000000000000000000000000000..17cc63e7f2e569664aa659e76dcef850cd75df88 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/index.js @@ -0,0 +1 @@ +export * from "./use-geolocation.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ae0d88349aa12bce2eca22a77f003b5f4e983ac --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.d.ts @@ -0,0 +1,27 @@ +import { type ConfigurableNavigator } from "../../internal/configurable-globals.js"; +export type UseGeolocationOptions = Partial & { + /** + * Whether to start the watcher immediately upon creation. If set to `false`, the watcher + * will only start tracking the position when `resume()` is called. + * + * @defaultValue true + */ + immediate?: boolean; +} & ConfigurableNavigator; +export type UseGeolocationPosition = Omit & { + coords: Omit; +}; +export type UseGeolocationReturn = { + readonly isSupported: boolean; + readonly position: UseGeolocationPosition; + readonly error: GeolocationPositionError | null; + readonly isPaused: boolean; + resume: () => void; + pause: () => void; +}; +/** + * Reactive access to the browser's [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API). + * + * @see https://runed.dev/docs/utilities/use-geolocation + */ +export declare function useGeolocation(options?: UseGeolocationOptions): UseGeolocationReturn; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..9eba5e2fae69d022cac15d2c8435fc992948bf72 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-geolocation/use-geolocation.svelte.js @@ -0,0 +1,71 @@ +import { defaultNavigator, } from "../../internal/configurable-globals.js"; +/** + * Reactive access to the browser's [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API). + * + * @see https://runed.dev/docs/utilities/use-geolocation + */ +export function useGeolocation(options = {}) { + const { enableHighAccuracy = true, maximumAge = 30000, timeout = 27000, immediate = true, navigator = defaultNavigator, } = options; + const isSupported = Boolean(navigator); + let error = $state.raw(null); + let position = $state({ + timestamp: 0, + coords: { + accuracy: 0, + latitude: Number.POSITIVE_INFINITY, + longitude: Number.POSITIVE_INFINITY, + altitude: null, + altitudeAccuracy: null, + heading: null, + speed: null, + }, + }); + let isPaused = $state(false); + function updatePosition(_position) { + error = null; + position.timestamp = _position.timestamp; + position.coords.accuracy = _position.coords.accuracy; + position.coords.altitude = _position.coords.altitude; + position.coords.altitudeAccuracy = _position.coords.altitudeAccuracy; + position.coords.heading = _position.coords.heading; + position.coords.latitude = _position.coords.latitude; + position.coords.longitude = _position.coords.longitude; + position.coords.speed = _position.coords.speed; + } + let watcher; + function resume() { + if (!navigator) + return; + watcher = navigator.geolocation.watchPosition(updatePosition, (err) => (error = err), { + enableHighAccuracy, + maximumAge, + timeout, + }); + isPaused = false; + } + function pause() { + if (watcher && navigator) { + navigator.geolocation.clearWatch(watcher); + } + isPaused = true; + } + $effect(() => { + if (immediate) + resume(); + return () => pause(); + }); + return { + get isSupported() { + return isSupported; + }, + position, + get error() { + return error; + }, + get isPaused() { + return isPaused; + }, + resume, + pause, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d972de5d99c4a3c9cab2abb66769e5f3f0c69cd8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/index.d.ts @@ -0,0 +1 @@ +export * from "./use-intersection-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d972de5d99c4a3c9cab2abb66769e5f3f0c69cd8 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/index.js @@ -0,0 +1 @@ +export * from "./use-intersection-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..57dba73ebc3a855eb8b5c26b447ac600bc46d66e --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.d.ts @@ -0,0 +1,28 @@ +import type { MaybeElementGetter, MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface UseIntersectionObserverOptions extends Omit, ConfigurableWindow { + /** + * Whether to start the observer immediately upon creation. If set to `false`, the observer + * will only start observing when `resume()` is called. + * + * @defaultValue true + */ + immediate?: boolean; + /** + * The root document/element to use as the bounding box for the intersection. + */ + root?: MaybeElementGetter; +} +/** + * Watch for intersection changes of a target element. + * + * @see https://runed.dev/docs/utilities/useIntersectionObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver IntersectionObserver MDN + */ +export declare function useIntersectionObserver(target: MaybeGetter, callback: IntersectionObserverCallback, options?: UseIntersectionObserverOptions): { + readonly isActive: boolean; + stop: () => void; + pause(): void; + resume(): void; +}; +export type UseIntersectionObserverReturn = ReturnType; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..dfa5e4f6c93f80fce0f1a16ee3ee311d04216fbc --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-intersection-observer/use-intersection-observer.svelte.js @@ -0,0 +1,49 @@ +import { extract } from "../extract/extract.svelte.js"; +import { get } from "../../internal/utils/get.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Watch for intersection changes of a target element. + * + * @see https://runed.dev/docs/utilities/useIntersectionObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver IntersectionObserver MDN + */ +export function useIntersectionObserver(target, callback, options = {}) { + const { root, rootMargin = "0px", threshold = 0.1, immediate = true, window = defaultWindow, } = options; + let isActive = $state(immediate); + let observer; + const targets = $derived.by(() => { + const value = extract(target); + return new Set(value ? (Array.isArray(value) ? value : [value]) : []); + }); + const stop = $effect.root(() => { + $effect(() => { + if (!targets.size || !isActive || !window) + return; + observer = new window.IntersectionObserver(callback, { + rootMargin, + root: get(root), + threshold, + }); + for (const el of targets) + observer.observe(el); + return () => { + observer?.disconnect(); + }; + }); + }); + $effect(() => { + return stop; + }); + return { + get isActive() { + return isActive; + }, + stop, + pause() { + isActive = false; + }, + resume() { + isActive = true; + }, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a9360150f5f5a38cf0110017aa3f1ccd8fb6734 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/index.d.ts @@ -0,0 +1 @@ +export * from "./use-mutation-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8a9360150f5f5a38cf0110017aa3f1ccd8fb6734 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/index.js @@ -0,0 +1 @@ +export * from "./use-mutation-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4f1a3c918d520792ca8074b7dcc8fd15442b82d --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.d.ts @@ -0,0 +1,15 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface UseMutationObserverOptions extends MutationObserverInit, ConfigurableWindow { +} +/** + * Watch for changes being made to the DOM tree. + * + * @see https://runed.dev/docs/utilities/useMutationObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN + */ +export declare function useMutationObserver(target: MaybeGetter, callback: MutationCallback, options?: UseMutationObserverOptions): { + stop: () => void; + takeRecords(): MutationRecord[] | undefined; +}; +export type UseMutationObserverReturn = ReturnType; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..768f03cc6b3b5b4cbb9fe23763289b19ddc43f96 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-mutation-observer/use-mutation-observer.svelte.js @@ -0,0 +1,38 @@ +import { extract } from "../extract/extract.svelte.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Watch for changes being made to the DOM tree. + * + * @see https://runed.dev/docs/utilities/useMutationObserver + * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN + */ +export function useMutationObserver(target, callback, options = {}) { + const { window = defaultWindow } = options; + let observer; + const targets = $derived.by(() => { + const value = extract(target); + return new Set(value ? (Array.isArray(value) ? value : [value]) : []); + }); + const stop = $effect.root(() => { + $effect(() => { + if (!targets.size || !window) + return; + observer = new window.MutationObserver(callback); + for (const el of targets) + observer.observe(el, options); + return () => { + observer?.disconnect(); + observer = undefined; + }; + }); + }); + $effect(() => { + return stop; + }); + return { + stop, + takeRecords() { + return observer?.takeRecords(); + }, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..532ba69de8269827446ce0d82bb285a491be3788 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/index.d.ts @@ -0,0 +1 @@ +export { useResizeObserver } from "./use-resize-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..532ba69de8269827446ce0d82bb285a491be3788 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/index.js @@ -0,0 +1 @@ +export { useResizeObserver } from "./use-resize-observer.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84d0e1dd7155560149472040f3f249b60d78f1c4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.d.ts @@ -0,0 +1,39 @@ +import type { MaybeGetter } from "../../internal/types.js"; +import { type ConfigurableWindow } from "../../internal/configurable-globals.js"; +export interface ResizeObserverSize { + readonly inlineSize: number; + readonly blockSize: number; +} +export interface ResizeObserverEntry { + readonly target: Element; + readonly contentRect: DOMRectReadOnly; + readonly borderBoxSize?: ReadonlyArray; + readonly contentBoxSize?: ReadonlyArray; + readonly devicePixelContentBoxSize?: ReadonlyArray; +} +export type ResizeObserverCallback = (entries: ReadonlyArray, observer: ResizeObserver) => void; +export interface UseResizeObserverOptions extends ConfigurableWindow { + /** + * Sets which box model the observer will observe changes to. Possible values + * are `content-box` (the default), `border-box` and `device-pixel-content-box`. + * + * @default 'content-box' + */ + box?: ResizeObserverBoxOptions; +} +declare class ResizeObserver { + constructor(callback: ResizeObserverCallback); + disconnect(): void; + observe(target: Element, options?: UseResizeObserverOptions): void; + unobserve(target: Element): void; +} +/** + * Reports changes to the dimensions of an Element's content or the border-box + * + * @see https://runed.dev/docs/utilities/useResizeObserver + */ +export declare function useResizeObserver(target: MaybeGetter, callback: ResizeObserverCallback, options?: UseResizeObserverOptions): { + stop: () => void; +}; +export type UseResizeObserverReturn = ReturnType; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..177ab31cb0707d7a1a3e4c279dee50b50295f348 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/use-resize-observer/use-resize-observer.svelte.js @@ -0,0 +1,34 @@ +import { extract } from "../extract/extract.svelte.js"; +import { defaultWindow } from "../../internal/configurable-globals.js"; +/** + * Reports changes to the dimensions of an Element's content or the border-box + * + * @see https://runed.dev/docs/utilities/useResizeObserver + */ +export function useResizeObserver(target, callback, options = {}) { + const { window = defaultWindow } = options; + let observer; + const targets = $derived.by(() => { + const value = extract(target); + return new Set(value ? (Array.isArray(value) ? value : [value]) : []); + }); + const stop = $effect.root(() => { + $effect(() => { + if (!targets.size || !window) + return; + observer = new window.ResizeObserver(callback); + for (const el of targets) + observer.observe(el, options); + return () => { + observer?.disconnect(); + observer = undefined; + }; + }); + }); + $effect(() => { + return stop; + }); + return { + stop, + }; +} diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/index.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58ed11fdce466c67f4ad5d6196d54e9e4f9046b9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/index.d.ts @@ -0,0 +1 @@ +export * from "./watch.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/index.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/index.js new file mode 100644 index 0000000000000000000000000000000000000000..58ed11fdce466c67f4ad5d6196d54e9e4f9046b9 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/index.js @@ -0,0 +1 @@ +export * from "./watch.svelte.js"; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4b1e67b2afd2c3ee9c4b928af0c87194355b11e1 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/watch.svelte.d.ts @@ -0,0 +1,36 @@ +import type { Getter } from "../../internal/types.js"; +export type WatchOptions = { + /** + * If `true`, the effect doesn't run until one of the `sources` changes. + * + * @default false + */ + lazy?: boolean; +}; +export declare function watch>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: { + [K in keyof T]: T[K] | undefined; +}) => void | VoidFunction, options?: WatchOptions): void; +export declare function watch(source: Getter, effect: (value: T, previousValue: T | undefined) => void | VoidFunction, options?: WatchOptions): void; +export declare namespace watch { + var pre: typeof watchPre; +} +declare function watchPre>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: { + [K in keyof T]: T[K] | undefined; +}) => void | VoidFunction, options?: WatchOptions): void; +declare function watchPre(source: Getter, effect: (value: T, previousValue: T | undefined) => void | VoidFunction, options?: WatchOptions): void; +export declare function watchOnce>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: T) => void | VoidFunction): void; +export declare function watchOnce(source: Getter, effect: (value: T, previousValue: T) => void | VoidFunction): void; +export declare namespace watchOnce { + var pre: typeof watchOncePre; +} +declare function watchOncePre>(sources: { + [K in keyof T]: Getter; +}, effect: (values: T, previousValues: T) => void | VoidFunction): void; +declare function watchOncePre(source: Getter, effect: (value: T, previousValue: T) => void | VoidFunction): void; +export {}; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/watch.svelte.js b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/watch.svelte.js new file mode 100644 index 0000000000000000000000000000000000000000..5c01891565e1ed7f238e23e5240e3edcaa283d6c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/dist/utilities/watch/watch.svelte.js @@ -0,0 +1,69 @@ +import { untrack } from "svelte"; +function runEffect(flush, effect) { + switch (flush) { + case "post": + $effect(effect); + break; + case "pre": + $effect.pre(effect); + break; + } +} +function runWatcher(sources, flush, effect, options = {}) { + const { lazy = false } = options; + // Run the effect immediately if `lazy` is `false`. + let active = !lazy; + // On the first run, if the dependencies are an array, pass an empty array + // to the previous value instead of `undefined` to allow destructuring. + // + // watch(() => [a, b], ([a, b], [prevA, prevB]) => { ... }); + let previousValues = Array.isArray(sources) + ? [] + : undefined; + runEffect(flush, () => { + const values = Array.isArray(sources) ? sources.map((source) => source()) : sources(); + if (!active) { + active = true; + previousValues = values; + return; + } + const cleanup = untrack(() => effect(values, previousValues)); + previousValues = values; + return cleanup; + }); +} +function runWatcherOnce(sources, flush, effect) { + const cleanupRoot = $effect.root(() => { + let stop = false; + runWatcher(sources, flush, (values, previousValues) => { + if (stop) { + cleanupRoot(); + return; + } + // Since `lazy` is `true`, `previousValues` is always defined. + const cleanup = effect(values, previousValues); + stop = true; + return cleanup; + }, + // Running the effect immediately just once makes no sense at all. + // That's just `onMount` with extra steps. + { lazy: true }); + }); + $effect(() => { + return cleanupRoot; + }); +} +export function watch(sources, effect, options) { + runWatcher(sources, "post", effect, options); +} +function watchPre(sources, effect, options) { + runWatcher(sources, "pre", effect, options); +} +watch.pre = watchPre; +export function watchOnce(source, effect) { + runWatcherOnce(source, "post", effect); +} +function watchOncePre(source, effect) { + runWatcherOnce(source, "pre", effect); +} +watchOnce.pre = watchOncePre; diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/package.json b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f5ddbb79ccd37df3b36310be5ed342fb0c9c112c --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/node_modules/runed/package.json @@ -0,0 +1,74 @@ +{ + "name": "runed", + "version": "0.23.4", + "type": "module", + "svelte": "./dist/index.js", + "types": "./dist/index.d.ts", + "contributors": [ + { + "name": "Thomas G. Lopes", + "url": "https://thomasglopes.com" + }, + { + "name": "Hunter Johnston", + "url": "https://x.com/huntabyte" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/svecosystem/runed", + "directory": "packages/runed" + }, + "funding": [ + "https://github.com/sponsors/huntabyte", + "https://github.com/sponsors/tglide" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "svelte": "./dist/index.js" + } + }, + "files": [ + "dist", + "!dist/**/*.test.*", + "!dist/**/*.spec.*" + ], + "peerDependencies": { + "svelte": "^5.7.0" + }, + "devDependencies": { + "@sveltejs/kit": "^2.5.3", + "@sveltejs/package": "^2.3.0", + "@sveltejs/vite-plugin-svelte": "4.0.0-next.7", + "@testing-library/dom": "^10.2.0", + "@testing-library/jest-dom": "^6.4.6", + "@testing-library/svelte": "^5.2.0", + "@testing-library/user-event": "^14.5.2", + "@types/node": "^20.10.6", + "@vitest/coverage-v8": "^1.5.1", + "@vitest/ui": "^1.6.0", + "jsdom": "^24.0.0", + "publint": "^0.1.9", + "resize-observer-polyfill": "^1.5.1", + "svelte": "^5.11.0", + "svelte-check": "^4.1.1", + "tslib": "^2.4.1", + "typescript": "^5.0.0", + "vite": "^5.0.3", + "vitest": "^1.5.1" + }, + "dependencies": { + "esm-env": "^1.0.0" + }, + "scripts": { + "dev": "pnpm sync && pnpm watch", + "build": "pnpm package", + "package": "svelte-kit sync && svelte-package && publint", + "test": "vitest --run", + "test:watch": "vitest --watch", + "test:ui": "vitest --watch --ui", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "watch": "svelte-kit sync && svelte-package --watch" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/package.json b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d08d9b137760f73521dfa5a6026e694b1483bbe4 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/node_modules/svelte-toolbelt/package.json @@ -0,0 +1,76 @@ +{ + "name": "svelte-toolbelt", + "version": "0.7.1", + "funding": [ + "https://github.com/sponsors/huntabyte" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "svelte": "./dist/index.js" + } + }, + "files": [ + "dist", + "!dist/**/*.test.*", + "!dist/**/*.spec.*" + ], + "peerDependencies": { + "svelte": "^5.0.0" + }, + "devDependencies": { + "@changesets/cli": "^2.27.1", + "@eslint/js": "^9.12.0", + "@sveltejs/adapter-auto": "^3.0.0", + "@sveltejs/kit": "^2.16.1", + "@sveltejs/package": "^2.3.9", + "@sveltejs/vite-plugin-svelte": "4.0.1", + "@svitejs/changesets-changelog-github-compact": "^1.1.0", + "@types/node": "^20.12.12", + "@typescript-eslint/eslint-plugin": "^8.10.0", + "@typescript-eslint/scope-manager": "^8.10.0", + "@typescript-eslint/utils": "^8.10.0", + "csstype": "^3.1.3", + "eslint": "^9.0.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-svelte": "^2.46.1", + "globals": "^15.11.0", + "jsdom": "^24.0.0", + "prettier": "^3.3.3", + "prettier-plugin-svelte": "^3.3.3", + "publint": "^0.1.9", + "svelte": "^5.19.6", + "svelte-check": "^4.1.4", + "svelte-eslint-parser": "^0.43.0", + "tslib": "^2.4.1", + "typescript": "^5.6.2", + "typescript-eslint": "^8.10.0", + "vite": "^5.4.8", + "vitest": "^2.1.2" + }, + "dependencies": { + "clsx": "^2.1.1", + "runed": "^0.23.2", + "style-to-object": "^1.0.8" + }, + "svelte": "./dist/index.js", + "types": "./dist/index.d.ts", + "type": "module", + "engines": { + "pnpm": ">=8.7.0", + "node": ">=18" + }, + "packageManager": "pnpm@8.15.8", + "scripts": { + "dev": "vite dev", + "build": "vite build && npm run package", + "preview": "vite preview", + "package": "svelte-kit sync && svelte-package && publint", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", + "test": "vitest", + "lint": "prettier --check . && eslint .", + "format": "prettier --write .", + "ci:publish": "pnpm package && changeset publish" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/mode-watcher/package.json b/tools/ui/node_modules/mode-watcher/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8a68f634bf7815a9f47ab39cb2f3db58d8a8ac56 --- /dev/null +++ b/tools/ui/node_modules/mode-watcher/package.json @@ -0,0 +1,68 @@ +{ + "name": "mode-watcher", + "version": "1.1.0", + "description": "SSR-friendly light and dark mode for SvelteKit", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/svecosystem/mode-watcher.git", + "directory": "packages/mode-watcher" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "svelte": "./dist/index.js" + } + }, + "files": [ + "dist", + "!dist/**/*.test.*", + "!dist/**/*.spec.*" + ], + "peerDependencies": { + "svelte": "^5.27.0" + }, + "devDependencies": { + "@playwright/test": "^1.28.1", + "@sveltejs/kit": "^2.20.7", + "@sveltejs/package": "^2.3.11", + "@sveltejs/vite-plugin-svelte": "^5.0.3", + "@svitejs/changesets-changelog-github-compact": "^1.1.0", + "@testing-library/dom": "^10.3.1", + "@testing-library/jest-dom": "^6.4.6", + "@testing-library/svelte": "^5.2.0", + "@testing-library/user-event": "^14.5.1", + "@types/node": "^20.14.10", + "autoprefixer": "^10.4.14", + "jsdom": "^24.1.0", + "postcss": "^8.4.24", + "postcss-load-config": "^4.0.1", + "publint": "^0.1.9", + "svelte": "^5.27.0", + "svelte-check": "^4.1.6", + "tailwindcss": "^3.3.2", + "tslib": "^2.8.1", + "typescript": "^5.8.3", + "vite": "^6.3.0", + "vitest": "^3.1.1", + "vitest-localstorage-mock": "^0.1.2" + }, + "svelte": "./dist/index.js", + "types": "./dist/index.d.ts", + "type": "module", + "dependencies": { + "runed": "^0.25.0", + "svelte-toolbelt": "^0.7.1" + }, + "scripts": { + "dev": "pnpm watch", + "dev:sandbox": "vite", + "build": "pnpm package", + "preview": "vite preview", + "package": "svelte-kit sync && svelte-package && publint", + "test": "vitest", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", + "watch": "svelte-kit sync && svelte-package --watch" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/mri/index.d.ts b/tools/ui/node_modules/mri/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a46e43dfec94a30d626037b873fe6e416b70fc64 --- /dev/null +++ b/tools/ui/node_modules/mri/index.d.ts @@ -0,0 +1,21 @@ +type Dict = Record; +type Arrayable = T | T[]; +type Default = Dict; + +declare function mri(args?: string[], options?: mri.Options): mri.Argv; + +declare namespace mri { + export interface Options { + boolean?: Arrayable; + string?: Arrayable; + alias?: Dict>; + default?: Dict; + unknown?(flag: string): void; + } + + export type Argv = T & { + _: string[]; + } +} + +export = mri; diff --git a/tools/ui/node_modules/mri/lib/index.js b/tools/ui/node_modules/mri/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f17f13a8c3f8d2691cec3c424050c32da5bc8815 --- /dev/null +++ b/tools/ui/node_modules/mri/lib/index.js @@ -0,0 +1,119 @@ +function toArr(any) { + return any == null ? [] : Array.isArray(any) ? any : [any]; +} + +function toVal(out, key, val, opts) { + var x, old=out[key], nxt=( + !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val)) + : typeof val === 'boolean' ? val + : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val)) + : (x = +val,x * 0 === 0) ? x : val + ); + out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]); +} + +module.exports = function (args, opts) { + args = args || []; + opts = opts || {}; + + var k, arr, arg, name, val, out={ _:[] }; + var i=0, j=0, idx=0, len=args.length; + + const alibi = opts.alias !== void 0; + const strict = opts.unknown !== void 0; + const defaults = opts.default !== void 0; + + opts.alias = opts.alias || {}; + opts.string = toArr(opts.string); + opts.boolean = toArr(opts.boolean); + + if (alibi) { + for (k in opts.alias) { + arr = opts.alias[k] = toArr(opts.alias[k]); + for (i=0; i < arr.length; i++) { + (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); + } + } + } + + for (i=opts.boolean.length; i-- > 0;) { + arr = opts.alias[opts.boolean[i]] || []; + for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]); + } + + for (i=opts.string.length; i-- > 0;) { + arr = opts.alias[opts.string[i]] || []; + for (j=arr.length; j-- > 0;) opts.string.push(arr[j]); + } + + if (defaults) { + for (k in opts.default) { + name = typeof opts.default[k]; + arr = opts.alias[k] = opts.alias[k] || []; + if (opts[name] !== void 0) { + opts[name].push(k); + for (i=0; i < arr.length; i++) { + opts[name].push(arr[i]); + } + } + } + } + + const keys = strict ? Object.keys(opts.alias) : []; + + for (i=0; i < len; i++) { + arg = args[i]; + + if (arg === '--') { + out._ = out._.concat(args.slice(++i)); + break; + } + + for (j=0; j < arg.length; j++) { + if (arg.charCodeAt(j) !== 45) break; // "-" + } + + if (j === 0) { + out._.push(arg); + } else if (arg.substring(j, j + 3) === 'no-') { + name = arg.substring(j + 3); + if (strict && !~keys.indexOf(name)) { + return opts.unknown(arg); + } + out[name] = false; + } else { + for (idx=j+1; idx < arg.length; idx++) { + if (arg.charCodeAt(idx) === 61) break; // "=" + } + + name = arg.substring(j, idx); + val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]); + arr = (j === 2 ? [name] : name); + + for (idx=0; idx < arr.length; idx++) { + name = arr[idx]; + if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); + toVal(out, name, (idx + 1 < arr.length) || val, opts); + } + } + } + + if (defaults) { + for (k in opts.default) { + if (out[k] === void 0) { + out[k] = opts.default[k]; + } + } + } + + if (alibi) { + for (k in out) { + arr = opts.alias[k] || []; + while (arr.length > 0) { + out[arr.shift()] = out[k]; + } + } + } + + return out; +} diff --git a/tools/ui/node_modules/mri/lib/index.mjs b/tools/ui/node_modules/mri/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1a233e5b1d1013e3a3369ad407818c860877c92c --- /dev/null +++ b/tools/ui/node_modules/mri/lib/index.mjs @@ -0,0 +1,119 @@ +function toArr(any) { + return any == null ? [] : Array.isArray(any) ? any : [any]; +} + +function toVal(out, key, val, opts) { + var x, old=out[key], nxt=( + !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val)) + : typeof val === 'boolean' ? val + : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val)) + : (x = +val,x * 0 === 0) ? x : val + ); + out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]); +} + +export default function (args, opts) { + args = args || []; + opts = opts || {}; + + var k, arr, arg, name, val, out={ _:[] }; + var i=0, j=0, idx=0, len=args.length; + + const alibi = opts.alias !== void 0; + const strict = opts.unknown !== void 0; + const defaults = opts.default !== void 0; + + opts.alias = opts.alias || {}; + opts.string = toArr(opts.string); + opts.boolean = toArr(opts.boolean); + + if (alibi) { + for (k in opts.alias) { + arr = opts.alias[k] = toArr(opts.alias[k]); + for (i=0; i < arr.length; i++) { + (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); + } + } + } + + for (i=opts.boolean.length; i-- > 0;) { + arr = opts.alias[opts.boolean[i]] || []; + for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]); + } + + for (i=opts.string.length; i-- > 0;) { + arr = opts.alias[opts.string[i]] || []; + for (j=arr.length; j-- > 0;) opts.string.push(arr[j]); + } + + if (defaults) { + for (k in opts.default) { + name = typeof opts.default[k]; + arr = opts.alias[k] = opts.alias[k] || []; + if (opts[name] !== void 0) { + opts[name].push(k); + for (i=0; i < arr.length; i++) { + opts[name].push(arr[i]); + } + } + } + } + + const keys = strict ? Object.keys(opts.alias) : []; + + for (i=0; i < len; i++) { + arg = args[i]; + + if (arg === '--') { + out._ = out._.concat(args.slice(++i)); + break; + } + + for (j=0; j < arg.length; j++) { + if (arg.charCodeAt(j) !== 45) break; // "-" + } + + if (j === 0) { + out._.push(arg); + } else if (arg.substring(j, j + 3) === 'no-') { + name = arg.substring(j + 3); + if (strict && !~keys.indexOf(name)) { + return opts.unknown(arg); + } + out[name] = false; + } else { + for (idx=j+1; idx < arg.length; idx++) { + if (arg.charCodeAt(idx) === 61) break; // "=" + } + + name = arg.substring(j, idx); + val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]); + arr = (j === 2 ? [name] : name); + + for (idx=0; idx < arr.length; idx++) { + name = arr[idx]; + if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); + toVal(out, name, (idx + 1 < arr.length) || val, opts); + } + } + } + + if (defaults) { + for (k in opts.default) { + if (out[k] === void 0) { + out[k] = opts.default[k]; + } + } + } + + if (alibi) { + for (k in out) { + arr = opts.alias[k] || []; + while (arr.length > 0) { + out[arr.shift()] = out[k]; + } + } + } + + return out; +} diff --git a/tools/ui/node_modules/mri/license.md b/tools/ui/node_modules/mri/license.md new file mode 100644 index 0000000000000000000000000000000000000000..a3f96f828458d4ccf4ca8e9b0949300f1916e114 --- /dev/null +++ b/tools/ui/node_modules/mri/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Luke Edwards (lukeed.com) + +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. diff --git a/tools/ui/node_modules/mri/package.json b/tools/ui/node_modules/mri/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5a224b264d3af10e6cbb7bb8bff1bb9486d515b6 --- /dev/null +++ b/tools/ui/node_modules/mri/package.json @@ -0,0 +1,43 @@ +{ + "name": "mri", + "version": "1.2.0", + "description": "Quickly scan for CLI flags and arguments", + "repository": "lukeed/mri", + "module": "lib/index.mjs", + "main": "lib/index.js", + "types": "index.d.ts", + "license": "MIT", + "files": [ + "*.d.ts", + "lib" + ], + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "build": "bundt", + "bench": "node bench", + "pretest": "npm run build", + "test": "tape test/*.js | tap-spec" + }, + "keywords": [ + "argv", + "arguments", + "cli", + "minimist", + "options", + "optimist", + "parser", + "args" + ], + "devDependencies": { + "bundt": "1.0.2", + "tap-spec": "4.1.2", + "tape": "4.13.3" + } +} diff --git a/tools/ui/node_modules/mri/readme.md b/tools/ui/node_modules/mri/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9067e80ee375c931a9a7446c05f86d3414fa7360 --- /dev/null +++ b/tools/ui/node_modules/mri/readme.md @@ -0,0 +1,166 @@ +# mri [![CI](https://github.com/lukeed/mri/workflows/CI/badge.svg?branch=master&event=push)](https://github.com/lukeed/mri/actions) + +> Quickly scan for CLI flags and arguments + +This is a [fast](#benchmarks) and lightweight alternative to [`minimist`](https://github.com/substack/minimist) and [`yargs-parser`](https://github.com/yargs/yargs-parser). + +It only exists because I find that I usually don't need most of what `minimist` and `yargs-parser` have to offer. However, `mri` is similar _enough_ that it might function as a "drop-in replacement" for you, too! + +See [Comparisons](#comparisons) for more info. + +## Install + +```sh +$ npm install --save mri +``` + +## Usage + +```sh +$ demo-cli --foo --bar=baz -mtv -- hello world +``` + +```js +const mri = require('mri'); + +const argv = process.argv.slice(2); + +mri(argv); +//=> { _: ['hello', 'world'], foo:true, bar:'baz', m:true, t:true, v:true } + +mri(argv, { boolean:['bar'] }); +//=> { _: ['baz', 'hello', 'world'], foo:true, bar:true, m:true, t:true, v:true } + +mri(argv, { + alias: { + b: 'bar', + foo: ['f', 'fuz'] + } +}); +//=> { _: ['hello', 'world'], foo:true, f:true, fuz:true, b:'baz', bar:'baz', m:true, t:true, v:true } +``` + +## API + +### mri(args, options) +Return: `Object` + +#### args +Type: `Array`
+Default: `[]` + +An array of arguments to parse. For CLI usage, send `process.argv.slice(2)`. See [`process.argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) for info. + +#### options.alias +Type: `Object`
+Default: `{}` + +An object of keys whose values are `String`s or `Array` of aliases. These will be added to the parsed output with matching values. + +#### options.boolean +Type: `Array|String`
+Default: `[]` + +A single key (or array of keys) that should be parsed as `Boolean`s. + +#### options.default +Type: `Object`
+Default: `{}` + +An `key:value` object of defaults. If a default is provided for a key, its type (`typeof`) will be used to cast parsed arguments. + +```js +mri(['--foo', 'bar']); +//=> { _:[], foo:'bar' } + +mri(['--foo', 'bar'], { + default: { foo:true, baz:'hello', bat:42 } +}); +//=> { _:['bar'], foo:true, baz:'hello', bat:42 } +``` + +> **Note:** Because `--foo` has a default of `true`, its output is cast to a Boolean. This means that `foo=true`, making `'bar'` an extra argument (`_` key). + +#### options.string +Type: `Array|String`
+Default: `[]` + +A single key (or array of keys) that should be parsed as `String`s. + +#### options.unknown +Type: `Function`
+Default: `undefined` + +Callback that is run when a parsed flag has not been defined as a known key or alias. Its only parameter is the unknown flag itself; eg `--foobar` or `-f`. + +Once an unknown flag is encountered, parsing will terminate, regardless of your return value. + +> **Note:** `mri` _only_ checks for unknown flags if `options.unknown` **and** `options.alias` are populated. Otherwise, everything will be accepted. + + +## Comparisons + +#### minimist + +- `mri` is 5x faster (see [benchmarks](#benchmarks)) +- Numerical values are cast as `Number`s when possible + - A key (and its aliases) will always honor `opts.boolean` or `opts.string` +- Short flag groups are treated as `Boolean`s by default: + ```js + minimist(['-abc', 'hello']); + //=> { _:[], a:'', b:'', c:'hello' } + + mri(['-abc', 'hello']); + //=> { _:[], a:true, b:true, c:'hello' } + ``` +- The `opts.unknown` behaves differently: + - Unlike `minimist`, `mri` will not continue continue parsing after encountering an unknown flag +- Missing `options`: + - `opts.stopEarly` + - `opts['--']` +- Ignores newlines (`\n`) within args (see [test](https://github.com/substack/minimist/blob/master/test/parse.js#L69-L80)) +- Ignores slashBreaks within args (see [test](https://github.com/substack/minimist/blob/master/test/parse.js#L147-L157)) +- Ignores dot-nested flags (see [test](https://github.com/substack/minimist/blob/master/test/parse.js#L180-L197)) + +#### yargs-parser + +- `mri` is 40x faster (see [benchmarks](#benchmarks)) +- Numerical values are cast as `Number`s when possible + - A key (and its aliases) will always honor `opts.boolean` or `opts.string` +- Missing `options`: + - `opts.array` + - `opts.config` + - `opts.coerce` + - `opts.count` + - `opts.envPrefix` + - `opts.narg` + - `opts.normalize` + - `opts.configuration` + - `opts.number` + - `opts['--']` +- Missing [`parser.detailed()`](https://github.com/yargs/yargs-parser#requireyargs-parserdetailedargs-opts) method +- No [additional configuration](https://github.com/yargs/yargs-parser#configuration) object +- Added [`options.unknown`](#optionsunknown) feature + + +## Benchmarks + +> Running Node.js v10.13.0 + +``` +Load Times: + nopt 3.179ms + yargs-parser 2.137ms + minimist 0.746ms + mri 0.517ms + +Benchmark: + minimist x 328,747 ops/sec ±1.09% (89 runs sampled) + mri x 1,622,801 ops/sec ±0.94% (92 runs sampled) + nopt x 888,223 ops/sec ±0.22% (92 runs sampled) + yargs-parser x 30,538 ops/sec ±0.81% (91 runs sampled) +``` + +## License + +MIT © [Luke Edwards](https://lukeed.com) diff --git a/tools/ui/node_modules/mrmime/index.d.ts b/tools/ui/node_modules/mrmime/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d9268fe1348b3996af27b10a8737b214a19cfa0 --- /dev/null +++ b/tools/ui/node_modules/mrmime/index.d.ts @@ -0,0 +1,2 @@ +export const mimes: Record; +export function lookup(extension: string): string | undefined; diff --git a/tools/ui/node_modules/mrmime/index.js b/tools/ui/node_modules/mrmime/index.js new file mode 100644 index 0000000000000000000000000000000000000000..069a8dc390584f9247b31ee7a0310a4227e03d31 --- /dev/null +++ b/tools/ui/node_modules/mrmime/index.js @@ -0,0 +1,449 @@ +const mimes = { + "3g2": "video/3gpp2", + "3gp": "video/3gpp", + "3gpp": "video/3gpp", + "3mf": "model/3mf", + "aac": "audio/aac", + "ac": "application/pkix-attr-cert", + "adp": "audio/adpcm", + "adts": "audio/aac", + "ai": "application/postscript", + "aml": "application/automationml-aml+xml", + "amlx": "application/automationml-amlx+zip", + "amr": "audio/amr", + "apng": "image/apng", + "appcache": "text/cache-manifest", + "appinstaller": "application/appinstaller", + "appx": "application/appx", + "appxbundle": "application/appxbundle", + "asc": "application/pgp-keys", + "atom": "application/atom+xml", + "atomcat": "application/atomcat+xml", + "atomdeleted": "application/atomdeleted+xml", + "atomsvc": "application/atomsvc+xml", + "au": "audio/basic", + "avci": "image/avci", + "avcs": "image/avcs", + "avif": "image/avif", + "aw": "application/applixware", + "bdoc": "application/bdoc", + "bin": "application/octet-stream", + "bmp": "image/bmp", + "bpk": "application/octet-stream", + "btf": "image/prs.btif", + "btif": "image/prs.btif", + "buffer": "application/octet-stream", + "ccxml": "application/ccxml+xml", + "cdfx": "application/cdfx+xml", + "cdmia": "application/cdmi-capability", + "cdmic": "application/cdmi-container", + "cdmid": "application/cdmi-domain", + "cdmio": "application/cdmi-object", + "cdmiq": "application/cdmi-queue", + "cer": "application/pkix-cert", + "cgm": "image/cgm", + "cjs": "application/node", + "class": "application/java-vm", + "coffee": "text/coffeescript", + "conf": "text/plain", + "cpl": "application/cpl+xml", + "cpt": "application/mac-compactpro", + "crl": "application/pkix-crl", + "css": "text/css", + "csv": "text/csv", + "cu": "application/cu-seeme", + "cwl": "application/cwl", + "cww": "application/prs.cww", + "davmount": "application/davmount+xml", + "dbk": "application/docbook+xml", + "deb": "application/octet-stream", + "def": "text/plain", + "deploy": "application/octet-stream", + "dib": "image/bmp", + "disposition-notification": "message/disposition-notification", + "dist": "application/octet-stream", + "distz": "application/octet-stream", + "dll": "application/octet-stream", + "dmg": "application/octet-stream", + "dms": "application/octet-stream", + "doc": "application/msword", + "dot": "application/msword", + "dpx": "image/dpx", + "drle": "image/dicom-rle", + "dsc": "text/prs.lines.tag", + "dssc": "application/dssc+der", + "dtd": "application/xml-dtd", + "dump": "application/octet-stream", + "dwd": "application/atsc-dwd+xml", + "ear": "application/java-archive", + "ecma": "application/ecmascript", + "elc": "application/octet-stream", + "emf": "image/emf", + "eml": "message/rfc822", + "emma": "application/emma+xml", + "emotionml": "application/emotionml+xml", + "eps": "application/postscript", + "epub": "application/epub+zip", + "exe": "application/octet-stream", + "exi": "application/exi", + "exp": "application/express", + "exr": "image/aces", + "ez": "application/andrew-inset", + "fdf": "application/fdf", + "fdt": "application/fdt+xml", + "fits": "image/fits", + "g3": "image/g3fax", + "gbr": "application/rpki-ghostbusters", + "geojson": "application/geo+json", + "gif": "image/gif", + "glb": "model/gltf-binary", + "gltf": "model/gltf+json", + "gml": "application/gml+xml", + "gpx": "application/gpx+xml", + "gram": "application/srgs", + "grxml": "application/srgs+xml", + "gxf": "application/gxf", + "gz": "application/gzip", + "h261": "video/h261", + "h263": "video/h263", + "h264": "video/h264", + "heic": "image/heic", + "heics": "image/heic-sequence", + "heif": "image/heif", + "heifs": "image/heif-sequence", + "hej2": "image/hej2k", + "held": "application/atsc-held+xml", + "hjson": "application/hjson", + "hlp": "application/winhlp", + "hqx": "application/mac-binhex40", + "hsj2": "image/hsj2", + "htm": "text/html", + "html": "text/html", + "ics": "text/calendar", + "ief": "image/ief", + "ifb": "text/calendar", + "iges": "model/iges", + "igs": "model/iges", + "img": "application/octet-stream", + "in": "text/plain", + "ini": "text/plain", + "ink": "application/inkml+xml", + "inkml": "application/inkml+xml", + "ipfix": "application/ipfix", + "iso": "application/octet-stream", + "its": "application/its+xml", + "jade": "text/jade", + "jar": "application/java-archive", + "jhc": "image/jphc", + "jls": "image/jls", + "jp2": "image/jp2", + "jpe": "image/jpeg", + "jpeg": "image/jpeg", + "jpf": "image/jpx", + "jpg": "image/jpeg", + "jpg2": "image/jp2", + "jpgm": "image/jpm", + "jpgv": "video/jpeg", + "jph": "image/jph", + "jpm": "image/jpm", + "jpx": "image/jpx", + "js": "text/javascript", + "json": "application/json", + "json5": "application/json5", + "jsonld": "application/ld+json", + "jsonml": "application/jsonml+json", + "jsx": "text/jsx", + "jt": "model/jt", + "jxl": "image/jxl", + "jxr": "image/jxr", + "jxra": "image/jxra", + "jxrs": "image/jxrs", + "jxs": "image/jxs", + "jxsc": "image/jxsc", + "jxsi": "image/jxsi", + "jxss": "image/jxss", + "kar": "audio/midi", + "ktx": "image/ktx", + "ktx2": "image/ktx2", + "less": "text/less", + "lgr": "application/lgr+xml", + "list": "text/plain", + "litcoffee": "text/coffeescript", + "log": "text/plain", + "lostxml": "application/lost+xml", + "lrf": "application/octet-stream", + "m1v": "video/mpeg", + "m21": "application/mp21", + "m2a": "audio/mpeg", + "m2t": "video/mp2t", + "m2ts": "video/mp2t", + "m2v": "video/mpeg", + "m3a": "audio/mpeg", + "m4a": "audio/mp4", + "m4p": "application/mp4", + "m4s": "video/iso.segment", + "ma": "application/mathematica", + "mads": "application/mads+xml", + "maei": "application/mmt-aei+xml", + "man": "text/troff", + "manifest": "text/cache-manifest", + "map": "application/json", + "mar": "application/octet-stream", + "markdown": "text/markdown", + "mathml": "application/mathml+xml", + "mb": "application/mathematica", + "mbox": "application/mbox", + "md": "text/markdown", + "mdx": "text/mdx", + "me": "text/troff", + "mesh": "model/mesh", + "meta4": "application/metalink4+xml", + "metalink": "application/metalink+xml", + "mets": "application/mets+xml", + "mft": "application/rpki-manifest", + "mid": "audio/midi", + "midi": "audio/midi", + "mime": "message/rfc822", + "mj2": "video/mj2", + "mjp2": "video/mj2", + "mjs": "text/javascript", + "mml": "text/mathml", + "mods": "application/mods+xml", + "mov": "video/quicktime", + "mp2": "audio/mpeg", + "mp21": "application/mp21", + "mp2a": "audio/mpeg", + "mp3": "audio/mpeg", + "mp4": "video/mp4", + "mp4a": "audio/mp4", + "mp4s": "application/mp4", + "mp4v": "video/mp4", + "mpd": "application/dash+xml", + "mpe": "video/mpeg", + "mpeg": "video/mpeg", + "mpf": "application/media-policy-dataset+xml", + "mpg": "video/mpeg", + "mpg4": "video/mp4", + "mpga": "audio/mpeg", + "mpp": "application/dash-patch+xml", + "mrc": "application/marc", + "mrcx": "application/marcxml+xml", + "ms": "text/troff", + "mscml": "application/mediaservercontrol+xml", + "msh": "model/mesh", + "msi": "application/octet-stream", + "msix": "application/msix", + "msixbundle": "application/msixbundle", + "msm": "application/octet-stream", + "msp": "application/octet-stream", + "mtl": "model/mtl", + "mts": "video/mp2t", + "musd": "application/mmt-usd+xml", + "mxf": "application/mxf", + "mxmf": "audio/mobile-xmf", + "mxml": "application/xv+xml", + "n3": "text/n3", + "nb": "application/mathematica", + "nq": "application/n-quads", + "nt": "application/n-triples", + "obj": "model/obj", + "oda": "application/oda", + "oga": "audio/ogg", + "ogg": "audio/ogg", + "ogv": "video/ogg", + "ogx": "application/ogg", + "omdoc": "application/omdoc+xml", + "onepkg": "application/onenote", + "onetmp": "application/onenote", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "opf": "application/oebps-package+xml", + "opus": "audio/ogg", + "otf": "font/otf", + "owl": "application/rdf+xml", + "oxps": "application/oxps", + "p10": "application/pkcs10", + "p7c": "application/pkcs7-mime", + "p7m": "application/pkcs7-mime", + "p7s": "application/pkcs7-signature", + "p8": "application/pkcs8", + "pdf": "application/pdf", + "pfr": "application/font-tdpfr", + "pgp": "application/pgp-encrypted", + "pkg": "application/octet-stream", + "pki": "application/pkixcmp", + "pkipath": "application/pkix-pkipath", + "pls": "application/pls+xml", + "png": "image/png", + "prc": "model/prc", + "prf": "application/pics-rules", + "provx": "application/provenance+xml", + "ps": "application/postscript", + "pskcxml": "application/pskc+xml", + "pti": "image/prs.pti", + "qt": "video/quicktime", + "raml": "application/raml+yaml", + "rapd": "application/route-apd+xml", + "rdf": "application/rdf+xml", + "relo": "application/p2p-overlay+xml", + "rif": "application/reginfo+xml", + "rl": "application/resource-lists+xml", + "rld": "application/resource-lists-diff+xml", + "rmi": "audio/midi", + "rnc": "application/relax-ng-compact-syntax", + "rng": "application/xml", + "roa": "application/rpki-roa", + "roff": "text/troff", + "rq": "application/sparql-query", + "rs": "application/rls-services+xml", + "rsat": "application/atsc-rsat+xml", + "rsd": "application/rsd+xml", + "rsheet": "application/urc-ressheet+xml", + "rss": "application/rss+xml", + "rtf": "text/rtf", + "rtx": "text/richtext", + "rusd": "application/route-usd+xml", + "s3m": "audio/s3m", + "sbml": "application/sbml+xml", + "scq": "application/scvp-cv-request", + "scs": "application/scvp-cv-response", + "sdp": "application/sdp", + "senmlx": "application/senml+xml", + "sensmlx": "application/sensml+xml", + "ser": "application/java-serialized-object", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "sgi": "image/sgi", + "sgm": "text/sgml", + "sgml": "text/sgml", + "shex": "text/shex", + "shf": "application/shf+xml", + "shtml": "text/html", + "sieve": "application/sieve", + "sig": "application/pgp-signature", + "sil": "audio/silk", + "silo": "model/mesh", + "siv": "application/sieve", + "slim": "text/slim", + "slm": "text/slim", + "sls": "application/route-s-tsid+xml", + "smi": "application/smil+xml", + "smil": "application/smil+xml", + "snd": "audio/basic", + "so": "application/octet-stream", + "spdx": "text/spdx", + "spp": "application/scvp-vp-response", + "spq": "application/scvp-vp-request", + "spx": "audio/ogg", + "sql": "application/sql", + "sru": "application/sru+xml", + "srx": "application/sparql-results+xml", + "ssdl": "application/ssdl+xml", + "ssml": "application/ssml+xml", + "stk": "application/hyperstudio", + "stl": "model/stl", + "stpx": "model/step+xml", + "stpxz": "model/step-xml+zip", + "stpz": "model/step+zip", + "styl": "text/stylus", + "stylus": "text/stylus", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "swidtag": "application/swid+xml", + "t": "text/troff", + "t38": "image/t38", + "td": "application/urc-targetdesc+xml", + "tei": "application/tei+xml", + "teicorpus": "application/tei+xml", + "text": "text/plain", + "tfi": "application/thraud+xml", + "tfx": "image/tiff-fx", + "tif": "image/tiff", + "tiff": "image/tiff", + "toml": "application/toml", + "tr": "text/troff", + "trig": "application/trig", + "ts": "video/mp2t", + "tsd": "application/timestamped-data", + "tsv": "text/tab-separated-values", + "ttc": "font/collection", + "ttf": "font/ttf", + "ttl": "text/turtle", + "ttml": "application/ttml+xml", + "txt": "text/plain", + "u3d": "model/u3d", + "u8dsn": "message/global-delivery-status", + "u8hdr": "message/global-headers", + "u8mdn": "message/global-disposition-notification", + "u8msg": "message/global", + "ubj": "application/ubjson", + "uri": "text/uri-list", + "uris": "text/uri-list", + "urls": "text/uri-list", + "vcard": "text/vcard", + "vrml": "model/vrml", + "vtt": "text/vtt", + "vxml": "application/voicexml+xml", + "war": "application/java-archive", + "wasm": "application/wasm", + "wav": "audio/wav", + "weba": "audio/webm", + "webm": "video/webm", + "webmanifest": "application/manifest+json", + "webp": "image/webp", + "wgsl": "text/wgsl", + "wgt": "application/widget", + "wif": "application/watcherinfo+xml", + "wmf": "image/wmf", + "woff": "font/woff", + "woff2": "font/woff2", + "wrl": "model/vrml", + "wsdl": "application/wsdl+xml", + "wspolicy": "application/wspolicy+xml", + "x3d": "model/x3d+xml", + "x3db": "model/x3d+fastinfoset", + "x3dbz": "model/x3d+binary", + "x3dv": "model/x3d-vrml", + "x3dvz": "model/x3d+vrml", + "x3dz": "model/x3d+xml", + "xaml": "application/xaml+xml", + "xav": "application/xcap-att+xml", + "xca": "application/xcap-caps+xml", + "xcs": "application/calendar+xml", + "xdf": "application/xcap-diff+xml", + "xdssc": "application/dssc+xml", + "xel": "application/xcap-el+xml", + "xenc": "application/xenc+xml", + "xer": "application/patch-ops-error+xml", + "xfdf": "application/xfdf", + "xht": "application/xhtml+xml", + "xhtml": "application/xhtml+xml", + "xhvml": "application/xv+xml", + "xlf": "application/xliff+xml", + "xm": "audio/xm", + "xml": "text/xml", + "xns": "application/xcap-ns+xml", + "xop": "application/xop+xml", + "xpl": "application/xproc+xml", + "xsd": "application/xml", + "xsf": "application/prs.xsf+xml", + "xsl": "application/xml", + "xslt": "application/xml", + "xspf": "application/xspf+xml", + "xvm": "application/xv+xml", + "xvml": "application/xv+xml", + "yaml": "text/yaml", + "yang": "application/yang", + "yin": "application/yin+xml", + "yml": "text/yaml", + "zip": "application/zip" +}; + +function lookup(extn) { + let tmp = ('' + extn).trim().toLowerCase(); + let idx = tmp.lastIndexOf('.'); + return mimes[!~idx ? tmp : tmp.substring(++idx)]; +} + +exports.mimes = mimes; +exports.lookup = lookup; diff --git a/tools/ui/node_modules/mrmime/index.mjs b/tools/ui/node_modules/mrmime/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..76b6205f5c34048859fc1aa8be57b632de00a675 --- /dev/null +++ b/tools/ui/node_modules/mrmime/index.mjs @@ -0,0 +1,448 @@ +const mimes = { + "3g2": "video/3gpp2", + "3gp": "video/3gpp", + "3gpp": "video/3gpp", + "3mf": "model/3mf", + "aac": "audio/aac", + "ac": "application/pkix-attr-cert", + "adp": "audio/adpcm", + "adts": "audio/aac", + "ai": "application/postscript", + "aml": "application/automationml-aml+xml", + "amlx": "application/automationml-amlx+zip", + "amr": "audio/amr", + "apng": "image/apng", + "appcache": "text/cache-manifest", + "appinstaller": "application/appinstaller", + "appx": "application/appx", + "appxbundle": "application/appxbundle", + "asc": "application/pgp-keys", + "atom": "application/atom+xml", + "atomcat": "application/atomcat+xml", + "atomdeleted": "application/atomdeleted+xml", + "atomsvc": "application/atomsvc+xml", + "au": "audio/basic", + "avci": "image/avci", + "avcs": "image/avcs", + "avif": "image/avif", + "aw": "application/applixware", + "bdoc": "application/bdoc", + "bin": "application/octet-stream", + "bmp": "image/bmp", + "bpk": "application/octet-stream", + "btf": "image/prs.btif", + "btif": "image/prs.btif", + "buffer": "application/octet-stream", + "ccxml": "application/ccxml+xml", + "cdfx": "application/cdfx+xml", + "cdmia": "application/cdmi-capability", + "cdmic": "application/cdmi-container", + "cdmid": "application/cdmi-domain", + "cdmio": "application/cdmi-object", + "cdmiq": "application/cdmi-queue", + "cer": "application/pkix-cert", + "cgm": "image/cgm", + "cjs": "application/node", + "class": "application/java-vm", + "coffee": "text/coffeescript", + "conf": "text/plain", + "cpl": "application/cpl+xml", + "cpt": "application/mac-compactpro", + "crl": "application/pkix-crl", + "css": "text/css", + "csv": "text/csv", + "cu": "application/cu-seeme", + "cwl": "application/cwl", + "cww": "application/prs.cww", + "davmount": "application/davmount+xml", + "dbk": "application/docbook+xml", + "deb": "application/octet-stream", + "def": "text/plain", + "deploy": "application/octet-stream", + "dib": "image/bmp", + "disposition-notification": "message/disposition-notification", + "dist": "application/octet-stream", + "distz": "application/octet-stream", + "dll": "application/octet-stream", + "dmg": "application/octet-stream", + "dms": "application/octet-stream", + "doc": "application/msword", + "dot": "application/msword", + "dpx": "image/dpx", + "drle": "image/dicom-rle", + "dsc": "text/prs.lines.tag", + "dssc": "application/dssc+der", + "dtd": "application/xml-dtd", + "dump": "application/octet-stream", + "dwd": "application/atsc-dwd+xml", + "ear": "application/java-archive", + "ecma": "application/ecmascript", + "elc": "application/octet-stream", + "emf": "image/emf", + "eml": "message/rfc822", + "emma": "application/emma+xml", + "emotionml": "application/emotionml+xml", + "eps": "application/postscript", + "epub": "application/epub+zip", + "exe": "application/octet-stream", + "exi": "application/exi", + "exp": "application/express", + "exr": "image/aces", + "ez": "application/andrew-inset", + "fdf": "application/fdf", + "fdt": "application/fdt+xml", + "fits": "image/fits", + "g3": "image/g3fax", + "gbr": "application/rpki-ghostbusters", + "geojson": "application/geo+json", + "gif": "image/gif", + "glb": "model/gltf-binary", + "gltf": "model/gltf+json", + "gml": "application/gml+xml", + "gpx": "application/gpx+xml", + "gram": "application/srgs", + "grxml": "application/srgs+xml", + "gxf": "application/gxf", + "gz": "application/gzip", + "h261": "video/h261", + "h263": "video/h263", + "h264": "video/h264", + "heic": "image/heic", + "heics": "image/heic-sequence", + "heif": "image/heif", + "heifs": "image/heif-sequence", + "hej2": "image/hej2k", + "held": "application/atsc-held+xml", + "hjson": "application/hjson", + "hlp": "application/winhlp", + "hqx": "application/mac-binhex40", + "hsj2": "image/hsj2", + "htm": "text/html", + "html": "text/html", + "ics": "text/calendar", + "ief": "image/ief", + "ifb": "text/calendar", + "iges": "model/iges", + "igs": "model/iges", + "img": "application/octet-stream", + "in": "text/plain", + "ini": "text/plain", + "ink": "application/inkml+xml", + "inkml": "application/inkml+xml", + "ipfix": "application/ipfix", + "iso": "application/octet-stream", + "its": "application/its+xml", + "jade": "text/jade", + "jar": "application/java-archive", + "jhc": "image/jphc", + "jls": "image/jls", + "jp2": "image/jp2", + "jpe": "image/jpeg", + "jpeg": "image/jpeg", + "jpf": "image/jpx", + "jpg": "image/jpeg", + "jpg2": "image/jp2", + "jpgm": "image/jpm", + "jpgv": "video/jpeg", + "jph": "image/jph", + "jpm": "image/jpm", + "jpx": "image/jpx", + "js": "text/javascript", + "json": "application/json", + "json5": "application/json5", + "jsonld": "application/ld+json", + "jsonml": "application/jsonml+json", + "jsx": "text/jsx", + "jt": "model/jt", + "jxl": "image/jxl", + "jxr": "image/jxr", + "jxra": "image/jxra", + "jxrs": "image/jxrs", + "jxs": "image/jxs", + "jxsc": "image/jxsc", + "jxsi": "image/jxsi", + "jxss": "image/jxss", + "kar": "audio/midi", + "ktx": "image/ktx", + "ktx2": "image/ktx2", + "less": "text/less", + "lgr": "application/lgr+xml", + "list": "text/plain", + "litcoffee": "text/coffeescript", + "log": "text/plain", + "lostxml": "application/lost+xml", + "lrf": "application/octet-stream", + "m1v": "video/mpeg", + "m21": "application/mp21", + "m2a": "audio/mpeg", + "m2t": "video/mp2t", + "m2ts": "video/mp2t", + "m2v": "video/mpeg", + "m3a": "audio/mpeg", + "m4a": "audio/mp4", + "m4p": "application/mp4", + "m4s": "video/iso.segment", + "ma": "application/mathematica", + "mads": "application/mads+xml", + "maei": "application/mmt-aei+xml", + "man": "text/troff", + "manifest": "text/cache-manifest", + "map": "application/json", + "mar": "application/octet-stream", + "markdown": "text/markdown", + "mathml": "application/mathml+xml", + "mb": "application/mathematica", + "mbox": "application/mbox", + "md": "text/markdown", + "mdx": "text/mdx", + "me": "text/troff", + "mesh": "model/mesh", + "meta4": "application/metalink4+xml", + "metalink": "application/metalink+xml", + "mets": "application/mets+xml", + "mft": "application/rpki-manifest", + "mid": "audio/midi", + "midi": "audio/midi", + "mime": "message/rfc822", + "mj2": "video/mj2", + "mjp2": "video/mj2", + "mjs": "text/javascript", + "mml": "text/mathml", + "mods": "application/mods+xml", + "mov": "video/quicktime", + "mp2": "audio/mpeg", + "mp21": "application/mp21", + "mp2a": "audio/mpeg", + "mp3": "audio/mpeg", + "mp4": "video/mp4", + "mp4a": "audio/mp4", + "mp4s": "application/mp4", + "mp4v": "video/mp4", + "mpd": "application/dash+xml", + "mpe": "video/mpeg", + "mpeg": "video/mpeg", + "mpf": "application/media-policy-dataset+xml", + "mpg": "video/mpeg", + "mpg4": "video/mp4", + "mpga": "audio/mpeg", + "mpp": "application/dash-patch+xml", + "mrc": "application/marc", + "mrcx": "application/marcxml+xml", + "ms": "text/troff", + "mscml": "application/mediaservercontrol+xml", + "msh": "model/mesh", + "msi": "application/octet-stream", + "msix": "application/msix", + "msixbundle": "application/msixbundle", + "msm": "application/octet-stream", + "msp": "application/octet-stream", + "mtl": "model/mtl", + "mts": "video/mp2t", + "musd": "application/mmt-usd+xml", + "mxf": "application/mxf", + "mxmf": "audio/mobile-xmf", + "mxml": "application/xv+xml", + "n3": "text/n3", + "nb": "application/mathematica", + "nq": "application/n-quads", + "nt": "application/n-triples", + "obj": "model/obj", + "oda": "application/oda", + "oga": "audio/ogg", + "ogg": "audio/ogg", + "ogv": "video/ogg", + "ogx": "application/ogg", + "omdoc": "application/omdoc+xml", + "onepkg": "application/onenote", + "onetmp": "application/onenote", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "opf": "application/oebps-package+xml", + "opus": "audio/ogg", + "otf": "font/otf", + "owl": "application/rdf+xml", + "oxps": "application/oxps", + "p10": "application/pkcs10", + "p7c": "application/pkcs7-mime", + "p7m": "application/pkcs7-mime", + "p7s": "application/pkcs7-signature", + "p8": "application/pkcs8", + "pdf": "application/pdf", + "pfr": "application/font-tdpfr", + "pgp": "application/pgp-encrypted", + "pkg": "application/octet-stream", + "pki": "application/pkixcmp", + "pkipath": "application/pkix-pkipath", + "pls": "application/pls+xml", + "png": "image/png", + "prc": "model/prc", + "prf": "application/pics-rules", + "provx": "application/provenance+xml", + "ps": "application/postscript", + "pskcxml": "application/pskc+xml", + "pti": "image/prs.pti", + "qt": "video/quicktime", + "raml": "application/raml+yaml", + "rapd": "application/route-apd+xml", + "rdf": "application/rdf+xml", + "relo": "application/p2p-overlay+xml", + "rif": "application/reginfo+xml", + "rl": "application/resource-lists+xml", + "rld": "application/resource-lists-diff+xml", + "rmi": "audio/midi", + "rnc": "application/relax-ng-compact-syntax", + "rng": "application/xml", + "roa": "application/rpki-roa", + "roff": "text/troff", + "rq": "application/sparql-query", + "rs": "application/rls-services+xml", + "rsat": "application/atsc-rsat+xml", + "rsd": "application/rsd+xml", + "rsheet": "application/urc-ressheet+xml", + "rss": "application/rss+xml", + "rtf": "text/rtf", + "rtx": "text/richtext", + "rusd": "application/route-usd+xml", + "s3m": "audio/s3m", + "sbml": "application/sbml+xml", + "scq": "application/scvp-cv-request", + "scs": "application/scvp-cv-response", + "sdp": "application/sdp", + "senmlx": "application/senml+xml", + "sensmlx": "application/sensml+xml", + "ser": "application/java-serialized-object", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "sgi": "image/sgi", + "sgm": "text/sgml", + "sgml": "text/sgml", + "shex": "text/shex", + "shf": "application/shf+xml", + "shtml": "text/html", + "sieve": "application/sieve", + "sig": "application/pgp-signature", + "sil": "audio/silk", + "silo": "model/mesh", + "siv": "application/sieve", + "slim": "text/slim", + "slm": "text/slim", + "sls": "application/route-s-tsid+xml", + "smi": "application/smil+xml", + "smil": "application/smil+xml", + "snd": "audio/basic", + "so": "application/octet-stream", + "spdx": "text/spdx", + "spp": "application/scvp-vp-response", + "spq": "application/scvp-vp-request", + "spx": "audio/ogg", + "sql": "application/sql", + "sru": "application/sru+xml", + "srx": "application/sparql-results+xml", + "ssdl": "application/ssdl+xml", + "ssml": "application/ssml+xml", + "stk": "application/hyperstudio", + "stl": "model/stl", + "stpx": "model/step+xml", + "stpxz": "model/step-xml+zip", + "stpz": "model/step+zip", + "styl": "text/stylus", + "stylus": "text/stylus", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "swidtag": "application/swid+xml", + "t": "text/troff", + "t38": "image/t38", + "td": "application/urc-targetdesc+xml", + "tei": "application/tei+xml", + "teicorpus": "application/tei+xml", + "text": "text/plain", + "tfi": "application/thraud+xml", + "tfx": "image/tiff-fx", + "tif": "image/tiff", + "tiff": "image/tiff", + "toml": "application/toml", + "tr": "text/troff", + "trig": "application/trig", + "ts": "video/mp2t", + "tsd": "application/timestamped-data", + "tsv": "text/tab-separated-values", + "ttc": "font/collection", + "ttf": "font/ttf", + "ttl": "text/turtle", + "ttml": "application/ttml+xml", + "txt": "text/plain", + "u3d": "model/u3d", + "u8dsn": "message/global-delivery-status", + "u8hdr": "message/global-headers", + "u8mdn": "message/global-disposition-notification", + "u8msg": "message/global", + "ubj": "application/ubjson", + "uri": "text/uri-list", + "uris": "text/uri-list", + "urls": "text/uri-list", + "vcard": "text/vcard", + "vrml": "model/vrml", + "vtt": "text/vtt", + "vxml": "application/voicexml+xml", + "war": "application/java-archive", + "wasm": "application/wasm", + "wav": "audio/wav", + "weba": "audio/webm", + "webm": "video/webm", + "webmanifest": "application/manifest+json", + "webp": "image/webp", + "wgsl": "text/wgsl", + "wgt": "application/widget", + "wif": "application/watcherinfo+xml", + "wmf": "image/wmf", + "woff": "font/woff", + "woff2": "font/woff2", + "wrl": "model/vrml", + "wsdl": "application/wsdl+xml", + "wspolicy": "application/wspolicy+xml", + "x3d": "model/x3d+xml", + "x3db": "model/x3d+fastinfoset", + "x3dbz": "model/x3d+binary", + "x3dv": "model/x3d-vrml", + "x3dvz": "model/x3d+vrml", + "x3dz": "model/x3d+xml", + "xaml": "application/xaml+xml", + "xav": "application/xcap-att+xml", + "xca": "application/xcap-caps+xml", + "xcs": "application/calendar+xml", + "xdf": "application/xcap-diff+xml", + "xdssc": "application/dssc+xml", + "xel": "application/xcap-el+xml", + "xenc": "application/xenc+xml", + "xer": "application/patch-ops-error+xml", + "xfdf": "application/xfdf", + "xht": "application/xhtml+xml", + "xhtml": "application/xhtml+xml", + "xhvml": "application/xv+xml", + "xlf": "application/xliff+xml", + "xm": "audio/xm", + "xml": "text/xml", + "xns": "application/xcap-ns+xml", + "xop": "application/xop+xml", + "xpl": "application/xproc+xml", + "xsd": "application/xml", + "xsf": "application/prs.xsf+xml", + "xsl": "application/xml", + "xslt": "application/xml", + "xspf": "application/xspf+xml", + "xvm": "application/xv+xml", + "xvml": "application/xv+xml", + "yaml": "text/yaml", + "yang": "application/yang", + "yin": "application/yin+xml", + "yml": "text/yaml", + "zip": "application/zip" +}; + +function lookup(extn) { + let tmp = ('' + extn).trim().toLowerCase(); + let idx = tmp.lastIndexOf('.'); + return mimes[!~idx ? tmp : tmp.substring(++idx)]; +} + +export { mimes, lookup }; diff --git a/tools/ui/node_modules/mrmime/license b/tools/ui/node_modules/mrmime/license new file mode 100644 index 0000000000000000000000000000000000000000..d46889ae35762abe2fc2f33a4b2ef0825fd1a6dc --- /dev/null +++ b/tools/ui/node_modules/mrmime/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Luke Edwards (https://lukeed.com) + +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. diff --git a/tools/ui/node_modules/mrmime/package.json b/tools/ui/node_modules/mrmime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d81b4585533d3420c53dab22d6fa15f02016ed36 --- /dev/null +++ b/tools/ui/node_modules/mrmime/package.json @@ -0,0 +1,44 @@ +{ + "name": "mrmime", + "version": "2.0.1", + "repository": "lukeed/mrmime", + "description": "A tiny (2.8kB) and fast utility for getting a MIME type from an extension or filename", + "module": "index.mjs", + "types": "index.d.ts", + "main": "index.js", + "license": "MIT", + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "index.d.ts", + "index.mjs", + "index.js" + ], + "engines": { + "node": ">=10" + }, + "scripts": { + "build": "tsm bin/index.ts", + "test": "uvu -r tsm test" + }, + "keywords": [ + "mime", + "extension", + "mimetype" + ], + "devDependencies": { + "tsm": "2.3.0", + "uvu": "0.5.2" + } +} diff --git a/tools/ui/node_modules/mrmime/readme.md b/tools/ui/node_modules/mrmime/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..75c591d2de0247738c1d9b89e4194071fac85687 --- /dev/null +++ b/tools/ui/node_modules/mrmime/readme.md @@ -0,0 +1,130 @@ +
+ mrmime +
+ + + +
+ A tiny (2.8kB) and fast utility for getting a MIME type from an extension or filename +
+ + +## Features + +* Lightweight – 2.8kB gzip
+ _Only includes standard mime types; all experimental and vendor-specific mimetypes removed._ + +* [Performant](#benchmarks)
+ _All lookups are O(1) with minimal processing._ + +* Comprehensive Dictionary
+ _Generated from [`mime-db`](https://github.com/jshttp/mime-db), which aggregates the IANA, NGINX, and Apache datasets._ + +* Customizable
+ _Exposes the `mimes` dictionary for easy additions or overrides._ + +* Supports Native ESM and [Deno](https://deno.land/x/mrmime)
+ _Ships with CommonJS and ESM support!_ + + +## Install + +``` +$ npm install --save mrmime +``` + + +## Usage + +```js +import { lookup, mimes } from 'mrmime'; + +// Get a MIME type +// --- +lookup('txt'); //=> "text/plain" +lookup('.txt'); //=> "text/plain" +lookup('a.txt'); //=> "text/plain" + +// Unknown extension +// --- +lookup('.xyz'); //=> undefined + +// Add extension to dictionary +// --- +mimes['xyz'] = 'hello/world'; +lookup('xyz'); //=> "hello/world" +``` + + +## API + +### lookup(input) +Returns: `string` or `undefined` + +#### input +Type: `string` + +The extension or filename to lookup. + +> **Important:** +> * Any `input` value is cast to string, lowercased, and trimmed. +> * If a filename or filepath is provided, only the extension will be used. + + +## Benchmarks + +> Running on Node v16.8.0 + +``` +Load times: + mrmime 0.963ms + mime/lite 3.281ms + mime 6.751ms + +Benchmark :: plain ("ext") + mime x 598,849 ops/sec ±0.28% (94 runs sampled) + mime/lite x 536,643 ops/sec ±0.11% (97 runs sampled) + mrmime x 835,885 ops/sec ±0.20% (97 runs sampled) + +Benchmark :: leading (".ext") + mime x 368,656 ops/sec ±0.19% (99 runs sampled) + mime/lite x 368,318 ops/sec ±0.13% (97 runs sampled) + mrmime x 533,643 ops/sec ±0.10% (96 runs sampled) + +Benchmark :: filename ("file.ext") + mime x 326,907 ops/sec ±0.17% (95 runs sampled) + mime/lite x 327,479 ops/sec ±0.12% (98 runs sampled) + mrmime x 512,823 ops/sec ±0.12% (99 runs sampled) +``` + + +## Credits + +Of course, a thank-you to [`mime`](https://github.com/broofa/mime) serving the community all these years & for being a all-encompassing MIME type library. I've only ever needed lookup/`getType` functionality – and now ESM support – so `mrmime` can only ever support 1/3 of what `mime` offers, at best. + +This would not be possible without the team behind [`mime-db`](https://github.com/jshttp/mime-db), who have painstakingly maintained an amazing database for 7+ years. + +Artwork created by [mintinol](https://www.deviantart.com/mintinol), which I found [here](https://www.deviantart.com/mintinol/art/Mr-Mime-373927920). + +Finally, thanks to [Tim Branyen](https://github.com/tbranyen) for donating the package name :) + + +## License + +MIT © [Luke Edwards](https://lukeed.com) diff --git a/tools/ui/node_modules/ms/index.js b/tools/ui/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea734fb73820316ed1c0f6a2f6e96dce0e3eb6f0 --- /dev/null +++ b/tools/ui/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/tools/ui/node_modules/ms/license.md b/tools/ui/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..fa5d39b6213f8a5e142b643575f99d9149cc71c6 --- /dev/null +++ b/tools/ui/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/ui/node_modules/ms/package.json b/tools/ui/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49971890df8e2b9a4a5f4909fbd6678b862d8a50 --- /dev/null +++ b/tools/ui/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/tools/ui/node_modules/ms/readme.md b/tools/ui/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0fc1abb3b8e30a3ab97023d243127c75b1b3a4d7 --- /dev/null +++ b/tools/ui/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/tools/ui/node_modules/nanoid/LICENSE b/tools/ui/node_modules/nanoid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..37f56aa49f8e009ed7e582cb3e905a1e0d1666fd --- /dev/null +++ b/tools/ui/node_modules/nanoid/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2017 Andrey Sitnik + +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. diff --git a/tools/ui/node_modules/nanoid/README.md b/tools/ui/node_modules/nanoid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5124349f6ae31861f457fdca881b7bb8d43c7198 --- /dev/null +++ b/tools/ui/node_modules/nanoid/README.md @@ -0,0 +1,36 @@ +# Nano ID + +Nano ID logo by Anton Lovchikov + +**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) + +A tiny, secure, URL-friendly, unique string ID generator for JavaScript. + +> “An amazing level of senseless perfectionism, +> which is simply impossible not to respect.” + +* **Small.** 130 bytes (minified and gzipped). No dependencies. + [Size Limit] controls the size. +* **Fast.** It is 2 times faster than UUID. +* **Safe.** It uses hardware random generator. Can be used in clusters. +* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). + So ID size was reduced from 36 to 21 symbols. +* **Portable.** Nano ID was ported + to [20 programming languages](#other-programming-languages). + +```js +import { nanoid } from 'nanoid' +model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" +``` + +Supports modern browsers, IE [with Babel], Node.js and React Native. + +[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ +[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ +[Size Limit]: https://github.com/ai/size-limit + + + Sponsored by Evil Martians + diff --git a/tools/ui/node_modules/nanoid/async/index.browser.cjs b/tools/ui/node_modules/nanoid/async/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0c8521ae8602876678dbf47dd3a47836e9ea1a5e --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/index.browser.cjs @@ -0,0 +1,43 @@ +let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + + + + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return async (size = defaultSize) => { + if (size <= 0) return '' + let id = '' + while (true) { + let bytes = crypto.getRandomValues(new Uint8Array(step)) + let i = step | 0 + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let nanoid = async (size = 21) => { + let id = '' + let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) + + while (size--) { + let byte = bytes[size] & 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte < 63) { + id += '_' + } else { + id += '-' + } + } + return id +} + +module.exports = { nanoid, customAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/async/index.browser.js b/tools/ui/node_modules/nanoid/async/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..b10c13c8fb44d2c8936666a8a11e5b20dcb9a330 --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/index.browser.js @@ -0,0 +1,43 @@ +let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + + + + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return async (size = defaultSize) => { + if (size <= 0) return '' + let id = '' + while (true) { + let bytes = crypto.getRandomValues(new Uint8Array(step)) + let i = step | 0 + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let nanoid = async (size = 21) => { + let id = '' + let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) + + while (size--) { + let byte = bytes[size] & 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte < 63) { + id += '_' + } else { + id += '-' + } + } + return id +} + +export { nanoid, customAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/async/index.cjs b/tools/ui/node_modules/nanoid/async/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..8f0529ea49f824c7a212628a2f3fd675637af61a --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/index.cjs @@ -0,0 +1,47 @@ +let crypto = require('crypto') + +let { urlAlphabet } = require('../url-alphabet/index.cjs') + +let random = bytes => + new Promise((resolve, reject) => { + crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { + if (err) { + reject(err) + } else { + resolve(buf) + } + }) + }) + +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + + + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + + return (size = defaultSize) => { + if (size <= 0) return Promise.resolve('') + return tick('', size) + } +} + +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) + +module.exports = { nanoid, customAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/async/index.d.ts b/tools/ui/node_modules/nanoid/async/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e919658b82e66e3bd39800232da5a469c8d13a8 --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/index.d.ts @@ -0,0 +1,56 @@ +/** + * Generate secure URL-friendly unique ID. The non-blocking version. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid/async' + * nanoid().then(id => { + * model.id = id + * }) + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A promise with a random string. + */ +export function nanoid(size?: number): Promise + +/** + * A low-level function. + * Generate secure unique ID with custom alphabet. The non-blocking version. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A function that returns a promise with a random string. + * + * ```js + * import { customAlphabet } from 'nanoid/async' + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid().then(id => { + * model.id = id //=> "8ё56а" + * }) + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => Promise + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { random } from 'nanoid/async' + * random(5).then(bytes => { + * bytes //=> [10, 67, 212, 67, 89] + * }) + * ``` + * + * @param bytes Size of the array. + * @returns A promise with a random bytes array. + */ +export function random(bytes: number): Promise diff --git a/tools/ui/node_modules/nanoid/async/index.js b/tools/ui/node_modules/nanoid/async/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1364176aeac35ac472ab5ac2c1e3aee34efaeeb8 --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/index.js @@ -0,0 +1,47 @@ +import crypto from 'crypto' + +import { urlAlphabet } from '../url-alphabet/index.js' + +let random = bytes => + new Promise((resolve, reject) => { + crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { + if (err) { + reject(err) + } else { + resolve(buf) + } + }) + }) + +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + + + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + + return (size = defaultSize) => { + if (size <= 0) return Promise.resolve('') + return tick('', size) + } +} + +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) + +export { nanoid, customAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/async/index.native.js b/tools/ui/node_modules/nanoid/async/index.native.js new file mode 100644 index 0000000000000000000000000000000000000000..9579c126ebff2567caa0d1d8a0b5cf9759a77692 --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/index.native.js @@ -0,0 +1,35 @@ +import { getRandomBytesAsync } from 'expo-random' + +import { urlAlphabet } from '../url-alphabet/index.js' + +let random = getRandomBytesAsync + +let customAlphabet = (alphabet, defaultSize = 21) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + + + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + let tick = (id, size = defaultSize) => + random(step).then(bytes => { + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length >= size) return id + } + return tick(id, size) + }) + + return size => tick('', size) +} + +let nanoid = (size = 21) => + random((size |= 0)).then(bytes => { + let id = '' + while (size--) { + id += urlAlphabet[bytes[size] & 63] + } + return id + }) + +export { nanoid, customAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/async/package.json b/tools/ui/node_modules/nanoid/async/package.json new file mode 100644 index 0000000000000000000000000000000000000000..578cdb4cb9babb17e4e08b4f6a30c2e195d2afed --- /dev/null +++ b/tools/ui/node_modules/nanoid/async/package.json @@ -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" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/nanoid/bin/nanoid.cjs b/tools/ui/node_modules/nanoid/bin/nanoid.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c76db0faa81f6d683c4a18a212f804fb70cf8143 --- /dev/null +++ b/tools/ui/node_modules/nanoid/bin/nanoid.cjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +let { nanoid, customAlphabet } = require('..') + +function print(msg) { + process.stdout.write(msg + '\n') +} + +function error(msg) { + process.stderr.write(msg + '\n') + process.exit(1) +} + +if (process.argv.includes('--help') || process.argv.includes('-h')) { + print(` + Usage + $ nanoid [options] + + Options + -s, --size Generated ID size + -a, --alphabet Alphabet to use + -h, --help Show this help + + Examples + $ nanoid --s 15 + S9sBF77U6sDB8Yg + + $ nanoid --size 10 --alphabet abc + bcabababca`) + process.exit() +} + +let alphabet, size +for (let i = 2; i < process.argv.length; i++) { + let arg = process.argv[i] + if (arg === '--size' || arg === '-s') { + size = Number(process.argv[i + 1]) + i += 1 + if (Number.isNaN(size) || size <= 0) { + error('Size must be positive integer') + } + } else if (arg === '--alphabet' || arg === '-a') { + alphabet = process.argv[i + 1] + i += 1 + } else { + error('Unknown argument ' + arg) + } +} + +if (alphabet) { + let customNanoid = customAlphabet(alphabet, size) + print(customNanoid()) +} else { + print(nanoid(size)) +} diff --git a/tools/ui/node_modules/nanoid/index.browser.cjs b/tools/ui/node_modules/nanoid/index.browser.cjs new file mode 100644 index 0000000000000000000000000000000000000000..4de57f03b8cad48475ed6e88eb2674f53e6d108a --- /dev/null +++ b/tools/ui/node_modules/nanoid/index.browser.cjs @@ -0,0 +1,45 @@ + +let { urlAlphabet } = require('./url-alphabet/index.cjs') + +let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + + + + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + if (size <= 0) return '' + let id = '' + while (true) { + let bytes = getRandom(step) + let j = step | 0 + while (j--) { + id += alphabet[bytes[j] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => + crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { + byte &= 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte > 62) { + id += '-' + } else { + id += '_' + } + return id + }, '') + +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/index.browser.js b/tools/ui/node_modules/nanoid/index.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..03da901b72ae97f2fa16dc256202789b206f3a54 --- /dev/null +++ b/tools/ui/node_modules/nanoid/index.browser.js @@ -0,0 +1,45 @@ + +import { urlAlphabet } from './url-alphabet/index.js' + +let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) + +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 + + + + let step = -~((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + if (size <= 0) return '' + let id = '' + while (true) { + let bytes = getRandom(step) + let j = step | 0 + while (j--) { + id += alphabet[bytes[j] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => + crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { + byte &= 63 + if (byte < 36) { + id += byte.toString(36) + } else if (byte < 62) { + id += (byte - 26).toString(36).toUpperCase() + } else if (byte > 62) { + id += '-' + } else { + id += '_' + } + return id + }, '') + +export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/index.cjs b/tools/ui/node_modules/nanoid/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..7fc216af5a75f7132994c920cfdb5cc667d4c3a4 --- /dev/null +++ b/tools/ui/node_modules/nanoid/index.cjs @@ -0,0 +1,58 @@ +let crypto = require('crypto') + +let { urlAlphabet } = require('./url-alphabet/index.cjs') + +const POOL_SIZE_MULTIPLIER = 128 +let pool, poolOffset + +let fillPool = bytes => { + if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size') + if (!pool || pool.length < bytes) { + pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) + crypto.randomFillSync(pool) + poolOffset = 0 + } else if (poolOffset + bytes > pool.length) { + crypto.randomFillSync(pool) + poolOffset = 0 + } + poolOffset += bytes +} + +let random = bytes => { + fillPool((bytes |= 0)) + return pool.subarray(poolOffset - bytes, poolOffset) +} + +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + + + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + if (size <= 0) return '' + let id = '' + while (true) { + let bytes = getRandom(step) + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => { + fillPool((size |= 0)) + let id = '' + for (let i = poolOffset - size; i < poolOffset; i++) { + id += urlAlphabet[pool[i] & 63] + } + return id +} + +module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/index.d.cts b/tools/ui/node_modules/nanoid/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/tools/ui/node_modules/nanoid/index.d.cts @@ -0,0 +1,91 @@ +/** + * Generate secure URL-friendly unique ID. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate secure unique ID with custom alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * const { customAlphabet } = require('nanoid') + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid() //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string + +/** + * Generate unique ID with custom random generator and alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * ```js + * import { customRandom } from 'nanoid/format' + * + * const nanoid = customRandom('abcdef', 5, size => { + * const random = [] + * for (let i = 0; i < size; i++) { + * random.push(randomByte()) + * } + * return random + * }) + * + * nanoid() //=> "fbaef" + * ``` + * + * @param alphabet Alphabet used to generate a random string. + * @param size Size of the random string. + * @param random A random bytes generator. + * @returns A random string generator. + */ +export function customRandom( + alphabet: string, + size: number, + random: (bytes: number) => Uint8Array +): () => string + +/** + * URL safe symbols. + * + * ```js + * import { urlAlphabet } from 'nanoid' + * const nanoid = customAlphabet(urlAlphabet, 10) + * nanoid() //=> "Uakgb_J5m9" + * ``` + */ +export const urlAlphabet: string + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { customRandom, random } from 'nanoid' + * const nanoid = customRandom("abcdef", 5, random) + * ``` + * + * @param bytes Size of the array. + * @returns An array of random bytes. + */ +export function random(bytes: number): Uint8Array diff --git a/tools/ui/node_modules/nanoid/index.d.ts b/tools/ui/node_modules/nanoid/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e111a39de010f548d397f06f8f964191834b869 --- /dev/null +++ b/tools/ui/node_modules/nanoid/index.d.ts @@ -0,0 +1,91 @@ +/** + * Generate secure URL-friendly unique ID. + * + * By default, the ID will have 21 symbols to have a collision probability + * similar to UUID v4. + * + * ```js + * import { nanoid } from 'nanoid' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate secure unique ID with custom alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * const { customAlphabet } = require('nanoid') + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * nanoid() //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string + +/** + * Generate unique ID with custom random generator and alphabet. + * + * Alphabet must contain 256 symbols or less. Otherwise, the generator + * will not be secure. + * + * ```js + * import { customRandom } from 'nanoid/format' + * + * const nanoid = customRandom('abcdef', 5, size => { + * const random = [] + * for (let i = 0; i < size; i++) { + * random.push(randomByte()) + * } + * return random + * }) + * + * nanoid() //=> "fbaef" + * ``` + * + * @param alphabet Alphabet used to generate a random string. + * @param size Size of the random string. + * @param random A random bytes generator. + * @returns A random string generator. + */ +export function customRandom( + alphabet: string, + size: number, + random: (bytes: number) => Uint8Array +): () => string + +/** + * URL safe symbols. + * + * ```js + * import { urlAlphabet } from 'nanoid' + * const nanoid = customAlphabet(urlAlphabet, 10) + * nanoid() //=> "Uakgb_J5m9" + * ``` + */ +export const urlAlphabet: string + +/** + * Generate an array of random bytes collected from hardware noise. + * + * ```js + * import { customRandom, random } from 'nanoid' + * const nanoid = customRandom("abcdef", 5, random) + * ``` + * + * @param bytes Size of the array. + * @returns An array of random bytes. + */ +export function random(bytes: number): Uint8Array diff --git a/tools/ui/node_modules/nanoid/index.js b/tools/ui/node_modules/nanoid/index.js new file mode 100644 index 0000000000000000000000000000000000000000..565ab45f0f9e997381a4134787ce3fe77b997cce --- /dev/null +++ b/tools/ui/node_modules/nanoid/index.js @@ -0,0 +1,63 @@ +import crypto from 'crypto' + +import { urlAlphabet } from './url-alphabet/index.js' + +const POOL_SIZE_MULTIPLIER = 128 +let pool, poolOffset + +let fillPool = bytes => { + if (bytes < 0) throw new RangeError('Wrong ID size') + try { + if (!pool || pool.length < bytes) { + pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) + crypto.randomFillSync(pool) + poolOffset = 0 + } else if (poolOffset + bytes > pool.length) { + crypto.randomFillSync(pool) + poolOffset = 0 + } + } catch (e) { + pool = undefined + throw e + } + poolOffset += bytes +} + +let random = bytes => { + fillPool((bytes |= 0)) + return pool.subarray(poolOffset - bytes, poolOffset) +} + +let customRandom = (alphabet, defaultSize, getRandom) => { + let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 + + + let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) + + return (size = defaultSize) => { + if (size <= 0) return '' + let id = '' + while (true) { + let bytes = getRandom(step) + let i = step + while (i--) { + id += alphabet[bytes[i] & mask] || '' + if (id.length === size) return id + } + } + } +} + +let customAlphabet = (alphabet, size = 21) => + customRandom(alphabet, size, random) + +let nanoid = (size = 21) => { + fillPool((size |= 0)) + let id = '' + for (let i = poolOffset - size; i < poolOffset; i++) { + id += urlAlphabet[pool[i] & 63] + } + return id +} + +export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/tools/ui/node_modules/nanoid/nanoid.js b/tools/ui/node_modules/nanoid/nanoid.js new file mode 100644 index 0000000000000000000000000000000000000000..ec242eadc85e4b0ef546c8fdc771f7e9d7d2f081 --- /dev/null +++ b/tools/ui/node_modules/nanoid/nanoid.js @@ -0,0 +1 @@ +export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),""); \ No newline at end of file diff --git a/tools/ui/node_modules/nanoid/non-secure/index.cjs b/tools/ui/node_modules/nanoid/non-secure/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..5f1e7434fbf7659c35684a2aa2b52e74d4e2c4f3 --- /dev/null +++ b/tools/ui/node_modules/nanoid/non-secure/index.cjs @@ -0,0 +1,24 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + let i = size | 0 + while (i-- > 0) { + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} + +let nanoid = (size = 21) => { + let id = '' + let i = size | 0 + while (i-- > 0) { + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} + +module.exports = { nanoid, customAlphabet } diff --git a/tools/ui/node_modules/nanoid/non-secure/index.d.ts b/tools/ui/node_modules/nanoid/non-secure/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4965322d636016d678fccdd94c3aacdf1fc50075 --- /dev/null +++ b/tools/ui/node_modules/nanoid/non-secure/index.d.ts @@ -0,0 +1,33 @@ +/** + * Generate URL-friendly unique ID. This method uses the non-secure + * predictable random generator with bigger collision probability. + * + * ```js + * import { nanoid } from 'nanoid/non-secure' + * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" + * ``` + * + * @param size Size of the ID. The default size is 21. + * @returns A random string. + */ +export function nanoid(size?: number): string + +/** + * Generate a unique ID based on a custom alphabet. + * This method uses the non-secure predictable random generator + * with bigger collision probability. + * + * @param alphabet Alphabet used to generate the ID. + * @param defaultSize Size of the ID. The default size is 21. + * @returns A random string generator. + * + * ```js + * import { customAlphabet } from 'nanoid/non-secure' + * const nanoid = customAlphabet('0123456789абвгдеё', 5) + * model.id = //=> "8ё56а" + * ``` + */ +export function customAlphabet( + alphabet: string, + defaultSize?: number +): (size?: number) => string diff --git a/tools/ui/node_modules/nanoid/non-secure/index.js b/tools/ui/node_modules/nanoid/non-secure/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2848f3f96088794ee48a8e9696c6585ec5a7cc51 --- /dev/null +++ b/tools/ui/node_modules/nanoid/non-secure/index.js @@ -0,0 +1,24 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +let customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = '' + let i = size | 0 + while (i-- > 0) { + id += alphabet[(Math.random() * alphabet.length) | 0] + } + return id + } +} + +let nanoid = (size = 21) => { + let id = '' + let i = size | 0 + while (i-- > 0) { + id += urlAlphabet[(Math.random() * 64) | 0] + } + return id +} + +export { nanoid, customAlphabet } diff --git a/tools/ui/node_modules/nanoid/non-secure/package.json b/tools/ui/node_modules/nanoid/non-secure/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/tools/ui/node_modules/nanoid/non-secure/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": "index.js" +} \ No newline at end of file diff --git a/tools/ui/node_modules/nanoid/package.json b/tools/ui/node_modules/nanoid/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5828231e680dfdc6ef21c682da6b51c8da3137aa --- /dev/null +++ b/tools/ui/node_modules/nanoid/package.json @@ -0,0 +1,89 @@ +{ + "name": "nanoid", + "version": "3.3.17", + "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator", + "keywords": [ + "uuid", + "random", + "id", + "url" + ], + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "author": "Andrey Sitnik ", + "license": "MIT", + "repository": "ai/nanoid", + "browser": { + "./index.js": "./index.browser.js", + "./async/index.js": "./async/index.browser.js", + "./async/index.cjs": "./async/index.browser.cjs", + "./index.cjs": "./index.browser.cjs" + }, + "react-native": "index.js", + "bin": "./bin/nanoid.cjs", + "sideEffects": false, + "types": "./index.d.ts", + "type": "module", + "main": "index.cjs", + "module": "index.js", + "exports": { + ".": { + "react-native": "./index.browser.js", + "browser": "./index.browser.js", + "require": { + "types": "./index.d.cts", + "default": "./index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "default": "./index.js" + }, + "./package.json": "./package.json", + "./async/package.json": "./async/package.json", + "./async": { + "browser": "./async/index.browser.js", + "require": { + "types": "./index.d.cts", + "default": "./async/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./async/index.js" + }, + "default": "./async/index.js" + }, + "./non-secure/package.json": "./non-secure/package.json", + "./non-secure": { + "require": { + "types": "./index.d.cts", + "default": "./non-secure/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./non-secure/index.js" + }, + "default": "./non-secure/index.js" + }, + "./url-alphabet/package.json": "./url-alphabet/package.json", + "./url-alphabet": { + "require": { + "types": "./index.d.cts", + "default": "./url-alphabet/index.cjs" + }, + "import": { + "types": "./index.d.ts", + "default": "./url-alphabet/index.js" + }, + "default": "./url-alphabet/index.js" + } + } +} diff --git a/tools/ui/node_modules/nanoid/url-alphabet/index.cjs b/tools/ui/node_modules/nanoid/url-alphabet/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..9021f0ba58856772c1e787f1581a566bbb5cd1d4 --- /dev/null +++ b/tools/ui/node_modules/nanoid/url-alphabet/index.cjs @@ -0,0 +1,4 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +module.exports = { urlAlphabet } diff --git a/tools/ui/node_modules/nanoid/url-alphabet/index.js b/tools/ui/node_modules/nanoid/url-alphabet/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f995c4f3a79097000a66e25c7ccba42c20dd88eb --- /dev/null +++ b/tools/ui/node_modules/nanoid/url-alphabet/index.js @@ -0,0 +1,4 @@ +let urlAlphabet = + 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' + +export { urlAlphabet } diff --git a/tools/ui/node_modules/nanoid/url-alphabet/package.json b/tools/ui/node_modules/nanoid/url-alphabet/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9930d6ad1671e19bfddbdeeb9bbcdeab83dc00ba --- /dev/null +++ b/tools/ui/node_modules/nanoid/url-alphabet/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "main": "index.cjs", + "module": "index.js", + "react-native": "index.js" +} \ No newline at end of file diff --git a/tools/ui/node_modules/natural-compare/README.md b/tools/ui/node_modules/natural-compare/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c85dfdf98ce8750965d43a5ebb1b1bedc7a363e6 --- /dev/null +++ b/tools/ui/node_modules/natural-compare/README.md @@ -0,0 +1,125 @@ + +[Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png +[Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png +[1]: https://travis-ci.org/litejs/natural-compare-lite +[2]: https://coveralls.io/r/litejs/natural-compare-lite +[npm package]: https://npmjs.org/package/natural-compare-lite +[GitHub repo]: https://github.com/litejs/natural-compare-lite + + + + @version 1.4.0 + @date 2015-10-26 + @stability 3 - Stable + + +Natural Compare – [![Build][]][1] [![Coverage][]][2] +=============== + +Compare strings containing a mix of letters and numbers +in the way a human being would in sort order. +This is described as a "natural ordering". + +```text +Standard sorting: Natural order sorting: + img1.png img1.png + img10.png img2.png + img12.png img10.png + img2.png img12.png +``` + +String.naturalCompare returns a number indicating +whether a reference string comes before or after or is the same +as the given string in sort order. +Use it with builtin sort() function. + + + +### Installation + +- In browser + +```html + +``` + +- In node.js: `npm install natural-compare-lite` + +```javascript +require("natural-compare-lite") +``` + +### Usage + +```javascript +// Simple case sensitive example +var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; +a.sort(String.naturalCompare); +// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] + +// Use wrapper function for case insensitivity +a.sort(function(a, b){ + return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); +}) + +// In most cases we want to sort an array of objects +var a = [ {"street":"350 5th Ave", "room":"A-1021"} + , {"street":"350 5th Ave", "room":"A-21046-b"} ]; + +// sort by street, then by room +a.sort(function(a, b){ + return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); +}) + +// When text transformation is needed (eg toLowerCase()), +// it is best for performance to keep +// transformed key in that object. +// There are no need to do text transformation +// on each comparision when sorting. +var a = [ {"make":"Audi", "model":"A6"} + , {"make":"Kia", "model":"Rio"} ]; + +// sort by make, then by model +a.map(function(car){ + car.sort_key = (car.make + " " + car.model).toLowerCase(); +}) +a.sort(function(a, b){ + return String.naturalCompare(a.sort_key, b.sort_key); +}) +``` + +- Works well with dates in ISO format eg "Rev 2012-07-26.doc". + + +### Custom alphabet + +It is possible to configure a custom alphabet +to achieve a desired order. + +```javascript +// Estonian alphabet +String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" +["t", "z", "x", "õ"].sort(String.naturalCompare) +// ["z", "t", "õ", "x"] + +// Russian alphabet +String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" +["Ё", "А", "Б"].sort(String.naturalCompare) +// ["А", "Б", "Ё"] +``` + + +External links +-------------- + +- [GitHub repo][https://github.com/litejs/natural-compare-lite] +- [jsperf test](http://jsperf.com/natural-sort-2/12) + + +Licence +------- + +Copyright (c) 2012-2015 Lauri Rooden <lauri@rooden.ee> +[The MIT License](http://lauri.rooden.ee/mit-license.txt) + + diff --git a/tools/ui/node_modules/natural-compare/index.js b/tools/ui/node_modules/natural-compare/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e705d49f5f1ba936086ae6d0fa24db176eb82adf --- /dev/null +++ b/tools/ui/node_modules/natural-compare/index.js @@ -0,0 +1,57 @@ + + + +/* + * @version 1.4.0 + * @date 2015-10-26 + * @stability 3 - Stable + * @author Lauri Rooden (https://github.com/litejs/natural-compare-lite) + * @license MIT License + */ + + +var naturalCompare = function(a, b) { + var i, codeA + , codeB = 1 + , posA = 0 + , posB = 0 + , alphabet = String.alphabet + + function getCode(str, pos, code) { + if (code) { + for (i = pos; code = getCode(str, i), code < 76 && code > 65;) ++i; + return +str.slice(pos - 1, i) + } + code = alphabet && alphabet.indexOf(str.charAt(pos)) + return code > -1 ? code + 76 : ((code = str.charCodeAt(pos) || 0), code < 45 || code > 127) ? code + : code < 46 ? 65 // - + : code < 48 ? code - 1 + : code < 58 ? code + 18 // 0-9 + : code < 65 ? code - 11 + : code < 91 ? code + 11 // A-Z + : code < 97 ? code - 37 + : code < 123 ? code + 5 // a-z + : code - 63 + } + + + if ((a+="") != (b+="")) for (;codeB;) { + codeA = getCode(a, posA++) + codeB = getCode(b, posB++) + + if (codeA < 76 && codeB < 76 && codeA > 66 && codeB > 66) { + codeA = getCode(a, posA, posA) + codeB = getCode(b, posB, posA = i) + posB = i + } + + if (codeA != codeB) return (codeA < codeB) ? -1 : 1 + } + return 0 +} + +try { + module.exports = naturalCompare; +} catch (e) { + String.naturalCompare = naturalCompare; +} diff --git a/tools/ui/node_modules/natural-compare/package.json b/tools/ui/node_modules/natural-compare/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a71362eea81a28d88aea31ea94942f6a675e40b --- /dev/null +++ b/tools/ui/node_modules/natural-compare/package.json @@ -0,0 +1,42 @@ +{ + "name": "natural-compare", + "version": "1.4.0", + "stability": 3, + "author": "Lauri Rooden (https://github.com/litejs/natural-compare-lite)", + "license": "MIT", + "description": "Compare strings containing a mix of letters and numbers in the way a human being would in sort order.", + "keywords": [ + "string", + "natural", + "order", + "sort", + "natsort", + "natcmp", + "compare", + "alphanum", + "litejs" + ], + "main": "index.js", + "readmeFilename": "README.md", + "files": [ + "index.js" + ], + "scripts": { + "build": "node node_modules/buildman/index.js --all", + "test": "node tests/index.js" + }, + "repository": "git://github.com/litejs/natural-compare-lite.git", + "bugs": { + "url": "https://github.com/litejs/natural-compare-lite/issues" + }, + "devDependencies": { + "buildman": "*", + "testman": "*" + }, + "buildman": { + "dist/index-min.js": { + "banner": "/*! litejs.com/MIT-LICENSE.txt */", + "input": "index.js" + } + } +} diff --git a/tools/ui/node_modules/natural-orderby/CHANGELOG.md b/tools/ui/node_modules/natural-orderby/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b298fffba5416d24ced21e84319606c1331a362c --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/CHANGELOG.md @@ -0,0 +1,32 @@ +# natural-orderby + +## 5.0.0 + +### Major Changes + +- feat: support numeric separators +- feat: add ability to define locale for sorting unicode + +## 4.0.0 + +### Major Changes + +- fix: update `Identifier` to be `keyof T` instead of any `string` + +## 3.0.2 + +### Patch Changes + +- fix: performance issue when parsing date strings + +## 3.0.1 + +### Patch Changes + +- fix umd imports + +## 3.0.0 + +### Major Changes + +- Migrate codebase to TypeScript diff --git a/tools/ui/node_modules/natural-orderby/LICENSE.md b/tools/ui/node_modules/natural-orderby/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..1b60ddb00be9f6e1c7302bbfd0b903c92ae206b2 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2018 - present Olaf Ennen + +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. diff --git a/tools/ui/node_modules/natural-orderby/README.md b/tools/ui/node_modules/natural-orderby/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9b21175f08ed3fd92b8f7c9dec226bfa0223d1d2 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/README.md @@ -0,0 +1,538 @@ +# Welcome to 🌲 natural-orderby + +Lightweight (< 1.6kB gzipped) and performant natural sorting of arrays and collections by differentiating between unicode characters, numbers, dates, etc. + +[![npm version](https://img.shields.io/npm/v/natural-orderby.svg)](https://www.npmjs.com/package/natural-orderby) +[![downloads](https://img.shields.io/npm/dm/natural-orderby.svg)](https://www.npmjs.com/package/natural-orderby) +[![CI](https://github.com/yobacca/natural-orderby/workflows/CI/badge.svg)](https://github.com/yobacca/natural-orderby/actions) +[![coverage](https://img.shields.io/codecov/c/github/yobacca/natural-orderby.svg)](https://codecov.io/gh/yobacca/natural-orderby) + +People sort strings containing numbers differently than most sorting algorithms, which sort values by comparing strings in Unicode code point order. This produces an ordering that is inconsistent with human logic. + +`natural-orderby` sorts the primitive values of [`Boolean`](https://developer.mozilla.org/en-US/docs/Glossary/Boolean), [`Null`](https://developer.mozilla.org/en-US/docs/Glossary/Null), [`Undefined`](https://developer.mozilla.org/en-US/docs/Glossary/Undefined), [`Number`](https://developer.mozilla.org/en-US/docs/Glossary/Number) or [`String`](https://developer.mozilla.org/en-US/docs/Glossary/String) type as well as [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) objects. When comparing strings it differentiates between unicode characters, integer, floating as well as hexadecimal numbers, various date formats, etc. You may sort flat or nested arrays or arrays of objects in a natural sorting order using `natural-orderby`. + +In addition to the efficient and fast `orderBy()` method `natural-orderby` also provides the method `compare()`, which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + +## Contents + +- [Getting Started](#getting-started) +- [Usage](#usage) +- [API Reference](#api-reference) +- [TypeScript Declarations](#typescript-declarations) +- [Credits](#credits) +- [License](#license) + +--- + +## Getting Started + +```bash +# npm +npm install natural-orderby --save + +# yarn +yarn add natural-orderby +``` + +If you´re not using a module bundler or package manager there´s also a global ("IIFE") build hosted on the unpkg CDN. Simply add the following ` +``` + +Once you've added `natural-orderby` you will have access to the global `window.naturalOrderBy` variable. + +## Usage + + +```javascript +// Using ES modules +import { orderBy } from 'natural-orderby'; + +// Using CommonJS modules +// const { orderBy } = require('natural-orderby'); + +const users = [ + { + username: 'Bamm-Bamm', + ip: '192.168.5.2', + datetime: 'Fri Jun 15 2018 16:48:00 GMT+0200 (CEST)' + }, + { + username: 'Wilma', + ip: '192.168.10.1', + datetime: '14 Jun 2018 00:00:00 PDT' + }, + { + username: 'Dino', + ip: '192.168.0.2', + datetime: 'June 15, 2018 14:48:00' + }, + { + username: 'Barney', + ip: '192.168.1.1', + datetime: 'Thu, 14 Jun 2018 07:00:00 GMT' + }, + { + username: 'Pebbles', + ip: '192.168.1.21', + datetime: '15 June 2018 14:48 UTC' + }, + { + username: 'Hoppy', + ip: '192.168.5.10', + datetime: '2018-06-15T14:48:00.000Z' + }, +]; + +const sortedUsers = orderBy( + users, + [v => v.datetime, v => v.ip], + ['desc', 'asc'] +); +``` + +This is the return value of `orderBy()`: + +```javascript +[ + { + username: 'Dino', + ip: '192.168.0.2', + datetime: 'June 15, 2018 14:48:00', + }, + { + username: 'Pebbles', + ip: '192.168.1.21', + datetime: '15 June 2018 14:48 UTC', + }, + { + username: 'Bamm-Bamm', + ip: '192.168.5.2', + datetime: 'Fri Jun 15 2018 16:48:00 GMT+0200 (CEST)', + }, + { + username: 'Hoppy', + ip: '192.168.5.10', + datetime: '2018-06-15T14:48:00.000Z', + }, + { + username: 'Barney', + ip: '192.168.1.1', + datetime: 'Thu, 14 Jun 2018 07:00:00 GMT', + }, + { + username: 'Wilma', + ip: '192.168.10.1', + datetime: '14 Jun 2018 00:00:00 PDT', + }, +]; +``` + +## API Reference + +### `orderBy()` + +Creates an array of elements, natural sorted by specified `identifiers` and the corresponding sort `orders`. This method implements a stable sort algorithm, which means the original sort order of equal elements is preserved. +It also avoids the high overhead caused by [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) invoking a compare function multiple times per element within the array. + +#### Syntax + + +```typescript +orderBy( + collection: ReadonlyArray, + identifiers?: ReadonlyArray> | Identifier | null, + orders?: ReadonlyArray | Order | null + locale?: string +): Array +``` + +| Type | Value | +| :-------------- | :----------------------------------------------------------------------------------- | +| `Identifier` | keyof T | number | (value: T) => unknown | +| `Order` | 'asc' | 'desc' | (valueA: unknown, valueB: unknown) => number | + +#### Description + +`orderBy()` sorts the elements of an array by specified identifiers and the corresponding sort orders in a natural order and returns a new array containing the sorted elements. + +If `collection` is an array of primitives, `identifiers` may be unspecified. Otherwise, you should specify `identifiers` to sort by or `collection` will be returned unsorted. An identifier can be expressed by: + +- an index position, if `collection` is a nested array, +- a property name, if `collection` is an array of objects, +- a function which returns a particular value from an element of a nested array or an array of objects. This function will be invoked by passing one element of `collection`. + +If `orders` is unspecified, all values are sorted in ascending order. Otherwise, specify an order of `'desc'` for descending or `'asc'` for ascending sort order of corresponding values. You may also specify a compare function for an order, which will be invoked by two arguments: `(valueA, valueB)`. It must return a number representing the sort order. + +If you want to sort unicode strings according to a specific locale, please provide a string value for `locale` with a BCP 47 language tag. If the argument is unspecified, the host locale setting will be used. + +> Note: `orderBy()` always returns a new array, even if the original was already sorted. + +#### Examples + + +```javascript +import { orderBy } from 'natural-orderby'; + +// Simple numerics + +orderBy(['10', 9, 2, '1', '4']); +// => ['1', 2, '4', 9, '10'] + + +// Floats + +orderBy(['10.0401', 10.022, 10.042, '10.021999']); +// => ['10.021999', 10.022, '10.0401', 10.042] + + +// Float & decimal notation + +orderBy(['10.04f', '10.039F', '10.038d', '10.037D']); +// => ['10.037D', '10.038d', '10.039F', '10.04f'] + + +// Scientific notation + +orderBy(['1.528535047e5', '1.528535047e7', '1.528535047e3']); +// => ['1.528535047e3', '1.528535047e5', '1.528535047e7'] + + +// IP addresses + +orderBy(['192.168.201.100', '192.168.201.12', '192.168.21.1']); +// => ['192.168.21.1', '192.168.201.12', '192.168.21.100'] + + +// Filenames + +orderBy(['01asset_0815.png', 'asset_47103.jpg', 'asset_151.jpg', '001asset_4711.jpg', 'asset_342.mp4']); +// => ['001asset_4711.jpg', '01asset_0815.png', 'asset_151.jpg', 'asset_342.mp4', 'asset_47103.jpg'] + +// Filenames - ordered by extension and filename + +orderBy( + ['01asset_0815.png', 'asset_47103.jpg', 'asset_151.jpg', '001asset_4711.jpg', 'asset_342.mp4'],[v => v.split('.').pop(), v => v] +); +// => ['001asset_4711.jpg', 'asset_151.jpg', 'asset_47103.jpg', 'asset_342.mp4', '01asset_0815.png'] + + +// Dates + +orderBy(['10/12/2018', '10/11/2018', '10/11/2017', '10/12/2017']); +// => ['10/11/2017', '10/12/2017', '10/11/2018', '10/12/2018'] + +orderBy(['Thu, 15 Jun 2017 20:45:30 GMT', 'Thu, 3 May 2018 17:45:30 GMT', 'Thu, 15 Jun 2017 17:45:30 GMT']); +// => ['Thu, 15 Jun 2017 17:45:30 GMT', 'Thu, 15 Jun 2018 20:45:30 GMT', 'Thu, 3 May 2018 17:45:30 GMT'] + + +// Money + +orderBy(['$102.00', '$21.10', '$101.02', '$101.01']); +// => ['$21.10', '$101.01', '$101.02', '$102.00'] + + +// Case-insensitive sort order + +orderBy(['A', 'C', 'E', 'b', 'd', 'f']); +// => ['A', 'b', 'C', 'd', 'E', 'f'] + + +// Default ascending sort order + +orderBy(['a', 'c', 'f', 'd', 'e', 'b']); +// => ['a', 'b', 'c', 'd', 'e', 'f'] + + +// Descending sort order + +orderBy(['a', 'c', 'f', 'd', 'e', 'b'], null, ['desc']); +// => ['f', 'e', 'd', 'c', 'b', 'a'] + + +// Custom compare function + +orderBy([2, 1, 5, 8, 6, 9], null, [(valueA, valueB) => valueA - valueB]); +// => [1, 2, 5, 6, 8, 9] + + +// collections + +const users = [ + { + username: 'Bamm-Bamm', + ip: '192.168.5.2', + datetime: 'Fri Jun 15 2018 16:48:00 GMT+0200 (CEST)' + }, + { + username: 'Wilma', + ip: '192.168.10.1', + datetime: '14 Jun 2018 00:00:00 PDT' + }, + { + username: 'Dino', + ip: '192.168.0.2', + datetime: 'June 15, 2018 14:48:00' + }, + { + username: 'Barney', + ip: '192.168.1.1', + datetime: 'Thu, 14 Jun 2018 07:00:00 GMT' + }, + { + username: 'Pebbles', + ip: '192.168.1.21', + datetime: '15 June 2018 14:48 UTC' + }, + { + username: 'Hoppy', + ip: '192.168.5.10', + datetime: '2018-06-15T14:48:00.000Z' + }, +]; + +orderBy( + users, + [v => v.datetime, v => v.ip], + ['desc', 'asc'] +); +// => [ +// { +// username: 'Dino', +// ip: '192.168.0.2', +// datetime: 'June 15, 2018 14:48:00', +// }, +// { +// username: 'Pebbles', +// ip: '192.168.1.21', +// datetime: '15 June 2018 14:48 UTC', +// }, +// { +// username: 'Bamm-Bamm', +// ip: '192.168.5.2', +// datetime: 'Fri Jun 15 2018 16:48:00 GMT+0200 (CEST)', +// }, +// { +// username: 'Hoppy', +// ip: '192.168.5.10', +// datetime: '2018-06-15T14:48:00.000Z', +// }, +// { +// username: 'Barney', +// ip: '192.168.1.1', +// datetime: 'Thu, 14 Jun 2018 07:00:00 GMT', +// }, +// { +// username: 'Wilma', +// ip: '192.168.10.1', +// datetime: '14 Jun 2018 00:00:00 PDT', +// }, +// ] +``` + +### `compare()` + +Creates a compare function that defines the natural sort order and which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + +#### Syntax + + +```javascript +compare(options?: CompareOptions): CompareFn +``` + +| Type | Value | +| :--------------- | :------------------------------------------------------------ | +| `CompareOptions` | { order?: 'asc' | 'desc', locale?: string } | +| `CompareFn` | (valueA: unknown, valueB: unknown) => number | + +#### Description + +`compare()` returns a compare function that defines the natural sort order and which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + +If `options` or its property `order` is unspecified, values are sorted in ascending sort order. Otherwise, specify an order of `'desc'` for descending or `'asc'` for ascending sort order of values. +If unicode strings should be ordered corresponding to a specific locale setting, specify the according value for the options property `locale`. It must be a string with a BCP 47 language tag. If the argument is unspecified, the host locale setting will be used. + +#### Examples + + +```javascript +import { compare } from 'natural-orderby'; + +// Simple numerics + +['10', 9, 2, '1', '4'].sort(compare()); +// => ['1', 2, '4', 9, '10'] + + +// Floats + +['10.0401', 10.022, 10.042, '10.021999'].sort(compare()); +// => ['10.021999', 10.022, '10.0401', 10.042] + + +// Float & decimal notation + +['10.04f', '10.039F', '10.038d', '10.037D'].sort(compare()); +// => ['10.037D', '10.038d', '10.039F', '10.04f'] + + +// Scientific notation + +['1.528535047e5', '1.528535047e7', '1.528535047e3'].sort(compare()); +// => ['1.528535047e3', '1.528535047e5', '1.528535047e7'] + + +// IP addresses + +['192.168.201.100', '192.168.201.12', '192.168.21.1'].sort(compare()); +// => ['192.168.21.1', '192.168.201.12', '192.168.21.100'] + + +// Filenames + +['01asset_0815.jpg', 'asset_47103.jpg', 'asset_151.jpg', '001asset_4711.jpg', 'asset_342.mp4'].sort(compare()); +// => ['001asset_4711.jpg', '01asset_0815.jpg', 'asset_151.jpg', 'asset_342.mp4', 'asset_47103.jpg'] + + +// Dates + +['10/12/2018', '10/11/2018', '10/11/2017', '10/12/2017'].sort(compare()); +// => ['10/11/2017', '10/12/2017', '10/11/2018', '10/12/2018'] + +['Thu, 15 Jun 2017 20:45:30 GMT', 'Thu, 3 May 2018 17:45:30 GMT', 'Thu, 15 Jun 2017 17:45:30 GMT'].sort(compare()); +// => ['Thu, 15 Jun 2017 17:45:30 GMT', 'Thu, 15 Jun 2018 20:45:30 GMT', 'Thu, 3 May 2018 17:45:30 GMT'] + + +// Money + +['$102.00', '$21.10', '$101.02', '$101.01'].sort(compare()); +// => ['$21.10', '$101.01', '$101.02', '$102.00'] + + +// Case-insensitive sort order + +['A', 'C', 'E', 'b', 'd', 'f'].sort(compare()); +// => ['A', 'b', 'C', 'd', 'E', 'f'] + + +// Default ascending sort order + +['a', 'c', 'f', 'd', 'e', 'b'].sort(compare()); +// => ['a', 'b', 'c', 'd', 'e', 'f'] + + +// Descending sort order + +['a', 'c', 'f', 'd', 'e', 'b'].sort(compare({ order: 'desc' })); +// => ['f', 'e', 'd', 'c', 'b', 'a'] + + +// collections + +const users = [ + { + username: 'Bamm-Bamm', + lastLogin: { + ip: '192.168.5.2', + datetime: 'Fri Jun 15 2018 16:48:00 GMT+0200 (CEST)' + }, + }, + { + username: 'Wilma', + lastLogin: { + ip: '192.168.10.1', + datetime: '14 Jun 2018 00:00:00 PDT' + }, + }, + { + username: 'Dino', + lastLogin: { + ip: '192.168.0.2', + datetime: 'June 15, 2018 14:48:00' + }, + }, + { + username: 'Barney', + lastLogin: { + ip: '192.168.1.1', + datetime: 'Thu, 14 Jun 2018 07:00:00 GMT' + }, + }, + { + username: 'Pebbles', + lastLogin: { + ip: '192.168.1.21', + datetime: '15 June 2018 14:48 UTC' + }, + }, + { + username: 'Hoppy', + lastLogin: { + ip: '192.168.5.10', + datetime: '2018-06-15T14:48:00.000Z' + }, + }, +]; + +users.sort((a, b) => compare()(a.lastLogin.ip, b.lastLogin.ip)); +// => [ +// { +// username: 'Dino', +// lastLogin: { +// ip: '192.168.0.2', +// datetime: 'June 15, 2018 14:48:00' +// }, +// }, +// { +// username: 'Barney', +// lastLogin: { +// ip: '192.168.1.1', +// datetime: 'Thu, 14 Jun 2018 07:00:00 GMT' +// }, +// }, +// { +// username: 'Pebbles', +// lastLogin: { +// ip: '192.168.1.21', +// datetime: '15 June 2018 14:48 UTC' +// }, +// }, +// { +// username: 'Bamm-Bamm', +// lastLogin: { +// ip: '192.168.5.2', +// datetime: 'Fri Jun 15 2018 16:48:00 GMT+0200 (CEST)' +// }, +// }, +// { +// username: 'Hoppy', +// lastLogin: { +// ip: '192.168.5.10', +// datetime: '2018-06-15T14:48:00.000Z' +// }, +// }, +// { +// username: 'Wilma', +// lastLogin: { +// ip: '192.168.10.1', +// datetime: '14 Jun 2018 00:00:00 PDT' +// }, +// }, +// ] +``` + +## TypeScript Declarations + +`natural-orderby` is completely written in [TypeScript](https://www.typescriptlang.org/) and provides TypeScript declarations. + +## Credits + +Inspired by [The Alphanum Algorithm](http://www.davekoelle.com/alphanum.html) from Dave Koelle. + +## License + +Licensed under the MIT License, Copyright © 2018 - present Olaf Ennen. + +See [LICENSE](./LICENSE.md) for more information. diff --git a/tools/ui/node_modules/natural-orderby/dist/index.d.ts b/tools/ui/node_modules/natural-orderby/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee201010443ec492bdabe96e5304bcfb444b3572 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/index.d.ts @@ -0,0 +1,26 @@ +type CompareFn = (valueA: unknown, valueB: unknown) => number; +type OrderEnum = 'asc' | 'desc'; +type Order = OrderEnum | CompareFn; +type CompareOptions = { + order?: OrderEnum; + locale?: Locale; +} | OrderEnum | undefined; +type Locale = string; +type IdentifierFn = (value: T) => unknown; +type Identifier = IdentifierFn | keyof T | number; + +/** + * Creates a compare function that defines the natural sort order considering + * the given `options` which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + */ +declare function compare(options?: CompareOptions): CompareFn; + +/** + * Creates an array of elements, natural sorted by specified identifiers and + * the corresponding sort orders. This method implements a stable sort + * algorithm, which means the original sort order of equal elements is + * preserved. + */ +declare function orderBy(collection: ReadonlyArray, identifiers?: ReadonlyArray> | Identifier | null, orders?: ReadonlyArray | Order | null, locale?: Locale): Array; + +export { type CompareFn, type CompareOptions, type Identifier, type Order, compare, orderBy }; diff --git a/tools/ui/node_modules/natural-orderby/dist/index.js b/tools/ui/node_modules/natural-orderby/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..88895853cb990d3b1d57c010033e1c373d979df3 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/index.js @@ -0,0 +1,411 @@ +/** + * natural-orderby v5.0.0 + * + * Copyright (c) Olaf Ennen + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +var compareNumbers = function compareNumbers(numberA, numberB) { + if (numberA < numberB) { + return -1; + } + if (numberA > numberB) { + return 1; + } + return 0; +}; + +var compareUnicode = function compareUnicode(stringA, stringB, locale) { + var result = stringA.localeCompare(stringB, locale); + return result ? result / Math.abs(result) : 0; +}; + +var RE_NUMBERS = /(^0x[\da-fA-F]+$|^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?!\.\d+)(?=\D|\s|$))|\d+)/g; +var RE_LEADING_OR_TRAILING_WHITESPACES = /^\s+|\s+$/g; // trim pre-post whitespace +var RE_WHITESPACES = /\s+/g; // normalize all whitespace to single ' ' character +var RE_INT_OR_FLOAT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; // identify integers and floats +var RE_DATE = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[/-]\d{1,4}[/-]\d{1,4}|^\w+, \w+ \d+, \d{4})/; // identify date strings +var RE_LEADING_ZERO = /^0+[1-9]{1}[0-9]*$/; +// eslint-disable-next-line no-control-regex +var RE_UNICODE_CHARACTERS = /[^\x00-\x80]/; + +var stringCompare = function stringCompare(stringA, stringB) { + if (stringA < stringB) { + return -1; + } + if (stringA > stringB) { + return 1; + } + return 0; +}; + +var compareChunks = function compareChunks(chunksA, chunksB, locale) { + var lengthA = chunksA.length; + var lengthB = chunksB.length; + var size = Math.min(lengthA, lengthB); + for (var i = 0; i < size; i++) { + var chunkA = chunksA[i]; + var chunkB = chunksB[i]; + if (chunkA.normalizedString !== chunkB.normalizedString) { + if (chunkA.normalizedString === '' !== (chunkB.normalizedString === '')) { + // empty strings have lowest value + return chunkA.normalizedString === '' ? -1 : 1; + } + if (chunkA.parsedNumber !== undefined && chunkB.parsedNumber !== undefined) { + // compare numbers + var result = compareNumbers(chunkA.parsedNumber, chunkB.parsedNumber); + if (result === 0) { + // compare string value, if parsed numbers are equal + // Example: + // chunkA = { parsedNumber: 1, normalizedString: "001" } + // chunkB = { parsedNumber: 1, normalizedString: "01" } + // chunkA.parsedNumber === chunkB.parsedNumber + // chunkA.normalizedString < chunkB.normalizedString + return stringCompare(chunkA.normalizedString, chunkB.normalizedString); + } + return result; + } else if (chunkA.parsedNumber !== undefined || chunkB.parsedNumber !== undefined) { + // number < string + return chunkA.parsedNumber !== undefined ? -1 : 1; + } else if (RE_UNICODE_CHARACTERS.test(chunkA.normalizedString + chunkB.normalizedString)) { + // use locale comparison only if one of the chunks contains unicode characters + return compareUnicode(chunkA.normalizedString, chunkB.normalizedString, locale); + } else { + // use common string comparison for performance reason + return stringCompare(chunkA.normalizedString, chunkB.normalizedString); + } + } + } + // if the chunks are equal so far, the one which has more chunks is greater than the other one + if (lengthA > size || lengthB > size) { + return lengthA <= size ? -1 : 1; + } + return 0; +}; + +var compareOtherTypes = function compareOtherTypes(valueA, valueB) { + if (!valueA.chunks ? valueB.chunks : !valueB.chunks) { + return !valueA.chunks ? 1 : -1; + } + if (valueA.isNaN ? !valueB.isNaN : valueB.isNaN) { + return valueA.isNaN ? -1 : 1; + } + if (valueA.isSymbol ? !valueB.isSymbol : valueB.isSymbol) { + return valueA.isSymbol ? -1 : 1; + } + if (valueA.isObject ? !valueB.isObject : valueB.isObject) { + return valueA.isObject ? -1 : 1; + } + if (valueA.isArray ? !valueB.isArray : valueB.isArray) { + return valueA.isArray ? -1 : 1; + } + if (valueA.isFunction ? !valueB.isFunction : valueB.isFunction) { + return valueA.isFunction ? -1 : 1; + } + if (valueA.isNull ? !valueB.isNull : valueB.isNull) { + return valueA.isNull ? -1 : 1; + } + return 0; +}; + +var compareValues = function compareValues(valueA, valueB, locale) { + if (valueA.value === valueB.value) { + return 0; + } + if (valueA.parsedNumber !== undefined && valueB.parsedNumber !== undefined) { + return compareNumbers(valueA.parsedNumber, valueB.parsedNumber); + } + if (valueA.chunks && valueB.chunks) { + return compareChunks(valueA.chunks, valueB.chunks, locale); + } + return compareOtherTypes(valueA, valueB); +}; + +var normalizeAlphaChunk = function normalizeAlphaChunk(chunk) { + return chunk.replace(RE_WHITESPACES, ' ').replace(RE_LEADING_OR_TRAILING_WHITESPACES, ''); +}; + +var parseNumber = function parseNumber(value) { + if (value.length !== 0) { + var parsedNumber = Number(value.replace(/_/g, '')); + if (!Number.isNaN(parsedNumber)) { + return parsedNumber; + } + } + return undefined; +}; + +var normalizeNumericChunk = function normalizeNumericChunk(chunk, index, chunks) { + if (RE_INT_OR_FLOAT.test(chunk)) { + // don´t parse a number, if there´s a preceding decimal point + // to keep significance + // e.g. 1.0020, 1.020 + if (!RE_LEADING_ZERO.test(chunk) || index === 0 || chunks[index - 1] !== '.') { + return parseNumber(chunk) || 0; + } + } + return undefined; +}; + +var createChunkMap = function createChunkMap(chunk, index, chunks) { + return { + parsedNumber: normalizeNumericChunk(chunk, index, chunks), + normalizedString: normalizeAlphaChunk(chunk) + }; +}; + +var createChunks = function createChunks(value) { + return value.replace(RE_NUMBERS, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); +}; + +var createChunkMaps = function createChunkMaps(value) { + var chunksMaps = createChunks(value).map(createChunkMap); + return chunksMaps; +}; + +var isFunction = function isFunction(value) { + return typeof value === 'function'; +}; + +var isNaN = function isNaN(value) { + return Number.isNaN(value) || value instanceof Number && Number.isNaN(value.valueOf()); +}; + +var isNull = function isNull(value) { + return value === null; +}; + +var isObject = function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Number) && !(value instanceof String) && !(value instanceof Boolean) && !(value instanceof Date); +}; + +var isSymbol = function isSymbol(value) { + return typeof value === 'symbol'; +}; + +var isUndefined = function isUndefined(value) { + return value === undefined; +}; + +var parseDate = function parseDate(value) { + try { + var parsedDate = Date.parse(value); + if (!Number.isNaN(parsedDate)) { + if (RE_DATE.test(value)) { + return parsedDate; + } + } + return undefined; + } catch (_unused) { + return undefined; + } +}; + +var numberify = function numberify(value) { + var parsedNumber = parseNumber(value); + if (parsedNumber !== undefined) { + return parsedNumber; + } + return parseDate(value); +}; + +var stringify = function stringify(value) { + if (typeof value === 'boolean' || value instanceof Boolean) { + return Number(value).toString(); + } + if (typeof value === 'number' || value instanceof Number) { + return value.toString(); + } + if (value instanceof Date) { + return value.getTime().toString(); + } + if (typeof value === 'string' || value instanceof String) { + return value.toLowerCase().replace(RE_LEADING_OR_TRAILING_WHITESPACES, ''); + } + return ''; +}; + +var getMappedValueRecord = function getMappedValueRecord(value) { + if (typeof value === 'string' || value instanceof String || (typeof value === 'number' || value instanceof Number) && !isNaN(value) || typeof value === 'boolean' || value instanceof Boolean || value instanceof Date) { + var stringValue = stringify(value); + var parsedNumber = numberify(stringValue); + var chunks = createChunkMaps(parsedNumber ? "" + parsedNumber : stringValue); + return { + parsedNumber: parsedNumber, + chunks: chunks, + value: value + }; + } + return { + isArray: Array.isArray(value), + isFunction: isFunction(value), + isNaN: isNaN(value), + isNull: isNull(value), + isObject: isObject(value), + isSymbol: isSymbol(value), + isUndefined: isUndefined(value), + value: value + }; +}; + +var baseCompare = function baseCompare(options) { + return function (valueA, valueB) { + var a = getMappedValueRecord(valueA); + var b = getMappedValueRecord(valueB); + var result = compareValues(a, b, options.locale); + return result * (options.order === 'desc' ? -1 : 1); + }; +}; + +var isValidOrder = function isValidOrder(value) { + return typeof value === 'string' && (value === 'asc' || value === 'desc'); +}; +var getOptions = function getOptions(customOptions) { + var order = 'asc'; + var locale; // = 'en'; + if (typeof customOptions === 'string' && isValidOrder(customOptions)) { + order = customOptions; + } else if (customOptions && typeof customOptions === 'object') { + if (customOptions.order && isValidOrder(customOptions.order)) { + order = customOptions.order; + } + if (customOptions.locale && customOptions.locale.length > 0) { + locale = customOptions.locale; + } + } + return { + order: order, + locale: locale + }; +}; + +/** + * Creates a compare function that defines the natural sort order considering + * the given `options` which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + */ +function compare(options) { + var validatedOptions = getOptions(options); + return baseCompare(validatedOptions); +} + +var compareMultiple = function compareMultiple(recordA, recordB, orders, locale) { + var indexA = recordA.index, + valuesA = recordA.values; + var indexB = recordB.index, + valuesB = recordB.values; + var length = valuesA.length; + var ordersLength = orders.length; + for (var i = 0; i < length; i++) { + var order = i < ordersLength ? orders[i] : null; + if (order && typeof order === 'function') { + var result = order(valuesA[i].value, valuesB[i].value); + if (result) { + return result; + } + } else { + var _result = compareValues(valuesA[i], valuesB[i], locale); + if (_result) { + return _result * (order === 'desc' ? -1 : 1); + } + } + } + return indexA - indexB; +}; + +var createIdentifierFn = function createIdentifierFn(identifier) { + if (typeof identifier === 'function') { + // identifier is already a lookup function + return identifier; + } + return function (value) { + if (Array.isArray(value)) { + var index = Number(identifier); + if (Number.isInteger(index)) { + return value[index]; + } + } else if (value && typeof value === 'object') { + var result = Object.getOwnPropertyDescriptor(value, identifier); + return result == null ? void 0 : result.value; + } + return value; + }; +}; + +var getElementByIndex = function getElementByIndex(collection, index) { + return collection[index]; +}; + +var getValueByIdentifier = function getValueByIdentifier(value, getValue) { + return getValue(value); +}; + +var baseOrderBy = function baseOrderBy(collection, identifiers, orders, locale) { + var identifierFns = identifiers.length ? identifiers.map(createIdentifierFn) : [function (value) { + return value; + }]; + + // temporary array holds elements with position and sort-values + var mappedCollection = collection.map(function (element, index) { + var values = identifierFns.map(function (identifier) { + return getValueByIdentifier(element, identifier); + }).map(getMappedValueRecord); + return { + index: index, + values: values + }; + }); + + // iterate over values and compare values until a != b or last value reached + mappedCollection.sort(function (recordA, recordB) { + return compareMultiple(recordA, recordB, orders, locale); + }); + return mappedCollection.map(function (element) { + return getElementByIndex(collection, element.index); + }); +}; + +var getIdentifiers = function getIdentifiers(identifiers) { + if (!identifiers) { + return []; + } + var identifierList = !Array.isArray(identifiers) ? [identifiers] : [].concat(identifiers); + if (identifierList.some(function (identifier) { + return typeof identifier !== 'string' && typeof identifier !== 'number' && typeof identifier !== 'function'; + })) { + return []; + } + return identifierList; +}; + +var getOrders = function getOrders(orders) { + if (!orders) { + return []; + } + var orderList = !Array.isArray(orders) ? [orders] : [].concat(orders); + if (orderList.some(function (order) { + return order !== 'asc' && order !== 'desc' && typeof order !== 'function'; + })) { + return []; + } + return orderList; +}; + +/** + * Creates an array of elements, natural sorted by specified identifiers and + * the corresponding sort orders. This method implements a stable sort + * algorithm, which means the original sort order of equal elements is + * preserved. + */ +function orderBy(collection, identifiers, orders, locale) { + if (!collection || !Array.isArray(collection)) { + return []; + } + var validatedIdentifiers = getIdentifiers(identifiers); + var validatedOrders = getOrders(orders); + return baseOrderBy(collection, validatedIdentifiers, validatedOrders, locale); +} + +export { compare, orderBy }; diff --git a/tools/ui/node_modules/natural-orderby/dist/main.js b/tools/ui/node_modules/natural-orderby/dist/main.js new file mode 100644 index 0000000000000000000000000000000000000000..fefb98a0074baacc3950e005eb2e0c40280984e4 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/main.js @@ -0,0 +1,19 @@ +/** + * natural-orderby v5.0.0 + * + * Copyright (c) Olaf Ennen + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +'use strict'; + +/* eslint-disable n/no-missing-require */ + +if (process.env.NODE_ENV === 'production') { + module.exports = require('./umd/natural-orderby.production.min.js'); +} else { + module.exports = require('./umd/natural-orderby.development.js'); +} diff --git a/tools/ui/node_modules/natural-orderby/dist/natural-orderby.development.js b/tools/ui/node_modules/natural-orderby/dist/natural-orderby.development.js new file mode 100644 index 0000000000000000000000000000000000000000..c8f29e52db40890f5859375eb4403427f8cb2b1e --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/natural-orderby.development.js @@ -0,0 +1,381 @@ +/** + * natural-orderby v5.0.0 + * + * Copyright (c) Olaf Ennen + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +const compareNumbers = (numberA, numberB) => { + if (numberA < numberB) { + return -1; + } + if (numberA > numberB) { + return 1; + } + return 0; +}; + +const compareUnicode = (stringA, stringB, locale) => { + const result = stringA.localeCompare(stringB, locale); + return result ? result / Math.abs(result) : 0; +}; + +const RE_NUMBERS = /(^0x[\da-fA-F]+$|^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?!\.\d+)(?=\D|\s|$))|\d+)/g; +const RE_LEADING_OR_TRAILING_WHITESPACES = /^\s+|\s+$/g; // trim pre-post whitespace +const RE_WHITESPACES = /\s+/g; // normalize all whitespace to single ' ' character +const RE_INT_OR_FLOAT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; // identify integers and floats +const RE_DATE = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[/-]\d{1,4}[/-]\d{1,4}|^\w+, \w+ \d+, \d{4})/; // identify date strings +const RE_LEADING_ZERO = /^0+[1-9]{1}[0-9]*$/; +// eslint-disable-next-line no-control-regex +const RE_UNICODE_CHARACTERS = /[^\x00-\x80]/; + +const stringCompare = (stringA, stringB) => { + if (stringA < stringB) { + return -1; + } + if (stringA > stringB) { + return 1; + } + return 0; +}; + +const compareChunks = (chunksA, chunksB, locale) => { + const lengthA = chunksA.length; + const lengthB = chunksB.length; + const size = Math.min(lengthA, lengthB); + for (let i = 0; i < size; i++) { + const chunkA = chunksA[i]; + const chunkB = chunksB[i]; + if (chunkA.normalizedString !== chunkB.normalizedString) { + if (chunkA.normalizedString === '' !== (chunkB.normalizedString === '')) { + // empty strings have lowest value + return chunkA.normalizedString === '' ? -1 : 1; + } + if (chunkA.parsedNumber !== undefined && chunkB.parsedNumber !== undefined) { + // compare numbers + const result = compareNumbers(chunkA.parsedNumber, chunkB.parsedNumber); + if (result === 0) { + // compare string value, if parsed numbers are equal + // Example: + // chunkA = { parsedNumber: 1, normalizedString: "001" } + // chunkB = { parsedNumber: 1, normalizedString: "01" } + // chunkA.parsedNumber === chunkB.parsedNumber + // chunkA.normalizedString < chunkB.normalizedString + return stringCompare(chunkA.normalizedString, chunkB.normalizedString); + } + return result; + } else if (chunkA.parsedNumber !== undefined || chunkB.parsedNumber !== undefined) { + // number < string + return chunkA.parsedNumber !== undefined ? -1 : 1; + } else if (RE_UNICODE_CHARACTERS.test(chunkA.normalizedString + chunkB.normalizedString)) { + // use locale comparison only if one of the chunks contains unicode characters + return compareUnicode(chunkA.normalizedString, chunkB.normalizedString, locale); + } else { + // use common string comparison for performance reason + return stringCompare(chunkA.normalizedString, chunkB.normalizedString); + } + } + } + // if the chunks are equal so far, the one which has more chunks is greater than the other one + if (lengthA > size || lengthB > size) { + return lengthA <= size ? -1 : 1; + } + return 0; +}; + +const compareOtherTypes = (valueA, valueB) => { + if (!valueA.chunks ? valueB.chunks : !valueB.chunks) { + return !valueA.chunks ? 1 : -1; + } + if (valueA.isNaN ? !valueB.isNaN : valueB.isNaN) { + return valueA.isNaN ? -1 : 1; + } + if (valueA.isSymbol ? !valueB.isSymbol : valueB.isSymbol) { + return valueA.isSymbol ? -1 : 1; + } + if (valueA.isObject ? !valueB.isObject : valueB.isObject) { + return valueA.isObject ? -1 : 1; + } + if (valueA.isArray ? !valueB.isArray : valueB.isArray) { + return valueA.isArray ? -1 : 1; + } + if (valueA.isFunction ? !valueB.isFunction : valueB.isFunction) { + return valueA.isFunction ? -1 : 1; + } + if (valueA.isNull ? !valueB.isNull : valueB.isNull) { + return valueA.isNull ? -1 : 1; + } + return 0; +}; + +const compareValues = (valueA, valueB, locale) => { + if (valueA.value === valueB.value) { + return 0; + } + if (valueA.parsedNumber !== undefined && valueB.parsedNumber !== undefined) { + return compareNumbers(valueA.parsedNumber, valueB.parsedNumber); + } + if (valueA.chunks && valueB.chunks) { + return compareChunks(valueA.chunks, valueB.chunks, locale); + } + return compareOtherTypes(valueA, valueB); +}; + +const normalizeAlphaChunk = chunk => { + return chunk.replace(RE_WHITESPACES, ' ').replace(RE_LEADING_OR_TRAILING_WHITESPACES, ''); +}; + +const parseNumber = value => { + if (value.length !== 0) { + const parsedNumber = Number(value.replace(/_/g, '')); + if (!Number.isNaN(parsedNumber)) { + return parsedNumber; + } + } + return undefined; +}; + +const normalizeNumericChunk = (chunk, index, chunks) => { + if (RE_INT_OR_FLOAT.test(chunk)) { + // don´t parse a number, if there´s a preceding decimal point + // to keep significance + // e.g. 1.0020, 1.020 + if (!RE_LEADING_ZERO.test(chunk) || index === 0 || chunks[index - 1] !== '.') { + return parseNumber(chunk) || 0; + } + } + return undefined; +}; + +const createChunkMap = (chunk, index, chunks) => ({ + parsedNumber: normalizeNumericChunk(chunk, index, chunks), + normalizedString: normalizeAlphaChunk(chunk) +}); + +const createChunks = value => value.replace(RE_NUMBERS, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); + +const createChunkMaps = value => { + const chunksMaps = createChunks(value).map(createChunkMap); + return chunksMaps; +}; + +const isFunction = value => typeof value === 'function'; + +const isNaN = value => Number.isNaN(value) || value instanceof Number && Number.isNaN(value.valueOf()); + +const isNull = value => value === null; + +const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Number) && !(value instanceof String) && !(value instanceof Boolean) && !(value instanceof Date); + +const isSymbol = value => typeof value === 'symbol'; + +const isUndefined = value => value === undefined; + +const parseDate = value => { + try { + const parsedDate = Date.parse(value); + if (!Number.isNaN(parsedDate)) { + if (RE_DATE.test(value)) { + return parsedDate; + } + } + return undefined; + } catch { + return undefined; + } +}; + +const numberify = value => { + const parsedNumber = parseNumber(value); + if (parsedNumber !== undefined) { + return parsedNumber; + } + return parseDate(value); +}; + +const stringify = value => { + if (typeof value === 'boolean' || value instanceof Boolean) { + return Number(value).toString(); + } + if (typeof value === 'number' || value instanceof Number) { + return value.toString(); + } + if (value instanceof Date) { + return value.getTime().toString(); + } + if (typeof value === 'string' || value instanceof String) { + return value.toLowerCase().replace(RE_LEADING_OR_TRAILING_WHITESPACES, ''); + } + return ''; +}; + +const getMappedValueRecord = value => { + if (typeof value === 'string' || value instanceof String || (typeof value === 'number' || value instanceof Number) && !isNaN(value) || typeof value === 'boolean' || value instanceof Boolean || value instanceof Date) { + const stringValue = stringify(value); + const parsedNumber = numberify(stringValue); + const chunks = createChunkMaps(parsedNumber ? `${parsedNumber}` : stringValue); + return { + parsedNumber, + chunks, + value + }; + } + return { + isArray: Array.isArray(value), + isFunction: isFunction(value), + isNaN: isNaN(value), + isNull: isNull(value), + isObject: isObject(value), + isSymbol: isSymbol(value), + isUndefined: isUndefined(value), + value + }; +}; + +const baseCompare = options => (valueA, valueB) => { + const a = getMappedValueRecord(valueA); + const b = getMappedValueRecord(valueB); + const result = compareValues(a, b, options.locale); + return result * (options.order === 'desc' ? -1 : 1); +}; + +const isValidOrder = value => typeof value === 'string' && (value === 'asc' || value === 'desc'); +const getOptions = customOptions => { + let order = 'asc'; + let locale; // = 'en'; + if (typeof customOptions === 'string' && isValidOrder(customOptions)) { + order = customOptions; + } else if (customOptions && typeof customOptions === 'object') { + if (customOptions.order && isValidOrder(customOptions.order)) { + order = customOptions.order; + } + if (customOptions.locale && customOptions.locale.length > 0) { + locale = customOptions.locale; + } + } + return { + order, + locale + }; +}; + +/** + * Creates a compare function that defines the natural sort order considering + * the given `options` which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + */ +function compare(options) { + const validatedOptions = getOptions(options); + return baseCompare(validatedOptions); +} + +const compareMultiple = (recordA, recordB, orders, locale) => { + const { + index: indexA, + values: valuesA + } = recordA; + const { + index: indexB, + values: valuesB + } = recordB; + const { + length + } = valuesA; + const ordersLength = orders.length; + for (let i = 0; i < length; i++) { + const order = i < ordersLength ? orders[i] : null; + if (order && typeof order === 'function') { + const result = order(valuesA[i].value, valuesB[i].value); + if (result) { + return result; + } + } else { + const result = compareValues(valuesA[i], valuesB[i], locale); + if (result) { + return result * (order === 'desc' ? -1 : 1); + } + } + } + return indexA - indexB; +}; + +const createIdentifierFn = identifier => { + if (typeof identifier === 'function') { + // identifier is already a lookup function + return identifier; + } + return value => { + if (Array.isArray(value)) { + const index = Number(identifier); + if (Number.isInteger(index)) { + return value[index]; + } + } else if (value && typeof value === 'object') { + const result = Object.getOwnPropertyDescriptor(value, identifier); + return result?.value; + } + return value; + }; +}; + +const getElementByIndex = (collection, index) => collection[index]; + +const getValueByIdentifier = (value, getValue) => getValue(value); + +const baseOrderBy = (collection, identifiers, orders, locale) => { + const identifierFns = identifiers.length ? identifiers.map(createIdentifierFn) : [value => value]; + + // temporary array holds elements with position and sort-values + const mappedCollection = collection.map((element, index) => { + const values = identifierFns.map(identifier => getValueByIdentifier(element, identifier)).map(getMappedValueRecord); + return { + index, + values + }; + }); + + // iterate over values and compare values until a != b or last value reached + mappedCollection.sort((recordA, recordB) => compareMultiple(recordA, recordB, orders, locale)); + return mappedCollection.map(element => getElementByIndex(collection, element.index)); +}; + +const getIdentifiers = identifiers => { + if (!identifiers) { + return []; + } + const identifierList = !Array.isArray(identifiers) ? [identifiers] : [...identifiers]; + if (identifierList.some(identifier => typeof identifier !== 'string' && typeof identifier !== 'number' && typeof identifier !== 'function')) { + return []; + } + return identifierList; +}; + +const getOrders = orders => { + if (!orders) { + return []; + } + const orderList = !Array.isArray(orders) ? [orders] : [...orders]; + if (orderList.some(order => order !== 'asc' && order !== 'desc' && typeof order !== 'function')) { + return []; + } + return orderList; +}; + +/** + * Creates an array of elements, natural sorted by specified identifiers and + * the corresponding sort orders. This method implements a stable sort + * algorithm, which means the original sort order of equal elements is + * preserved. + */ +function orderBy(collection, identifiers, orders, locale) { + if (!collection || !Array.isArray(collection)) { + return []; + } + const validatedIdentifiers = getIdentifiers(identifiers); + const validatedOrders = getOrders(orders); + return baseOrderBy(collection, validatedIdentifiers, validatedOrders, locale); +} + +export { compare, orderBy }; diff --git a/tools/ui/node_modules/natural-orderby/dist/natural-orderby.production.min.js b/tools/ui/node_modules/natural-orderby/dist/natural-orderby.production.min.js new file mode 100644 index 0000000000000000000000000000000000000000..8026f3a676292a5622ae9c7bd9c23c8c59a0d9a4 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/natural-orderby.production.min.js @@ -0,0 +1,11 @@ +/** + * natural-orderby v5.0.0 + * + * Copyright (c) Olaf Ennen + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +const e=(e,r)=>er?1:0,r=(e,r,n)=>{const t=e.localeCompare(r,n);return t?t/Math.abs(t):0},n=/(^0x[\da-fA-F]+$|^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?!\.\d+)(?=\D|\s|$))|\d+)/g,t=/^\s+|\s+$/g,i=/\s+/g,o=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,s=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[/-]\d{1,4}[/-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,a=/^0+[1-9]{1}[0-9]*$/,u=/[^\x00-\x80]/,c=(e,r)=>er?1:0,l=(n,t,i)=>n.value===t.value?0:void 0!==n.parsedNumber&&void 0!==t.parsedNumber?e(n.parsedNumber,t.parsedNumber):n.chunks&&t.chunks?((n,t,i)=>{const o=n.length,s=t.length,a=Math.min(o,s);for(let l=0;la||s>a?o<=a?-1:1:0})(n.chunks,t.chunks,i):((e,r)=>(e.chunks?!r.chunks:r.chunks)?e.chunks?-1:1:(e.isNaN?!r.isNaN:r.isNaN)?e.isNaN?-1:1:(e.isSymbol?!r.isSymbol:r.isSymbol)?e.isSymbol?-1:1:(e.isObject?!r.isObject:r.isObject)?e.isObject?-1:1:(e.isArray?!r.isArray:r.isArray)?e.isArray?-1:1:(e.isFunction?!r.isFunction:r.isFunction)?e.isFunction?-1:1:(e.isNull?!r.isNull:r.isNull)?e.isNull?-1:1:0)(n,t),d=e=>e.replace(i," ").replace(t,""),f=e=>{if(0!==e.length){const r=Number(e.replace(/_/g,""));if(!Number.isNaN(r))return r}},m=(e,r,n)=>{if(o.test(e)&&(!a.test(e)||0===r||"."!==n[r-1]))return f(e)||0},p=(e,r,n)=>({parsedNumber:m(e,r,n),normalizedString:d(e)}),N=e=>{const r=(e=>e.replace(n,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"))(e).map(p);return r},b=e=>"function"==typeof e,y=e=>Number.isNaN(e)||e instanceof Number&&Number.isNaN(e.valueOf()),g=e=>null===e,S=e=>!(null===e||"object"!=typeof e||Array.isArray(e)||e instanceof Number||e instanceof String||e instanceof Boolean||e instanceof Date),v=e=>"symbol"==typeof e,h=e=>void 0===e,A=e=>{const r=f(e);return void 0!==r?r:(e=>{try{const r=Date.parse(e);return!Number.isNaN(r)&&s.test(e)?r:void 0}catch{return}})(e)},z=e=>{if("string"==typeof e||e instanceof String||("number"==typeof e||e instanceof Number)&&!y(e)||"boolean"==typeof e||e instanceof Boolean||e instanceof Date){const r=(e=>"boolean"==typeof e||e instanceof Boolean?Number(e).toString():"number"==typeof e||e instanceof Number?e.toString():e instanceof Date?e.getTime().toString():"string"==typeof e||e instanceof String?e.toLowerCase().replace(t,""):"")(e),n=A(r);return{parsedNumber:n,chunks:N(n?`${n}`:r),value:e}}return{isArray:Array.isArray(e),isFunction:b(e),isNaN:y(e),isNull:g(e),isObject:S(e),isSymbol:v(e),isUndefined:h(e),value:e}},j=e=>"string"==typeof e&&("asc"===e||"desc"===e);function k(e){return(e=>(r,n)=>{const t=z(r),i=z(n);return l(t,i,e.locale)*("desc"===e.order?-1:1)})((e=>{let r,n="asc";return"string"==typeof e&&j(e)?n=e:e&&"object"==typeof e&&(e.order&&j(e.order)&&(n=e.order),e.locale&&e.locale.length>0&&(r=e.locale)),{order:n,locale:r}})(e))}const w=e=>"function"==typeof e?e:r=>{if(Array.isArray(r)){const n=Number(e);if(Number.isInteger(n))return r[n]}else if(r&&"object"==typeof r){const n=Object.getOwnPropertyDescriptor(r,e);return n?.value}return r},x=(e,r,n,t)=>{const i=r.length?r.map(w):[e=>e],o=e.map(((e,r)=>({index:r,values:i.map((r=>r(e))).map(z)})));return o.sort(((e,r)=>((e,r,n,t)=>{const{index:i,values:o}=e,{index:s,values:a}=r,{length:u}=o,c=n.length;for(let d=0;d((e,r)=>e[r])(e,r.index)))};function O(e,r,n,t){if(!e||!Array.isArray(e))return[];const i=(e=>{if(!e)return[];const r=Array.isArray(e)?[...e]:[e];return r.some((e=>"string"!=typeof e&&"number"!=typeof e&&"function"!=typeof e))?[]:r})(r),o=(e=>{if(!e)return[];const r=Array.isArray(e)?[...e]:[e];return r.some((e=>"asc"!==e&&"desc"!==e&&"function"!=typeof e))?[]:r})(n);return x(e,i,o,t)}export{k as compare,O as orderBy}; diff --git a/tools/ui/node_modules/natural-orderby/dist/umd/natural-orderby.development.js b/tools/ui/node_modules/natural-orderby/dist/umd/natural-orderby.development.js new file mode 100644 index 0000000000000000000000000000000000000000..1df4a741b846ad03e44968e1a7d50a33acab0667 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/umd/natural-orderby.development.js @@ -0,0 +1,420 @@ +/** + * natural-orderby v5.0.0 + * + * Copyright (c) Olaf Ennen + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.naturalOrderBy = {})); +})(this, (function (exports) { 'use strict'; + + var compareNumbers = function compareNumbers(numberA, numberB) { + if (numberA < numberB) { + return -1; + } + if (numberA > numberB) { + return 1; + } + return 0; + }; + + var compareUnicode = function compareUnicode(stringA, stringB, locale) { + var result = stringA.localeCompare(stringB, locale); + return result ? result / Math.abs(result) : 0; + }; + + var RE_NUMBERS = /(^0x[\da-fA-F]+$|^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?!\.\d+)(?=\D|\s|$))|\d+)/g; + var RE_LEADING_OR_TRAILING_WHITESPACES = /^\s+|\s+$/g; // trim pre-post whitespace + var RE_WHITESPACES = /\s+/g; // normalize all whitespace to single ' ' character + var RE_INT_OR_FLOAT = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; // identify integers and floats + var RE_DATE = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[/-]\d{1,4}[/-]\d{1,4}|^\w+, \w+ \d+, \d{4})/; // identify date strings + var RE_LEADING_ZERO = /^0+[1-9]{1}[0-9]*$/; + // eslint-disable-next-line no-control-regex + var RE_UNICODE_CHARACTERS = /[^\x00-\x80]/; + + var stringCompare = function stringCompare(stringA, stringB) { + if (stringA < stringB) { + return -1; + } + if (stringA > stringB) { + return 1; + } + return 0; + }; + + var compareChunks = function compareChunks(chunksA, chunksB, locale) { + var lengthA = chunksA.length; + var lengthB = chunksB.length; + var size = Math.min(lengthA, lengthB); + for (var i = 0; i < size; i++) { + var chunkA = chunksA[i]; + var chunkB = chunksB[i]; + if (chunkA.normalizedString !== chunkB.normalizedString) { + if (chunkA.normalizedString === '' !== (chunkB.normalizedString === '')) { + // empty strings have lowest value + return chunkA.normalizedString === '' ? -1 : 1; + } + if (chunkA.parsedNumber !== undefined && chunkB.parsedNumber !== undefined) { + // compare numbers + var result = compareNumbers(chunkA.parsedNumber, chunkB.parsedNumber); + if (result === 0) { + // compare string value, if parsed numbers are equal + // Example: + // chunkA = { parsedNumber: 1, normalizedString: "001" } + // chunkB = { parsedNumber: 1, normalizedString: "01" } + // chunkA.parsedNumber === chunkB.parsedNumber + // chunkA.normalizedString < chunkB.normalizedString + return stringCompare(chunkA.normalizedString, chunkB.normalizedString); + } + return result; + } else if (chunkA.parsedNumber !== undefined || chunkB.parsedNumber !== undefined) { + // number < string + return chunkA.parsedNumber !== undefined ? -1 : 1; + } else if (RE_UNICODE_CHARACTERS.test(chunkA.normalizedString + chunkB.normalizedString)) { + // use locale comparison only if one of the chunks contains unicode characters + return compareUnicode(chunkA.normalizedString, chunkB.normalizedString, locale); + } else { + // use common string comparison for performance reason + return stringCompare(chunkA.normalizedString, chunkB.normalizedString); + } + } + } + // if the chunks are equal so far, the one which has more chunks is greater than the other one + if (lengthA > size || lengthB > size) { + return lengthA <= size ? -1 : 1; + } + return 0; + }; + + var compareOtherTypes = function compareOtherTypes(valueA, valueB) { + if (!valueA.chunks ? valueB.chunks : !valueB.chunks) { + return !valueA.chunks ? 1 : -1; + } + if (valueA.isNaN ? !valueB.isNaN : valueB.isNaN) { + return valueA.isNaN ? -1 : 1; + } + if (valueA.isSymbol ? !valueB.isSymbol : valueB.isSymbol) { + return valueA.isSymbol ? -1 : 1; + } + if (valueA.isObject ? !valueB.isObject : valueB.isObject) { + return valueA.isObject ? -1 : 1; + } + if (valueA.isArray ? !valueB.isArray : valueB.isArray) { + return valueA.isArray ? -1 : 1; + } + if (valueA.isFunction ? !valueB.isFunction : valueB.isFunction) { + return valueA.isFunction ? -1 : 1; + } + if (valueA.isNull ? !valueB.isNull : valueB.isNull) { + return valueA.isNull ? -1 : 1; + } + return 0; + }; + + var compareValues = function compareValues(valueA, valueB, locale) { + if (valueA.value === valueB.value) { + return 0; + } + if (valueA.parsedNumber !== undefined && valueB.parsedNumber !== undefined) { + return compareNumbers(valueA.parsedNumber, valueB.parsedNumber); + } + if (valueA.chunks && valueB.chunks) { + return compareChunks(valueA.chunks, valueB.chunks, locale); + } + return compareOtherTypes(valueA, valueB); + }; + + var normalizeAlphaChunk = function normalizeAlphaChunk(chunk) { + return chunk.replace(RE_WHITESPACES, ' ').replace(RE_LEADING_OR_TRAILING_WHITESPACES, ''); + }; + + var parseNumber = function parseNumber(value) { + if (value.length !== 0) { + var parsedNumber = Number(value.replace(/_/g, '')); + if (!Number.isNaN(parsedNumber)) { + return parsedNumber; + } + } + return undefined; + }; + + var normalizeNumericChunk = function normalizeNumericChunk(chunk, index, chunks) { + if (RE_INT_OR_FLOAT.test(chunk)) { + // don´t parse a number, if there´s a preceding decimal point + // to keep significance + // e.g. 1.0020, 1.020 + if (!RE_LEADING_ZERO.test(chunk) || index === 0 || chunks[index - 1] !== '.') { + return parseNumber(chunk) || 0; + } + } + return undefined; + }; + + var createChunkMap = function createChunkMap(chunk, index, chunks) { + return { + parsedNumber: normalizeNumericChunk(chunk, index, chunks), + normalizedString: normalizeAlphaChunk(chunk) + }; + }; + + var createChunks = function createChunks(value) { + return value.replace(RE_NUMBERS, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'); + }; + + var createChunkMaps = function createChunkMaps(value) { + var chunksMaps = createChunks(value).map(createChunkMap); + return chunksMaps; + }; + + var isFunction = function isFunction(value) { + return typeof value === 'function'; + }; + + var isNaN = function isNaN(value) { + return Number.isNaN(value) || value instanceof Number && Number.isNaN(value.valueOf()); + }; + + var isNull = function isNull(value) { + return value === null; + }; + + var isObject = function isObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Number) && !(value instanceof String) && !(value instanceof Boolean) && !(value instanceof Date); + }; + + var isSymbol = function isSymbol(value) { + return typeof value === 'symbol'; + }; + + var isUndefined = function isUndefined(value) { + return value === undefined; + }; + + var parseDate = function parseDate(value) { + try { + var parsedDate = Date.parse(value); + if (!Number.isNaN(parsedDate)) { + if (RE_DATE.test(value)) { + return parsedDate; + } + } + return undefined; + } catch (_unused) { + return undefined; + } + }; + + var numberify = function numberify(value) { + var parsedNumber = parseNumber(value); + if (parsedNumber !== undefined) { + return parsedNumber; + } + return parseDate(value); + }; + + var stringify = function stringify(value) { + if (typeof value === 'boolean' || value instanceof Boolean) { + return Number(value).toString(); + } + if (typeof value === 'number' || value instanceof Number) { + return value.toString(); + } + if (value instanceof Date) { + return value.getTime().toString(); + } + if (typeof value === 'string' || value instanceof String) { + return value.toLowerCase().replace(RE_LEADING_OR_TRAILING_WHITESPACES, ''); + } + return ''; + }; + + var getMappedValueRecord = function getMappedValueRecord(value) { + if (typeof value === 'string' || value instanceof String || (typeof value === 'number' || value instanceof Number) && !isNaN(value) || typeof value === 'boolean' || value instanceof Boolean || value instanceof Date) { + var stringValue = stringify(value); + var parsedNumber = numberify(stringValue); + var chunks = createChunkMaps(parsedNumber ? "" + parsedNumber : stringValue); + return { + parsedNumber: parsedNumber, + chunks: chunks, + value: value + }; + } + return { + isArray: Array.isArray(value), + isFunction: isFunction(value), + isNaN: isNaN(value), + isNull: isNull(value), + isObject: isObject(value), + isSymbol: isSymbol(value), + isUndefined: isUndefined(value), + value: value + }; + }; + + var baseCompare = function baseCompare(options) { + return function (valueA, valueB) { + var a = getMappedValueRecord(valueA); + var b = getMappedValueRecord(valueB); + var result = compareValues(a, b, options.locale); + return result * (options.order === 'desc' ? -1 : 1); + }; + }; + + var isValidOrder = function isValidOrder(value) { + return typeof value === 'string' && (value === 'asc' || value === 'desc'); + }; + var getOptions = function getOptions(customOptions) { + var order = 'asc'; + var locale; // = 'en'; + if (typeof customOptions === 'string' && isValidOrder(customOptions)) { + order = customOptions; + } else if (customOptions && typeof customOptions === 'object') { + if (customOptions.order && isValidOrder(customOptions.order)) { + order = customOptions.order; + } + if (customOptions.locale && customOptions.locale.length > 0) { + locale = customOptions.locale; + } + } + return { + order: order, + locale: locale + }; + }; + + /** + * Creates a compare function that defines the natural sort order considering + * the given `options` which may be passed to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). + */ + function compare(options) { + var validatedOptions = getOptions(options); + return baseCompare(validatedOptions); + } + + var compareMultiple = function compareMultiple(recordA, recordB, orders, locale) { + var indexA = recordA.index, + valuesA = recordA.values; + var indexB = recordB.index, + valuesB = recordB.values; + var length = valuesA.length; + var ordersLength = orders.length; + for (var i = 0; i < length; i++) { + var order = i < ordersLength ? orders[i] : null; + if (order && typeof order === 'function') { + var result = order(valuesA[i].value, valuesB[i].value); + if (result) { + return result; + } + } else { + var _result = compareValues(valuesA[i], valuesB[i], locale); + if (_result) { + return _result * (order === 'desc' ? -1 : 1); + } + } + } + return indexA - indexB; + }; + + var createIdentifierFn = function createIdentifierFn(identifier) { + if (typeof identifier === 'function') { + // identifier is already a lookup function + return identifier; + } + return function (value) { + if (Array.isArray(value)) { + var index = Number(identifier); + if (Number.isInteger(index)) { + return value[index]; + } + } else if (value && typeof value === 'object') { + var result = Object.getOwnPropertyDescriptor(value, identifier); + return result == null ? void 0 : result.value; + } + return value; + }; + }; + + var getElementByIndex = function getElementByIndex(collection, index) { + return collection[index]; + }; + + var getValueByIdentifier = function getValueByIdentifier(value, getValue) { + return getValue(value); + }; + + var baseOrderBy = function baseOrderBy(collection, identifiers, orders, locale) { + var identifierFns = identifiers.length ? identifiers.map(createIdentifierFn) : [function (value) { + return value; + }]; + + // temporary array holds elements with position and sort-values + var mappedCollection = collection.map(function (element, index) { + var values = identifierFns.map(function (identifier) { + return getValueByIdentifier(element, identifier); + }).map(getMappedValueRecord); + return { + index: index, + values: values + }; + }); + + // iterate over values and compare values until a != b or last value reached + mappedCollection.sort(function (recordA, recordB) { + return compareMultiple(recordA, recordB, orders, locale); + }); + return mappedCollection.map(function (element) { + return getElementByIndex(collection, element.index); + }); + }; + + var getIdentifiers = function getIdentifiers(identifiers) { + if (!identifiers) { + return []; + } + var identifierList = !Array.isArray(identifiers) ? [identifiers] : [].concat(identifiers); + if (identifierList.some(function (identifier) { + return typeof identifier !== 'string' && typeof identifier !== 'number' && typeof identifier !== 'function'; + })) { + return []; + } + return identifierList; + }; + + var getOrders = function getOrders(orders) { + if (!orders) { + return []; + } + var orderList = !Array.isArray(orders) ? [orders] : [].concat(orders); + if (orderList.some(function (order) { + return order !== 'asc' && order !== 'desc' && typeof order !== 'function'; + })) { + return []; + } + return orderList; + }; + + /** + * Creates an array of elements, natural sorted by specified identifiers and + * the corresponding sort orders. This method implements a stable sort + * algorithm, which means the original sort order of equal elements is + * preserved. + */ + function orderBy(collection, identifiers, orders, locale) { + if (!collection || !Array.isArray(collection)) { + return []; + } + var validatedIdentifiers = getIdentifiers(identifiers); + var validatedOrders = getOrders(orders); + return baseOrderBy(collection, validatedIdentifiers, validatedOrders, locale); + } + + exports.compare = compare; + exports.orderBy = orderBy; + +})); diff --git a/tools/ui/node_modules/natural-orderby/dist/umd/natural-orderby.production.min.js b/tools/ui/node_modules/natural-orderby/dist/umd/natural-orderby.production.min.js new file mode 100644 index 0000000000000000000000000000000000000000..a02901dd1bc4508f348536118f3cb6fac0b4e31c --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/dist/umd/natural-orderby.production.min.js @@ -0,0 +1,11 @@ +/** + * natural-orderby v5.0.0 + * + * Copyright (c) Olaf Ennen + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */ +!function(r,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((r="undefined"!=typeof globalThis?globalThis:r||self).naturalOrderBy={})}(this,(function(r){"use strict";var n=function(r,n){return rn?1:0},e=function(r,n,e){var t=r.localeCompare(n,e);return t?t/Math.abs(t):0},t=/(^0x[\da-fA-F]+$|^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?!\.\d+)(?=\D|\s|$))|\d+)/g,i=/^\s+|\s+$/g,o=/\s+/g,u=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/,a=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[/-]\d{1,4}[/-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,s=/^0+[1-9]{1}[0-9]*$/,c=/[^\x00-\x80]/,f=function(r,n){return rn?1:0},l=function(r,t,i){return r.value===t.value?0:void 0!==r.parsedNumber&&void 0!==t.parsedNumber?n(r.parsedNumber,t.parsedNumber):r.chunks&&t.chunks?function(r,t,i){for(var o=r.length,u=t.length,a=Math.min(o,u),s=0;sa||u>a?o<=a?-1:1:0}(r.chunks,t.chunks,i):function(r,n){return(r.chunks?!n.chunks:n.chunks)?r.chunks?-1:1:(r.isNaN?!n.isNaN:n.isNaN)?r.isNaN?-1:1:(r.isSymbol?!n.isSymbol:n.isSymbol)?r.isSymbol?-1:1:(r.isObject?!n.isObject:n.isObject)?r.isObject?-1:1:(r.isArray?!n.isArray:n.isArray)?r.isArray?-1:1:(r.isFunction?!n.isFunction:n.isFunction)?r.isFunction?-1:1:(r.isNull?!n.isNull:n.isNull)?r.isNull?-1:1:0}(r,t)},d=function(r){return r.replace(o," ").replace(i,"")},m=function(r){if(0!==r.length){var n=Number(r.replace(/_/g,""));if(!Number.isNaN(n))return n}},p=function(r,n,e){if(u.test(r)&&(!s.test(r)||0===n||"."!==e[n-1]))return m(r)||0},y=function(r,n,e){return{parsedNumber:p(r,n,e),normalizedString:d(r)}},b=function(r){var n=function(r){return r.replace(t,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0")}(r).map(y);return n},N=function(r){return"function"==typeof r},v=function(r){return Number.isNaN(r)||r instanceof Number&&Number.isNaN(r.valueOf())},g=function(r){return null===r},S=function(r){return!(null===r||"object"!=typeof r||Array.isArray(r)||r instanceof Number||r instanceof String||r instanceof Boolean||r instanceof Date)},h=function(r){return"symbol"==typeof r},A=function(r){return void 0===r},z=function(r){var n=m(r);return void 0!==n?n:function(r){try{var n=Date.parse(r);return!Number.isNaN(n)&&a.test(r)?n:void 0}catch(r){return}}(r)},j=function(r){if("string"==typeof r||r instanceof String||("number"==typeof r||r instanceof Number)&&!v(r)||"boolean"==typeof r||r instanceof Boolean||r instanceof Date){var n=function(r){return"boolean"==typeof r||r instanceof Boolean?Number(r).toString():"number"==typeof r||r instanceof Number?r.toString():r instanceof Date?r.getTime().toString():"string"==typeof r||r instanceof String?r.toLowerCase().replace(i,""):""}(r),e=z(n);return{parsedNumber:e,chunks:b(e?""+e:n),value:r}}return{isArray:Array.isArray(r),isFunction:N(r),isNaN:v(r),isNull:g(r),isObject:S(r),isSymbol:h(r),isUndefined:A(r),value:r}},x=function(r){return"string"==typeof r&&("asc"===r||"desc"===r)};var k=function(r){return"function"==typeof r?r:function(n){if(Array.isArray(n)){var e=Number(r);if(Number.isInteger(e))return n[e]}else if(n&&"object"==typeof n){var t=Object.getOwnPropertyDescriptor(n,r);return null==t?void 0:t.value}return n}},w=function(r,n,e,t){var i=n.length?n.map(k):[function(r){return r}],o=r.map((function(r,n){return{index:n,values:i.map((function(n){return n(r)})).map(j)}}));return o.sort((function(r,n){return function(r,n,e,t){for(var i=r.index,o=r.values,u=n.index,a=n.values,s=o.length,c=e.length,f=0;f0&&(e=n.locale)),{order:t,locale:e}))},r.orderBy=function(r,n,e,t){if(!r||!Array.isArray(r))return[];var i=function(r){if(!r)return[];var n=Array.isArray(r)?[].concat(r):[r];return n.some((function(r){return"string"!=typeof r&&"number"!=typeof r&&"function"!=typeof r}))?[]:n}(n),o=function(r){if(!r)return[];var n=Array.isArray(r)?[].concat(r):[r];return n.some((function(r){return"asc"!==r&&"desc"!==r&&"function"!=typeof r}))?[]:n}(e);return w(r,i,o,t)}})); diff --git a/tools/ui/node_modules/natural-orderby/package.json b/tools/ui/node_modules/natural-orderby/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e84c798afe5d31e26011c164d7d360b9ae39e158 --- /dev/null +++ b/tools/ui/node_modules/natural-orderby/package.json @@ -0,0 +1,119 @@ +{ + "name": "natural-orderby", + "version": "5.0.0", + "description": "Lightweight and performant natural sorting of arrays and collections by differentiating between unicode characters, numbers, dates, etc.", + "sideEffects": false, + "main": "./dist/main.js", + "types": "./dist/index.d.ts", + "module": "./dist/index.js", + "repository": { + "type": "git", + "url": "https://github.com/yobacca/natural-orderby.git" + }, + "scripts": { + "build": "tsc && rollup -c", + "clean": "git clean -fdX .", + "docs": "docsify serve docs", + "format": "prettier --ignore-path .eslintignore --write src", + "lint": "eslint src", + "test": "cross-env TZ=UTC jest src", + "typecheck": "tsc --noEmit --emitDeclarationOnly false", + "size": "filesize", + "prepublishOnly": "yarn build", + "prepare": "husky" + }, + "files": [ + "dist/", + "LICENSE.md", + "CHANGELOG.md", + "README.md" + ], + "keywords": [ + "sort", + "order", + "string", + "natsort", + "natcmp", + "compare", + "alphanum", + "unicode", + "date", + "number", + "float", + "numeric", + "natural", + "human", + "javascript", + "array", + "collection", + "list", + "sorting", + "case sensitive", + "case insensitive", + "ascending", + "descending", + "browser", + "node.js", + "node" + ], + "author": "Olaf Ennen ", + "license": "MIT", + "bugs": { + "url": "https://github.com/yobacca/natural-orderby/issues" + }, + "homepage": "https://yobacca.github.io/natural-orderby", + "dependencies": {}, + "devDependencies": { + "@ampproject/filesize": "^4.3.0", + "@babel/core": "^7.18.2", + "@babel/preset-env": "^7.18.2", + "@babel/preset-modules": "^0.1.5", + "@babel/preset-typescript": "^7.17.12", + "@changesets/cli": "^2.25.2", + "@commitlint/cli": "^19.4.0", + "@commitlint/config-conventional": "^19.2.2", + "@commitlint/types": "^19.0.3", + "@rollup/plugin-babel": "^6.0.0", + "@rollup/plugin-node-resolve": "^15.0.1", + "@rollup/plugin-terser": "^0.4.4", + "@types/jest": "29.5.13", + "@typescript-eslint/eslint-plugin": "^7.18.0", + "@typescript-eslint/parser": "^7.18.0", + "cross-env": "^7.0.3", + "docsify-cli": "^4.3.0", + "eslint": "^8.56.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-import": "^2.29.1", + "eslint-plugin-jest": "^28.8.0", + "eslint-plugin-n": "^17.10.2", + "eslint-plugin-prettier": "^5.2.1", + "husky": "^9.1.5", + "jest": "^29.3.1", + "lint-staged": "^15.2.9", + "prettier": "^3.3.3", + "rollup": "^4.21.1", + "rollup-plugin-delete": "^2.0.0", + "rollup-plugin-dts": "^6.1.1", + "ts-jest": "^29.0.3", + "typescript": "^5.5.4" + }, + "lint-staged": { + "*.{ts,md,json}": [ + "prettier --write" + ], + "*.{ts,json}": [ + "eslint --rule \"@typescript-eslint/no-unused-vars: error\"" + ] + }, + "engines": { + "node": ">=18" + }, + "filesize": { + "./dist/umd/natural-orderby.production.min.js": { + "none": "5.5 kB" + }, + "./dist/natural-orderby.production.min.js": { + "none": "4.6 kB" + } + } +} diff --git a/tools/ui/node_modules/negotiator/HISTORY.md b/tools/ui/node_modules/negotiator/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..63d537d3f681143b17f9250b199a865297b020be --- /dev/null +++ b/tools/ui/node_modules/negotiator/HISTORY.md @@ -0,0 +1,114 @@ +1.0.0 / 2024-08-31 +================== + + * Drop support for node <18 + * Added an option preferred encodings array #59 + +0.6.3 / 2022-01-22 +================== + + * Revert "Lazy-load modules from main entry point" + +0.6.2 / 2019-04-29 +================== + + * Fix sorting charset, encoding, and language with extra parameters + +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/tools/ui/node_modules/negotiator/LICENSE b/tools/ui/node_modules/negotiator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea6b9e2e9ac251526c95df2dd995cf5f1e861854 --- /dev/null +++ b/tools/ui/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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. diff --git a/tools/ui/node_modules/negotiator/README.md b/tools/ui/node_modules/negotiator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6fb7f2db31e670a487e3aa21a99fdc9c3978e6be --- /dev/null +++ b/tools/ui/node_modules/negotiator/README.md @@ -0,0 +1,212 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][github-actions-ci-image]][github-actions-ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encoding(availableEncodings, { preferred }) + +Returns the most preferred encoding from a list of available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +##### encodings(availableEncodings, { preferred }) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings, while prioritizing based on `preferred` array between same-quality encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator +[github-actions-ci-image]: https://img.shields.io/github/workflow/status/jshttp/negotiator/ci/master?label=ci +[github-actions-ci-url]: https://github.com/jshttp/negotiator/actions/workflows/ci.yml diff --git a/tools/ui/node_modules/negotiator/index.js b/tools/ui/node_modules/negotiator/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4f51315d6af4bda48533904adf1c530d1ac95a4a --- /dev/null +++ b/tools/ui/node_modules/negotiator/index.js @@ -0,0 +1,83 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +var preferredCharsets = require('./lib/charset') +var preferredEncodings = require('./lib/encoding') +var preferredLanguages = require('./lib/language') +var preferredMediaTypes = require('./lib/mediaType') + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available, opts) { + var set = this.encodings(available, opts); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available, options) { + var opts = options || {}; + return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; diff --git a/tools/ui/node_modules/negotiator/lib/charset.js b/tools/ui/node_modules/negotiator/lib/charset.js new file mode 100644 index 0000000000000000000000000000000000000000..cdd014803474a4b76b981c475a32ebcaa81a36e5 --- /dev/null +++ b/tools/ui/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/tools/ui/node_modules/negotiator/lib/encoding.js b/tools/ui/node_modules/negotiator/lib/encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..9ebb633d67743316863baf3504bfe1d47d53b033 --- /dev/null +++ b/tools/ui/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,205 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {encoding: encoding, o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + encoding: encoding, + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided, preferred) { + var accepts = parseAcceptEncoding(accept || ''); + + var comparator = preferred ? function comparator (a, b) { + if (a.q !== b.q) { + return b.q - a.q // higher quality first + } + + var aPreferred = preferred.indexOf(a.encoding) + var bPreferred = preferred.indexOf(b.encoding) + + if (aPreferred === -1 && bPreferred === -1) { + // consider the original specifity/order + return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) + } + + if (aPreferred !== -1 && bPreferred !== -1) { + return aPreferred - bPreferred // consider the preferred order + } + + return aPreferred === -1 ? 1 : -1 // preferred first + } : compareSpecs; + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(comparator) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/tools/ui/node_modules/negotiator/lib/language.js b/tools/ui/node_modules/negotiator/lib/language.js new file mode 100644 index 0000000000000000000000000000000000000000..a23167252719be841ad570eb655a703a4ae8fe9e --- /dev/null +++ b/tools/ui/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1] + var suffix = match[2] + var full = prefix + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/tools/ui/node_modules/negotiator/lib/mediaType.js b/tools/ui/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 0000000000000000000000000000000000000000..8e402ea88394c040bf5964f65b8eba33b50bd4a1 --- /dev/null +++ b/tools/ui/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.slice(1, -1) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.slice(0, index); + val = str.slice(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/tools/ui/node_modules/negotiator/package.json b/tools/ui/node_modules/negotiator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e4bdc1ef4f74812bfc15dbd980eab1f57282b753 --- /dev/null +++ b/tools/ui/node_modules/negotiator/package.json @@ -0,0 +1,43 @@ +{ + "name": "negotiator", + "description": "HTTP content negotiation", + "version": "1.0.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Federico Romero ", + "Isaac Z. Schlueter (http://blog.izs.me/)" + ], + "license": "MIT", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "repository": "jshttp/negotiator", + "devDependencies": { + "eslint": "7.32.0", + "eslint-plugin-markdown": "2.2.1", + "mocha": "9.1.3", + "nyc": "15.1.0" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test:debug": "mocha --reporter spec --check-leaks --inspect --inspect-brk test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/tools/ui/node_modules/node-addon-api/LICENSE.md b/tools/ui/node_modules/node-addon-api/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..819d91a5bd799be3e9444acc9dd1ebe6ee5de529 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2017 [Node.js API collaborators](https://github.com/nodejs/node-addon-api#collaborators) + +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. diff --git a/tools/ui/node_modules/node-addon-api/README.md b/tools/ui/node_modules/node-addon-api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e90eb7c9927c962a2bf8b73ac2697c0de5868921 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/README.md @@ -0,0 +1,319 @@ +NOTE: The default branch has been renamed! +master is now named main + +If you have a local clone, you can update it by running: + +```shell +git branch -m master main +git fetch origin +git branch -u origin/main main +``` + +# **node-addon-api module** +This module contains **header-only C++ wrapper classes** which simplify +the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) +provided by Node.js when using C++. It provides a C++ object model +and exception handling semantics with low overhead. + +There are three options for implementing addons: Node-API, nan, or direct +use of internal V8, libuv, and Node.js libraries. Unless there is a need for +direct access to functionality that is not exposed by Node-API as outlined +in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) +in Node.js core, use Node-API. Refer to +[C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) +for more information on Node-API. + +Node-API is an ABI stable C interface provided by Node.js for building native +addons. It is independent of the underlying JavaScript runtime (e.g. V8 or ChakraCore) +and is maintained as part of Node.js itself. It is intended to insulate +native addons from changes in the underlying JavaScript engine and allow +modules compiled for one version to run on later versions of Node.js without +recompilation. + +The `node-addon-api` module, which is not part of Node.js, preserves the benefits +of the Node-API as it consists only of inline code that depends only on the stable API +provided by Node-API. As such, modules built against one version of Node.js +using node-addon-api should run without having to be rebuilt with newer versions +of Node.js. + +It is important to remember that *other* Node.js interfaces such as +`libuv` (included in a project via `#include `) are not ABI-stable across +Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` +exclusively and build against a version of Node.js that includes an +implementation of Node-API (meaning an active LTS version of Node.js) in +order to benefit from ABI stability across Node.js major versions. Node.js +provides an [ABI stability guide][] containing a detailed explanation of ABI +stability in general, and the Node-API ABI stability guarantee in particular. + +As new APIs are added to Node-API, node-addon-api must be updated to provide +wrappers for those new APIs. For this reason, node-addon-api provides +methods that allow callers to obtain the underlying Node-API handles so +direct calls to Node-API and the use of the objects/methods provided by +node-addon-api can be used together. For example, in order to be able +to use an API for which the node-addon-api does not yet provide a wrapper. + +APIs exposed by node-addon-api are generally used to create and +manipulate JavaScript values. Concepts and operations generally map +to ideas specified in the **ECMA262 Language Specification**. + +The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an +excellent orientation and tips for developers just getting started with Node-API +and node-addon-api. + +- **[Setup](#setup)** +- **[API Documentation](#api)** +- **[Examples](#examples)** +- **[Tests](#tests)** +- **[More resource and info about native Addons](#resources)** +- **[Badges](#badges)** +- **[Code of Conduct](CODE_OF_CONDUCT.md)** +- **[Contributors](#contributors)** +- **[License](#license)** + +## **Current version: 7.1.1** + +(See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) + +[![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) + + + +node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. +This allows addons built with it to run with Node.js versions which support the targeted Node-API version. +**However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that +every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. + +The oldest Node.js version supported by the current version of node-addon-api is Node.js 16.x. + +## Setup + - [Installation and usage](doc/setup.md) + - [node-gyp](doc/node-gyp.md) + - [cmake-js](doc/cmake-js.md) + - [Conversion tool](doc/conversion-tool.md) + - [Checker tool](doc/checker-tool.md) + - [Generator](doc/generator.md) + - [Prebuild tools](doc/prebuild_tools.md) + + + +### **API Documentation** + +The following is the documentation for node-addon-api. + + - [Full Class Hierarchy](doc/hierarchy.md) + - [Addon Structure](doc/addon.md) + - Data Types: + - [Env](doc/env.md) + - [CallbackInfo](doc/callbackinfo.md) + - [Reference](doc/reference.md) + - [Value](doc/value.md) + - [Name](doc/name.md) + - [Symbol](doc/symbol.md) + - [String](doc/string.md) + - [Number](doc/number.md) + - [Date](doc/date.md) + - [BigInt](doc/bigint.md) + - [Boolean](doc/boolean.md) + - [External](doc/external.md) + - [Object](doc/object.md) + - [Array](doc/array.md) + - [ObjectReference](doc/object_reference.md) + - [PropertyDescriptor](doc/property_descriptor.md) + - [Function](doc/function.md) + - [FunctionReference](doc/function_reference.md) + - [ObjectWrap](doc/object_wrap.md) + - [ClassPropertyDescriptor](doc/class_property_descriptor.md) + - [Buffer](doc/buffer.md) + - [ArrayBuffer](doc/array_buffer.md) + - [TypedArray](doc/typed_array.md) + - [TypedArrayOf](doc/typed_array_of.md) + - [DataView](doc/dataview.md) + - [Error Handling](doc/error_handling.md) + - [Error](doc/error.md) + - [TypeError](doc/type_error.md) + - [RangeError](doc/range_error.md) + - [SyntaxError](doc/syntax_error.md) + - [Object Lifetime Management](doc/object_lifetime_management.md) + - [HandleScope](doc/handle_scope.md) + - [EscapableHandleScope](doc/escapable_handle_scope.md) + - [Memory Management](doc/memory_management.md) + - [Async Operations](doc/async_operations.md) + - [AsyncWorker](doc/async_worker.md) + - [AsyncContext](doc/async_context.md) + - [AsyncWorker Variants](doc/async_worker_variants.md) + - [Thread-safe Functions](doc/threadsafe.md) + - [ThreadSafeFunction](doc/threadsafe_function.md) + - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) + - [Promises](doc/promises.md) + - [Version management](doc/version_management.md) + + + +### **Examples** + +Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** + +- **[Hello World](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/1_hello_world)** +- **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/2_function_arguments/node-addon-api)** +- **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/3_callbacks/node-addon-api)** +- **[Object factory](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/4_object_factory/node-addon-api)** +- **[Function factory](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/5_function_factory/node-addon-api)** +- **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/6_object_wrap/node-addon-api)** +- **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/main/src/1-getting-started/7_factory_wrap/node-addon-api)** +- **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/main/src/2-js-to-native-conversion/8_passing_wrapped/node-addon-api)** + + + +### **Tests** + +To run the **node-addon-api** tests do: + +``` +npm install +npm test +``` + +To avoid testing the deprecated portions of the API run +``` +npm install +npm test --disable-deprecated +``` + +To run the tests targeting a specific version of Node-API run +``` +npm install +export NAPI_VERSION=X +npm test --NAPI_VERSION=X +``` + +where X is the version of Node-API you want to target. + +To run a specific unit test, filter conditions are available + +**Example:** + compile and run only tests on objectwrap.cc and objectwrap.js + ``` + npm run unit --filter=objectwrap + ``` + +Multiple unit tests cane be selected with wildcards + +**Example:** +compile and run all test files ending with "reference" -> function_reference.cc, object_reference.cc, reference.cc + ``` + npm run unit --filter=*reference + ``` + +Multiple filter conditions can be joined to broaden the test selection + +**Example:** + compile and run all tests under folders threadsafe_function and typed_threadsafe_function and also the objectwrap.cc file + npm run unit --filter='*function objectwrap' + +### **Debug** + +To run the **node-addon-api** tests with `--debug` option: + +``` +npm run-script dev +``` + +If you want a faster build, you might use the following option: + +``` +npm run-script dev:incremental +``` + +Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** + +### **Benchmarks** + +You can run the available benchmarks using the following command: + +``` +npm run-script benchmark +``` + +See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. + + + +### **More resource and info about native Addons** +- **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** +- **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** +- **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** +- **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** + +As node-addon-api's core mission is to expose the plain C Node-API as C++ +wrappers, tools that facilitate n-api/node-addon-api providing more +convenient patterns for developing a Node.js add-on with n-api/node-addon-api +can be published to NPM as standalone packages. It is also recommended to tag +such packages with `node-addon-api` to provide more visibility to the community. + +Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). + + + +### **Other bindings** + +- **[napi-rs](https://napi.rs)** - (`Rust`) + + + +### **Badges** + +The use of badges is recommended to indicate the minimum version of Node-API +required for the module. This helps to determine which Node.js major versions are +supported. Addon maintainers can consult the [Node-API support matrix][] to determine +which Node.js versions provide a given Node-API version. The following badges are +available: + +![Node-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v1%20Badge.svg) +![Node-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v2%20Badge.svg) +![Node-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v3%20Badge.svg) +![Node-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v4%20Badge.svg) +![Node-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v5%20Badge.svg) +![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) +![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) +![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) +![Node-API v9 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v9%20Badge.svg) +![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) + +## **Contributing** + +We love contributions from the community to **node-addon-api**! +See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. + + + +## Team members + +### Active +| Name | GitHub Link | +| ------------------- | ----------------------------------------------------- | +| Anna Henningsen | [addaleax](https://github.com/addaleax) | +| Chengzhong Wu | [legendecas](https://github.com/legendecas) | +| Jack Xia | [JckXia](https://github.com/JckXia) | +| Kevin Eady | [KevinEady](https://github.com/KevinEady) | +| Michael Dawson | [mhdawson](https://github.com/mhdawson) | +| Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | +| Vladimir Morozov | [vmoroz](https://github.com/vmoroz) | + +### Emeritus +| Name | GitHub Link | +| ------------------- | ----------------------------------------------------- | +| Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | +| Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | +| Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | +| Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | +| Jason Ginchereau | [jasongin](https://github.com/jasongin) | +| Jim Schlight | [jschlight](https://github.com/jschlight) | +| Sampson Gao | [sampsongao](https://github.com/sampsongao) | +| Taylor Woll | [boingoing](https://github.com/boingoing) | + + + +Licensed under [MIT](./LICENSE.md) + +[ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ +[Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix diff --git a/tools/ui/node_modules/node-addon-api/common.gypi b/tools/ui/node_modules/node-addon-api/common.gypi new file mode 100644 index 0000000000000000000000000000000000000000..06c0176b29c2fbaa0296f7cea7c9eef4ba6a3756 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/common.gypi @@ -0,0 +1,20 @@ +{ + 'variables': { + 'NAPI_VERSION%': " +inline PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + napi_value name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, nullptr}); + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Name name, Getter getter, napi_property_attributes attributes, void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Accessor(nameValue, getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::AccessorCallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, setter, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + using CbData = details::AccessorCallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({getter, setter, nullptr}); + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Accessor( + nameValue, getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({cb, nullptr}); + + return PropertyDescriptor({utf8name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + napi_value name, + Callable cb, + napi_property_attributes attributes, + void* /*data*/) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + // TODO: Delete when the function is destroyed + auto callbackData = new CbData({cb, nullptr}); + + return PropertyDescriptor({nullptr, + name, + CbData::Wrapper, + nullptr, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Name name, Callable cb, napi_property_attributes attributes, void* data) { + napi_value nameValue = name; + return PropertyDescriptor::Function(nameValue, cb, attributes, data); +} + +#endif // !SRC_NAPI_INL_DEPRECATED_H_ diff --git a/tools/ui/node_modules/node-addon-api/napi-inl.h b/tools/ui/node_modules/node-addon-api/napi-inl.h new file mode 100644 index 0000000000000000000000000000000000000000..a5ae7af72408c6f19de4b43c6b521e17d45cd52b --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/napi-inl.h @@ -0,0 +1,6607 @@ +#ifndef SRC_NAPI_INL_H_ +#define SRC_NAPI_INL_H_ + +//////////////////////////////////////////////////////////////////////////////// +// Node-API C++ Wrapper Classes +// +// Inline header-only implementations for "Node-API" ABI-stable C APIs for +// Node.js. +//////////////////////////////////////////////////////////////////////////////// + +// Note: Do not include this file directly! Include "napi.h" instead. + +#include +#include +#if NAPI_HAS_THREADS +#include +#endif // NAPI_HAS_THREADS +#include +#include + +namespace Napi { + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +namespace NAPI_CPP_CUSTOM_NAMESPACE { +#endif + +// Helpers to handle functions exposed from C++ and internal constants. +namespace details { + +// New napi_status constants not yet available in all supported versions of +// Node.js releases. Only necessary when they are used in napi.h and napi-inl.h. +constexpr int napi_no_external_buffers_allowed = 22; + +template +inline void default_finalizer(napi_env /*env*/, void* data, void* /*hint*/) { + delete static_cast(data); +} + +// Attach a data item to an object and delete it when the object gets +// garbage-collected. +// TODO: Replace this code with `napi_add_finalizer()` whenever it becomes +// available on all supported versions of Node.js. +template > +inline napi_status AttachData(napi_env env, + napi_value obj, + FreeType* data, + void* hint = nullptr) { + napi_status status; +#if (NAPI_VERSION < 5) + napi_value symbol, external; + status = napi_create_symbol(env, nullptr, &symbol); + if (status == napi_ok) { + status = napi_create_external(env, data, finalizer, hint, &external); + if (status == napi_ok) { + napi_property_descriptor desc = {nullptr, + symbol, + nullptr, + nullptr, + nullptr, + external, + napi_default, + nullptr}; + status = napi_define_properties(env, obj, 1, &desc); + } + } +#else // NAPI_VERSION >= 5 + status = napi_add_finalizer(env, obj, data, finalizer, hint, nullptr); +#endif + return status; +} + +// For use in JS to C++ callback wrappers to catch any Napi::Error exceptions +// and rethrow them as JavaScript exceptions before returning from the callback. +template +inline napi_value WrapCallback(Callable callback) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + return callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + return nullptr; + } +#else // NAPI_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + return callback(); +#endif // NAPI_CPP_EXCEPTIONS +} + +// For use in JS to C++ void callback wrappers to catch any Napi::Error +// exceptions and rethrow them as JavaScript exceptions before returning from +// the callback. +template +inline void WrapVoidCallback(Callable callback) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + } +#else // NAPI_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + callback(); +#endif // NAPI_CPP_EXCEPTIONS +} + +template +struct CallbackData { + static inline napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); + } + + Callable callback; + void* data; +}; + +template +struct CallbackData { + static inline napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); + } + + Callable callback; + void* data; +}; + +template +napi_value TemplatedVoidCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + Callback(cbInfo); + return nullptr; + }); +} + +template +napi_value TemplatedCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + return Callback(cbInfo); + }); +} + +template +napi_value TemplatedInstanceCallback(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + return instance ? (instance->*UnwrapCallback)(cbInfo) : Napi::Value(); + }); +} + +template +napi_value TemplatedInstanceVoidCallback(napi_env env, napi_callback_info info) + NAPI_NOEXCEPT { + return details::WrapCallback([&] { + CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + if (instance) (instance->*UnwrapCallback)(cbInfo); + return nullptr; + }); +} + +template +struct FinalizeData { + static inline void Wrapper(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback([&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(Env(env), static_cast(data)); + delete finalizeData; + }); + } + + static inline void WrapperWithHint(napi_env env, + void* data, + void* finalizeHint) NAPI_NOEXCEPT { + WrapVoidCallback([&] { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback( + Env(env), static_cast(data), finalizeData->hint); + delete finalizeData; + }); + } + + Finalizer callback; + Hint* hint; +}; + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) +template , + typename FinalizerDataType = void> +struct ThreadSafeFinalize { + static inline void Wrapper(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env)); + delete finalizeData; + } + + static inline void FinalizeWrapperWithData(napi_env env, + void* rawFinalizeData, + void* /* rawContext */) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), finalizeData->data); + delete finalizeData; + } + + static inline void FinalizeWrapperWithContext(napi_env env, + void* rawFinalizeData, + void* rawContext) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback(Env(env), static_cast(rawContext)); + delete finalizeData; + } + + static inline void FinalizeFinalizeWrapperWithDataAndContext( + napi_env env, void* rawFinalizeData, void* rawContext) { + if (rawFinalizeData == nullptr) return; + + ThreadSafeFinalize* finalizeData = + static_cast(rawFinalizeData); + finalizeData->callback( + Env(env), finalizeData->data, static_cast(rawContext)); + delete finalizeData; + } + + FinalizerDataType* data; + Finalizer callback; +}; + +template +inline typename std::enable_if(nullptr)>::type +CallJsWrapper(napi_env env, napi_value jsCallback, void* context, void* data) { + details::WrapVoidCallback([&]() { + call(env, + Function(env, jsCallback), + static_cast(context), + static_cast(data)); + }); +} + +template +inline typename std::enable_if(nullptr)>::type +CallJsWrapper(napi_env env, + napi_value jsCallback, + void* /*context*/, + void* /*data*/) { + details::WrapVoidCallback([&]() { + if (jsCallback != nullptr) { + Function(env, jsCallback).Call(0, nullptr); + } + }); +} + +#if NAPI_VERSION > 4 + +template +napi_value DefaultCallbackWrapper(napi_env /*env*/, std::nullptr_t /*cb*/) { + return nullptr; +} + +template +napi_value DefaultCallbackWrapper(napi_env /*env*/, Napi::Function cb) { + return cb; +} + +#else +template +napi_value DefaultCallbackWrapper(napi_env env, Napi::Function cb) { + if (cb.IsEmpty()) { + return TSFN::EmptyFunctionFactory(env); + } + return cb; +} +#endif // NAPI_VERSION > 4 +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS + +template +struct AccessorCallbackData { + static inline napi_value GetterWrapper(napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); + } + + static inline napi_value SetterWrapper(napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo); + return nullptr; + }); + } + + Getter getterCallback; + Setter setterCallback; + void* data; +}; + +} // namespace details + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED +#include "napi-inl.deprecated.h" +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + +//////////////////////////////////////////////////////////////////////////////// +// Module registration +//////////////////////////////////////////////////////////////////////////////// + +// Register an add-on based on an initializer function. +#define NODE_API_MODULE(modname, regfunc) \ + static napi_value __napi_##regfunc(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, regfunc); \ + } \ + NAPI_MODULE(modname, __napi_##regfunc) + +// Register an add-on based on a subclass of `Addon` with a custom Node.js +// module name. +#define NODE_API_NAMED_ADDON(modname, classname) \ + static napi_value __napi_##classname(napi_env env, napi_value exports) { \ + return Napi::RegisterModule(env, exports, &classname::Init); \ + } \ + NAPI_MODULE(modname, __napi_##classname) + +// Register an add-on based on a subclass of `Addon` with the Node.js module +// name given by node-gyp from the `target_name` in binding.gyp. +#define NODE_API_ADDON(classname) \ + NODE_API_NAMED_ADDON(NODE_GYP_MODULE_NAME, classname) + +// Adapt the NAPI_MODULE registration function: +// - Wrap the arguments in NAPI wrappers. +// - Catch any NAPI errors and rethrow as JS exceptions. +inline napi_value RegisterModule(napi_env env, + napi_value exports, + ModuleRegisterCallback registerCallback) { + return details::WrapCallback([&] { + return napi_value( + registerCallback(Napi::Env(env), Napi::Object(env, exports))); + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// Maybe class +//////////////////////////////////////////////////////////////////////////////// + +template +bool Maybe::IsNothing() const { + return !_has_value; +} + +template +bool Maybe::IsJust() const { + return _has_value; +} + +template +void Maybe::Check() const { + NAPI_CHECK(IsJust(), "Napi::Maybe::Check", "Maybe value is Nothing."); +} + +template +T Maybe::Unwrap() const { + NAPI_CHECK(IsJust(), "Napi::Maybe::Unwrap", "Maybe value is Nothing."); + return _value; +} + +template +T Maybe::UnwrapOr(const T& default_value) const { + return _has_value ? _value : default_value; +} + +template +bool Maybe::UnwrapTo(T* out) const { + if (IsJust()) { + *out = _value; + return true; + }; + return false; +} + +template +bool Maybe::operator==(const Maybe& other) const { + return (IsJust() == other.IsJust()) && + (!IsJust() || Unwrap() == other.Unwrap()); +} + +template +bool Maybe::operator!=(const Maybe& other) const { + return !operator==(other); +} + +template +Maybe::Maybe() : _has_value(false) {} + +template +Maybe::Maybe(const T& t) : _has_value(true), _value(t) {} + +template +inline Maybe Nothing() { + return Maybe(); +} + +template +inline Maybe Just(const T& t) { + return Maybe(t); +} + +//////////////////////////////////////////////////////////////////////////////// +// Env class +//////////////////////////////////////////////////////////////////////////////// + +inline Env::Env(napi_env env) : _env(env) {} + +inline Env::operator napi_env() const { + return _env; +} + +inline Object Env::Global() const { + napi_value value; + napi_status status = napi_get_global(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Object()); + return Object(*this, value); +} + +inline Value Env::Undefined() const { + napi_value value; + napi_status status = napi_get_undefined(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline Value Env::Null() const { + napi_value value; + napi_status status = napi_get_null(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline bool Env::IsExceptionPending() const { + bool result; + napi_status status = napi_is_exception_pending(_env, &result); + if (status != napi_ok) + result = false; // Checking for a pending exception shouldn't throw. + return result; +} + +inline Error Env::GetAndClearPendingException() const { + napi_value value; + napi_status status = napi_get_and_clear_last_exception(_env, &value); + if (status != napi_ok) { + // Don't throw another exception when failing to get the exception! + return Error(); + } + return Error(_env, value); +} + +inline MaybeOrValue Env::RunScript(const char* utf8script) const { + String script = String::New(_env, utf8script); + return RunScript(script); +} + +inline MaybeOrValue Env::RunScript(const std::string& utf8script) const { + return RunScript(utf8script.c_str()); +} + +inline MaybeOrValue Env::RunScript(String script) const { + napi_value result; + napi_status status = napi_run_script(_env, script, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Value(_env, result), Napi::Value); +} + +#if NAPI_VERSION > 2 +template +void Env::CleanupHook::Wrapper(void* data) NAPI_NOEXCEPT { + auto* cleanupData = + static_cast::CleanupData*>( + data); + cleanupData->hook(); + delete cleanupData; +} + +template +void Env::CleanupHook::WrapperWithArg(void* data) NAPI_NOEXCEPT { + auto* cleanupData = + static_cast::CleanupData*>( + data); + cleanupData->hook(static_cast(cleanupData->arg)); + delete cleanupData; +} +#endif // NAPI_VERSION > 2 + +#if NAPI_VERSION > 5 +template fini> +inline void Env::SetInstanceData(T* data) const { + napi_status status = napi_set_instance_data( + _env, + data, + [](napi_env env, void* data, void*) { fini(env, static_cast(data)); }, + nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template fini> +inline void Env::SetInstanceData(DataType* data, HintType* hint) const { + napi_status status = napi_set_instance_data( + _env, + data, + [](napi_env env, void* data, void* hint) { + fini(env, static_cast(data), static_cast(hint)); + }, + hint); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline T* Env::GetInstanceData() const { + void* data = nullptr; + + napi_status status = napi_get_instance_data(_env, &data); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + + return static_cast(data); +} + +template +void Env::DefaultFini(Env, T* data) { + delete data; +} + +template +void Env::DefaultFiniWithHint(Env, DataType* data, HintType*) { + delete data; +} +#endif // NAPI_VERSION > 5 + +#if NAPI_VERSION > 8 +inline const char* Env::GetModuleFileName() const { + const char* result; + napi_status status = node_api_get_module_file_name(_env, &result); + NAPI_THROW_IF_FAILED(*this, status, nullptr); + return result; +} +#endif // NAPI_VERSION > 8 +//////////////////////////////////////////////////////////////////////////////// +// Value class +//////////////////////////////////////////////////////////////////////////////// + +inline Value::Value() : _env(nullptr), _value(nullptr) {} + +inline Value::Value(napi_env env, napi_value value) + : _env(env), _value(value) {} + +inline Value::operator napi_value() const { + return _value; +} + +inline bool Value::operator==(const Value& other) const { + return StrictEquals(other); +} + +inline bool Value::operator!=(const Value& other) const { + return !this->operator==(other); +} + +inline bool Value::StrictEquals(const Value& other) const { + bool result; + napi_status status = napi_strict_equals(_env, *this, other, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Napi::Env Value::Env() const { + return Napi::Env(_env); +} + +inline bool Value::IsEmpty() const { + return _value == nullptr; +} + +inline napi_valuetype Value::Type() const { + if (IsEmpty()) { + return napi_undefined; + } + + napi_valuetype type; + napi_status status = napi_typeof(_env, _value, &type); + NAPI_THROW_IF_FAILED(_env, status, napi_undefined); + return type; +} + +inline bool Value::IsUndefined() const { + return Type() == napi_undefined; +} + +inline bool Value::IsNull() const { + return Type() == napi_null; +} + +inline bool Value::IsBoolean() const { + return Type() == napi_boolean; +} + +inline bool Value::IsNumber() const { + return Type() == napi_number; +} + +#if NAPI_VERSION > 5 +inline bool Value::IsBigInt() const { + return Type() == napi_bigint; +} +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +inline bool Value::IsDate() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_date(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} +#endif + +inline bool Value::IsString() const { + return Type() == napi_string; +} + +inline bool Value::IsSymbol() const { + return Type() == napi_symbol; +} + +inline bool Value::IsArray() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_array(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsArrayBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_arraybuffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsTypedArray() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_typedarray(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsObject() const { + return Type() == napi_object || IsFunction(); +} + +inline bool Value::IsFunction() const { + return Type() == napi_function; +} + +inline bool Value::IsPromise() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_promise(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsDataView() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_dataview(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsBuffer() const { + if (IsEmpty()) { + return false; + } + + bool result; + napi_status status = napi_is_buffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsExternal() const { + return Type() == napi_external; +} + +template +inline T Value::As() const { +#ifdef NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS + T::CheckCast(_env, _value); +#endif + return T(_env, _value); +} + +inline MaybeOrValue Value::ToBoolean() const { + napi_value result; + napi_status status = napi_coerce_to_bool(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Boolean(_env, result), Napi::Boolean); +} + +inline MaybeOrValue Value::ToNumber() const { + napi_value result; + napi_status status = napi_coerce_to_number(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Number(_env, result), Napi::Number); +} + +inline MaybeOrValue Value::ToString() const { + napi_value result; + napi_status status = napi_coerce_to_string(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::String(_env, result), Napi::String); +} + +inline MaybeOrValue Value::ToObject() const { + napi_value result; + napi_status status = napi_coerce_to_object(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Object(_env, result), Napi::Object); +} + +//////////////////////////////////////////////////////////////////////////////// +// Boolean class +//////////////////////////////////////////////////////////////////////////////// + +inline Boolean Boolean::New(napi_env env, bool val) { + napi_value value; + napi_status status = napi_get_boolean(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Boolean()); + return Boolean(env, value); +} + +inline void Boolean::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Boolean::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Boolean::CheckCast", "napi_typeof failed"); + NAPI_CHECK( + type == napi_boolean, "Boolean::CheckCast", "value is not napi_boolean"); +} + +inline Boolean::Boolean() : Napi::Value() {} + +inline Boolean::Boolean(napi_env env, napi_value value) + : Napi::Value(env, value) {} + +inline Boolean::operator bool() const { + return Value(); +} + +inline bool Boolean::Value() const { + bool result; + napi_status status = napi_get_value_bool(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Number class +//////////////////////////////////////////////////////////////////////////////// + +inline Number Number::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_double(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Number()); + return Number(env, value); +} + +inline void Number::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Number::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Number::CheckCast", "napi_typeof failed"); + NAPI_CHECK( + type == napi_number, "Number::CheckCast", "value is not napi_number"); +} + +inline Number::Number() : Value() {} + +inline Number::Number(napi_env env, napi_value value) : Value(env, value) {} + +inline Number::operator int32_t() const { + return Int32Value(); +} + +inline Number::operator uint32_t() const { + return Uint32Value(); +} + +inline Number::operator int64_t() const { + return Int64Value(); +} + +inline Number::operator float() const { + return FloatValue(); +} + +inline Number::operator double() const { + return DoubleValue(); +} + +inline int32_t Number::Int32Value() const { + int32_t result; + napi_status status = napi_get_value_int32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint32_t Number::Uint32Value() const { + uint32_t result; + napi_status status = napi_get_value_uint32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline int64_t Number::Int64Value() const { + int64_t result; + napi_status status = napi_get_value_int64(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline float Number::FloatValue() const { + return static_cast(DoubleValue()); +} + +inline double Number::DoubleValue() const { + double result; + napi_status status = napi_get_value_double(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +#if NAPI_VERSION > 5 +//////////////////////////////////////////////////////////////////////////////// +// BigInt Class +//////////////////////////////////////////////////////////////////////////////// + +inline BigInt BigInt::New(napi_env env, int64_t val) { + napi_value value; + napi_status status = napi_create_bigint_int64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, uint64_t val) { + napi_value value; + napi_status status = napi_create_bigint_uint64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, + int sign_bit, + size_t word_count, + const uint64_t* words) { + napi_value value; + napi_status status = + napi_create_bigint_words(env, sign_bit, word_count, words, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline void BigInt::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "BigInt::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "BigInt::CheckCast", "napi_typeof failed"); + NAPI_CHECK( + type == napi_bigint, "BigInt::CheckCast", "value is not napi_bigint"); +} + +inline BigInt::BigInt() : Value() {} + +inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) {} + +inline int64_t BigInt::Int64Value(bool* lossless) const { + int64_t result; + napi_status status = + napi_get_value_bigint_int64(_env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint64_t BigInt::Uint64Value(bool* lossless) const { + uint64_t result; + napi_status status = + napi_get_value_bigint_uint64(_env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline size_t BigInt::WordCount() const { + size_t word_count; + napi_status status = + napi_get_value_bigint_words(_env, _value, nullptr, &word_count, nullptr); + NAPI_THROW_IF_FAILED(_env, status, 0); + return word_count; +} + +inline void BigInt::ToWords(int* sign_bit, + size_t* word_count, + uint64_t* words) { + napi_status status = + napi_get_value_bigint_words(_env, _value, sign_bit, word_count, words); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +//////////////////////////////////////////////////////////////////////////////// +// Date Class +//////////////////////////////////////////////////////////////////////////////// + +inline Date Date::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_date(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Date()); + return Date(env, value); +} + +inline void Date::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Date::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_date(env, value, &result); + NAPI_CHECK(status == napi_ok, "Date::CheckCast", "napi_is_date failed"); + NAPI_CHECK(result, "Date::CheckCast", "value is not date"); +} + +inline Date::Date() : Value() {} + +inline Date::Date(napi_env env, napi_value value) : Value(env, value) {} + +inline Date::operator double() const { + return ValueOf(); +} + +inline double Date::ValueOf() const { + double result; + napi_status status = napi_get_date_value(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Name class +//////////////////////////////////////////////////////////////////////////////// +inline void Name::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Name::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Name::CheckCast", "napi_typeof failed"); + NAPI_CHECK(type == napi_string || type == napi_symbol, + "Name::CheckCast", + "value is not napi_string or napi_symbol"); +} + +inline Name::Name() : Value() {} + +inline Name::Name(napi_env env, napi_value value) : Value(env, value) {} + +//////////////////////////////////////////////////////////////////////////////// +// String class +//////////////////////////////////////////////////////////////////////////////// + +inline String String::New(napi_env env, const std::string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const std::u16string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const char* val) { + // TODO(@gabrielschulhof) Remove if-statement when core's error handling is + // available in all supported versions. + if (val == nullptr) { + // Throw an error that looks like it came from core. + NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); + } + napi_value value; + napi_status status = + napi_create_string_utf8(env, val, std::strlen(val), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val) { + napi_value value; + // TODO(@gabrielschulhof) Remove if-statement when core's error handling is + // available in all supported versions. + if (val == nullptr) { + // Throw an error that looks like it came from core. + NAPI_THROW_IF_FAILED(env, napi_invalid_arg, String()); + } + napi_status status = + napi_create_string_utf16(env, val, std::u16string(val).size(), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf8(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf16(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline void String::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "String::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "String::CheckCast", "napi_typeof failed"); + NAPI_CHECK( + type == napi_string, "String::CheckCast", "value is not napi_string"); +} + +inline String::String() : Name() {} + +inline String::String(napi_env env, napi_value value) : Name(env, value) {} + +inline String::operator std::string() const { + return Utf8Value(); +} + +inline String::operator std::u16string() const { + return Utf16Value(); +} + +inline std::string String::Utf8Value() const { + size_t length; + napi_status status = + napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, ""); + + std::string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf8( + _env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, ""); + return value; +} + +inline std::u16string String::Utf16Value() const { + size_t length; + napi_status status = + napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + + std::u16string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf16( + _env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + return value; +} + +//////////////////////////////////////////////////////////////////////////////// +// Symbol class +//////////////////////////////////////////////////////////////////////////////// + +inline Symbol Symbol::New(napi_env env, const char* description) { + napi_value descriptionValue = description != nullptr + ? String::New(env, description) + : static_cast(nullptr); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, const std::string& description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, String description) { + napi_value descriptionValue = description; + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, napi_value description) { + napi_value value; + napi_status status = napi_create_symbol(env, description, &value); + NAPI_THROW_IF_FAILED(env, status, Symbol()); + return Symbol(env, value); +} + +inline MaybeOrValue Symbol::WellKnown(napi_env env, + const std::string& name) { +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + Value symbol_obj; + Value symbol_value; + if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && + symbol_obj.As().Get(name).UnwrapTo(&symbol_value)) { + return Just(symbol_value.As()); + } + return Nothing(); +#else + return Napi::Env(env) + .Global() + .Get("Symbol") + .As() + .Get(name) + .As(); +#endif +} + +inline MaybeOrValue Symbol::For(napi_env env, + const std::string& description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::For(env, descriptionValue); +} + +inline MaybeOrValue Symbol::For(napi_env env, const char* description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::For(env, descriptionValue); +} + +inline MaybeOrValue Symbol::For(napi_env env, String description) { + return Symbol::For(env, static_cast(description)); +} + +inline MaybeOrValue Symbol::For(napi_env env, napi_value description) { +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + Value symbol_obj; + Value symbol_for_value; + Value symbol_value; + if (Napi::Env(env).Global().Get("Symbol").UnwrapTo(&symbol_obj) && + symbol_obj.As().Get("for").UnwrapTo(&symbol_for_value) && + symbol_for_value.As() + .Call(symbol_obj, {description}) + .UnwrapTo(&symbol_value)) { + return Just(symbol_value.As()); + } + return Nothing(); +#else + Object symbol_obj = Napi::Env(env).Global().Get("Symbol").As(); + return symbol_obj.Get("for") + .As() + .Call(symbol_obj, {description}) + .As(); +#endif +} + +inline void Symbol::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Symbol::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Symbol::CheckCast", "napi_typeof failed"); + NAPI_CHECK( + type == napi_symbol, "Symbol::CheckCast", "value is not napi_symbol"); +} + +inline Symbol::Symbol() : Name() {} + +inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) {} + +//////////////////////////////////////////////////////////////////////////////// +// Automagic value creation +//////////////////////////////////////////////////////////////////////////////// + +namespace details { +template +struct vf_number { + static Number From(napi_env env, T value) { + return Number::New(env, static_cast(value)); + } +}; + +template <> +struct vf_number { + static Boolean From(napi_env env, bool value) { + return Boolean::New(env, value); + } +}; + +struct vf_utf8_charp { + static String From(napi_env env, const char* value) { + return String::New(env, value); + } +}; + +struct vf_utf16_charp { + static String From(napi_env env, const char16_t* value) { + return String::New(env, value); + } +}; +struct vf_utf8_string { + static String From(napi_env env, const std::string& value) { + return String::New(env, value); + } +}; + +struct vf_utf16_string { + static String From(napi_env env, const std::u16string& value) { + return String::New(env, value); + } +}; + +template +struct vf_fallback { + static Value From(napi_env env, const T& value) { return Value(env, value); } +}; + +template +struct disjunction : std::false_type {}; +template +struct disjunction : B {}; +template +struct disjunction + : std::conditional>::type {}; + +template +struct can_make_string + : disjunction::type, + typename std::is_convertible::type, + typename std::is_convertible::type, + typename std::is_convertible::type> {}; +} // namespace details + +template +Value Value::From(napi_env env, const T& value) { + using Helper = typename std::conditional< + std::is_integral::value || std::is_floating_point::value, + details::vf_number, + typename std::conditional::value, + String, + details::vf_fallback>::type>::type; + return Helper::From(env, value); +} + +template +String String::From(napi_env env, const T& value) { + struct Dummy {}; + using Helper = typename std::conditional< + std::is_convertible::value, + details::vf_utf8_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf8_string, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_string, + Dummy>::type>::type>::type>::type; + return Helper::From(env, value); +} + +//////////////////////////////////////////////////////////////////////////////// +// TypeTaggable class +//////////////////////////////////////////////////////////////////////////////// + +inline TypeTaggable::TypeTaggable() : Value() {} + +inline TypeTaggable::TypeTaggable(napi_env _env, napi_value _value) + : Value(_env, _value) {} + +#if NAPI_VERSION >= 8 + +inline void TypeTaggable::TypeTag(const napi_type_tag* type_tag) const { + napi_status status = napi_type_tag_object(_env, _value, type_tag); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline bool TypeTaggable::CheckTypeTag(const napi_type_tag* type_tag) const { + bool result; + napi_status status = + napi_check_object_type_tag(_env, _value, type_tag, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +#endif // NAPI_VERSION >= 8 + +//////////////////////////////////////////////////////////////////////////////// +// Object class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object::PropertyLValue::operator Value() const { + MaybeOrValue val = Object(_env, _object).Get(_key); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + return val.Unwrap(); +#else + return val; +#endif +} + +template +template +inline Object::PropertyLValue& Object::PropertyLValue::operator=( + ValueType value) { +#ifdef NODE_ADDON_API_ENABLE_MAYBE + MaybeOrValue result = +#endif + Object(_env, _object).Set(_key, value); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + result.Unwrap(); +#endif + return *this; +} + +template +inline Object::PropertyLValue::PropertyLValue(Object object, Key key) + : _env(object.Env()), _object(object), _key(key) {} + +inline Object Object::New(napi_env env) { + napi_value value; + napi_status status = napi_create_object(env, &value); + NAPI_THROW_IF_FAILED(env, status, Object()); + return Object(env, value); +} + +inline void Object::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Object::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Object::CheckCast", "napi_typeof failed"); + NAPI_CHECK( + type == napi_object, "Object::CheckCast", "value is not napi_object"); +} + +inline Object::Object() : TypeTaggable() {} + +inline Object::Object(napi_env env, napi_value value) + : TypeTaggable(env, value) {} + +inline Object::PropertyLValue Object::operator[]( + const char* utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator[]( + const std::string& utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator[](uint32_t index) { + return PropertyLValue(*this, index); +} + +inline Object::PropertyLValue Object::operator[](Value index) const { + return PropertyLValue(*this, index); +} + +inline MaybeOrValue Object::operator[](const char* utf8name) const { + return Get(utf8name); +} + +inline MaybeOrValue Object::operator[]( + const std::string& utf8name) const { + return Get(utf8name); +} + +inline MaybeOrValue Object::operator[](uint32_t index) const { + return Get(index); +} + +inline MaybeOrValue Object::Has(napi_value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Has(Value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Has(const char* utf8name) const { + bool result; + napi_status status = napi_has_named_property(_env, _value, utf8name, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Has(const std::string& utf8name) const { + return Has(utf8name.c_str()); +} + +inline MaybeOrValue Object::HasOwnProperty(napi_value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::HasOwnProperty(Value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::HasOwnProperty(const char* utf8name) const { + napi_value key; + napi_status status = + napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); + NAPI_MAYBE_THROW_IF_FAILED(_env, status, bool); + return HasOwnProperty(key); +} + +inline MaybeOrValue Object::HasOwnProperty( + const std::string& utf8name) const { + return HasOwnProperty(utf8name.c_str()); +} + +inline MaybeOrValue Object::Get(napi_value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); +} + +inline MaybeOrValue Object::Get(Value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); +} + +inline MaybeOrValue Object::Get(const char* utf8name) const { + napi_value result; + napi_status status = napi_get_named_property(_env, _value, utf8name, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, result), Value); +} + +inline MaybeOrValue Object::Get(const std::string& utf8name) const { + return Get(utf8name.c_str()); +} + +template +inline MaybeOrValue Object::Set(napi_value key, + const ValueType& value) const { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +template +inline MaybeOrValue Object::Set(Value key, const ValueType& value) const { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +template +inline MaybeOrValue Object::Set(const char* utf8name, + const ValueType& value) const { + napi_status status = + napi_set_named_property(_env, _value, utf8name, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +template +inline MaybeOrValue Object::Set(const std::string& utf8name, + const ValueType& value) const { + return Set(utf8name.c_str(), value); +} + +inline MaybeOrValue Object::Delete(napi_value key) const { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Delete(Value key) const { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Delete(const char* utf8name) const { + return Delete(String::New(_env, utf8name)); +} + +inline MaybeOrValue Object::Delete(const std::string& utf8name) const { + return Delete(String::New(_env, utf8name)); +} + +inline MaybeOrValue Object::Has(uint32_t index) const { + bool result; + napi_status status = napi_has_element(_env, _value, index, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::Get(uint32_t index) const { + napi_value value; + napi_status status = napi_get_element(_env, _value, index, &value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Value(_env, value), Value); +} + +template +inline MaybeOrValue Object::Set(uint32_t index, + const ValueType& value) const { + napi_status status = + napi_set_element(_env, _value, index, Value::From(_env, value)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::Delete(uint32_t index) const { + bool result; + napi_status status = napi_delete_element(_env, _value, index, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +inline MaybeOrValue Object::GetPropertyNames() const { + napi_value result; + napi_status status = napi_get_property_names(_env, _value, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, Array(_env, result), Array); +} + +inline MaybeOrValue Object::DefineProperty( + const PropertyDescriptor& property) const { + napi_status status = napi_define_properties( + _env, + _value, + 1, + reinterpret_cast(&property)); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::DefineProperties( + const std::initializer_list& properties) const { + napi_status status = napi_define_properties( + _env, + _value, + properties.size(), + reinterpret_cast(properties.begin())); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::DefineProperties( + const std::vector& properties) const { + napi_status status = napi_define_properties( + _env, + _value, + properties.size(), + reinterpret_cast(properties.data())); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::InstanceOf( + const Function& constructor) const { + bool result; + napi_status status = napi_instanceof(_env, _value, constructor, &result); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, result, bool); +} + +template +inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + details::AttachData::Wrapper>( + _env, *this, data, finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Object::AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint) const { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = details:: + AttachData::WrapperWithHint>( + _env, *this, data, finalizeData); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +#ifdef NAPI_CPP_EXCEPTIONS +inline Object::const_iterator::const_iterator(const Object* object, + const Type type) { + _object = object; + _keys = object->GetPropertyNames(); + _index = type == Type::BEGIN ? 0 : _keys.Length(); +} + +inline Object::const_iterator Napi::Object::begin() const { + const_iterator it(this, Object::const_iterator::Type::BEGIN); + return it; +} + +inline Object::const_iterator Napi::Object::end() const { + const_iterator it(this, Object::const_iterator::Type::END); + return it; +} + +inline Object::const_iterator& Object::const_iterator::operator++() { + ++_index; + return *this; +} + +inline bool Object::const_iterator::operator==( + const const_iterator& other) const { + return _index == other._index; +} + +inline bool Object::const_iterator::operator!=( + const const_iterator& other) const { + return _index != other._index; +} + +inline const std::pair> +Object::const_iterator::operator*() const { + const Value key = _keys[_index]; + const PropertyLValue value = (*_object)[key]; + return {key, value}; +} + +inline Object::iterator::iterator(Object* object, const Type type) { + _object = object; + _keys = object->GetPropertyNames(); + _index = type == Type::BEGIN ? 0 : _keys.Length(); +} + +inline Object::iterator Napi::Object::begin() { + iterator it(this, Object::iterator::Type::BEGIN); + return it; +} + +inline Object::iterator Napi::Object::end() { + iterator it(this, Object::iterator::Type::END); + return it; +} + +inline Object::iterator& Object::iterator::operator++() { + ++_index; + return *this; +} + +inline bool Object::iterator::operator==(const iterator& other) const { + return _index == other._index; +} + +inline bool Object::iterator::operator!=(const iterator& other) const { + return _index != other._index; +} + +inline std::pair> +Object::iterator::operator*() { + Value key = _keys[_index]; + PropertyLValue value = (*_object)[key]; + return {key, value}; +} +#endif // NAPI_CPP_EXCEPTIONS + +#if NAPI_VERSION >= 8 +inline MaybeOrValue Object::Freeze() const { + napi_status status = napi_object_freeze(_env, _value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} + +inline MaybeOrValue Object::Seal() const { + napi_status status = napi_object_seal(_env, _value); + NAPI_RETURN_OR_THROW_IF_FAILED(_env, status, status == napi_ok, bool); +} +#endif // NAPI_VERSION >= 8 + +//////////////////////////////////////////////////////////////////////////////// +// External class +//////////////////////////////////////////////////////////////////////////////// + +template +inline External External::New(napi_env env, T* data) { + napi_value value; + napi_status status = + napi_create_external(env, data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, External()); + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + napi_create_external(env, + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external( + env, + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +inline void External::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "External::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "External::CheckCast", "napi_typeof failed"); + NAPI_CHECK(type == napi_external, + "External::CheckCast", + "value is not napi_external"); +} + +template +inline External::External() : TypeTaggable() {} + +template +inline External::External(napi_env env, napi_value value) + : TypeTaggable(env, value) {} + +template +inline T* External::Data() const { + void* data; + napi_status status = napi_get_value_external(_env, _value, &data); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return reinterpret_cast(data); +} + +//////////////////////////////////////////////////////////////////////////////// +// Array class +//////////////////////////////////////////////////////////////////////////////// + +inline Array Array::New(napi_env env) { + napi_value value; + napi_status status = napi_create_array(env, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline Array Array::New(napi_env env, size_t length) { + napi_value value; + napi_status status = napi_create_array_with_length(env, length, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline void Array::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Array::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_array(env, value, &result); + NAPI_CHECK(status == napi_ok, "Array::CheckCast", "napi_is_array failed"); + NAPI_CHECK(result, "Array::CheckCast", "value is not array"); +} + +inline Array::Array() : Object() {} + +inline Array::Array(napi_env env, napi_value value) : Object(env, value) {} + +inline uint32_t Array::Length() const { + uint32_t result; + napi_status status = napi_get_array_length(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// ArrayBuffer class +//////////////////////////////////////////////////////////////////////////////// + +inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { + napi_value value; + void* data; + napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value); +} + +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength) { + napi_value value; + napi_status status = napi_create_external_arraybuffer( + env, externalData, byteLength, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value); +} +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + +inline void ArrayBuffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "ArrayBuffer::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_arraybuffer(env, value, &result); + NAPI_CHECK(status == napi_ok, + "ArrayBuffer::CheckCast", + "napi_is_arraybuffer failed"); + NAPI_CHECK(result, "ArrayBuffer::CheckCast", "value is not arraybuffer"); +} + +inline ArrayBuffer::ArrayBuffer() : Object() {} + +inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) + : Object(env, value) {} + +inline void* ArrayBuffer::Data() { + void* data; + napi_status status = napi_get_arraybuffer_info(_env, _value, &data, nullptr); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return data; +} + +inline size_t ArrayBuffer::ByteLength() { + size_t length; + napi_status status = + napi_get_arraybuffer_info(_env, _value, nullptr, &length); + NAPI_THROW_IF_FAILED(_env, status, 0); + return length; +} + +#if NAPI_VERSION >= 7 +inline bool ArrayBuffer::IsDetached() const { + bool detached; + napi_status status = napi_is_detached_arraybuffer(_env, _value, &detached); + NAPI_THROW_IF_FAILED(_env, status, false); + return detached; +} + +inline void ArrayBuffer::Detach() { + napi_status status = napi_detach_arraybuffer(_env, _value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_VERSION >= 7 + +//////////////////////////////////////////////////////////////////////////////// +// DataView class +//////////////////////////////////////////////////////////////////////////////// +inline DataView DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer) { + return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset) { + if (byteOffset > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New( + env, "Start offset is outside the bounds of the buffer"), + DataView()); + } + return New( + env, arrayBuffer, byteOffset, arrayBuffer.ByteLength() - byteOffset); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength) { + if (byteOffset + byteLength > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, "Invalid DataView length"), DataView()); + } + napi_value value; + napi_status status = + napi_create_dataview(env, byteLength, arrayBuffer, byteOffset, &value); + NAPI_THROW_IF_FAILED(env, status, DataView()); + return DataView(env, value); +} + +inline void DataView::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "DataView::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_dataview(env, value, &result); + NAPI_CHECK( + status == napi_ok, "DataView::CheckCast", "napi_is_dataview failed"); + NAPI_CHECK(result, "DataView::CheckCast", "value is not dataview"); +} + +inline DataView::DataView() : Object() {} + +inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + &_length /* byteLength */, + &_data /* data */, + nullptr /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Napi::ArrayBuffer DataView::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + &arrayBuffer /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +inline size_t DataView::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_dataview_info(_env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + nullptr /* arrayBuffer */, + &byteOffset /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t DataView::ByteLength() const { + return _length; +} + +inline void* DataView::Data() const { + return _data; +} + +inline float DataView::GetFloat32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline double DataView::GetFloat64(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int8_t DataView::GetInt8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int16_t DataView::GetInt16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int32_t DataView::GetInt32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint8_t DataView::GetUint8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint16_t DataView::GetUint16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint32_t DataView::GetUint32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline void DataView::SetFloat32(size_t byteOffset, float value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetFloat64(size_t byteOffset, double value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt8(size_t byteOffset, int8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt16(size_t byteOffset, int16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt32(size_t byteOffset, int32_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const { + WriteData(byteOffset, value); +} + +template +inline T DataView::ReadData(size_t byteOffset) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW( + RangeError::New(_env, "Offset is outside the bounds of the DataView"), + 0); + } + + return *reinterpret_cast(static_cast(_data) + byteOffset); +} + +template +inline void DataView::WriteData(size_t byteOffset, T value) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW_VOID( + RangeError::New(_env, "Offset is outside the bounds of the DataView")); + } + + *reinterpret_cast(static_cast(_data) + byteOffset) = value; +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArray class +//////////////////////////////////////////////////////////////////////////////// +inline void TypedArray::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "TypedArray::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_typedarray(env, value, &result); + NAPI_CHECK( + status == napi_ok, "TypedArray::CheckCast", "napi_is_typedarray failed"); + NAPI_CHECK(result, "TypedArray::CheckCast", "value is not typedarray"); +} + +inline TypedArray::TypedArray() + : Object(), _type(napi_typedarray_type::napi_int8_array), _length(0) {} + +inline TypedArray::TypedArray(napi_env env, napi_value value) + : Object(env, value), + _type(napi_typedarray_type::napi_int8_array), + _length(0) { + if (value != nullptr) { + napi_status status = + napi_get_typedarray_info(_env, + _value, + &const_cast(this)->_type, + &const_cast(this)->_length, + nullptr, + nullptr, + nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +inline TypedArray::TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length) + : Object(env, value), _type(type), _length(length) {} + +inline napi_typedarray_type TypedArray::TypedArrayType() const { + return _type; +} + +inline uint8_t TypedArray::ElementSize() const { + switch (_type) { + case napi_int8_array: + case napi_uint8_array: + case napi_uint8_clamped_array: + return 1; + case napi_int16_array: + case napi_uint16_array: + return 2; + case napi_int32_array: + case napi_uint32_array: + case napi_float32_array: + return 4; + case napi_float64_array: +#if (NAPI_VERSION > 5) + case napi_bigint64_array: + case napi_biguint64_array: +#endif // (NAPI_VERSION > 5) + return 8; + default: + return 0; + } +} + +inline size_t TypedArray::ElementLength() const { + return _length; +} + +inline size_t TypedArray::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t TypedArray::ByteLength() const { + return ElementSize() * ElementLength(); +} + +inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArrayOf class +//////////////////////////////////////////////////////////////////////////////// +template +inline void TypedArrayOf::CheckCast(napi_env env, napi_value value) { + TypedArray::CheckCast(env, value); + napi_typedarray_type type; + napi_status status = napi_get_typedarray_info( + env, value, &type, nullptr, nullptr, nullptr, nullptr); + NAPI_CHECK(status == napi_ok, + "TypedArrayOf::CheckCast", + "napi_is_typedarray failed"); + + NAPI_CHECK( + (type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && std::is_same::value)), + "TypedArrayOf::CheckCast", + "Array type must match the template parameter. (Uint8 arrays may " + "optionally have the \"clamped\" array type.)"); +} + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + napi_typedarray_type type) { + Napi::ArrayBuffer arrayBuffer = + Napi::ArrayBuffer::New(env, elementLength * sizeof(T)); + return New(env, elementLength, arrayBuffer, 0, type); +} + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::ArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type) { + napi_value value; + napi_status status = napi_create_typedarray( + env, type, elementLength, arrayBuffer, bufferOffset, &value); + NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); + + return TypedArrayOf( + env, + value, + type, + elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + + bufferOffset)); +} + +template +inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) {} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value) + : TypedArray(env, value), _data(nullptr) { + napi_status status = napi_ok; + if (value != nullptr) { + void* data = nullptr; + status = napi_get_typedarray_info( + _env, _value, &_type, &_length, &data, nullptr, nullptr); + _data = static_cast(data); + } else { + _type = TypedArrayTypeForPrimitiveType(); + _length = 0; + } + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data) + : TypedArray(env, value, type, length), _data(data) { + if (!(type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && + std::is_same::value))) { + NAPI_THROW_VOID(TypeError::New( + env, + "Array type must match the template parameter. " + "(Uint8 arrays may optionally have the \"clamped\" array type.)")); + } +} + +template +inline T& TypedArrayOf::operator[](size_t index) { + return _data[index]; +} + +template +inline const T& TypedArrayOf::operator[](size_t index) const { + return _data[index]; +} + +template +inline T* TypedArrayOf::Data() { + return _data; +} + +template +inline const T* TypedArrayOf::Data() const { + return _data; +} + +//////////////////////////////////////////////////////////////////////////////// +// Function class +//////////////////////////////////////////////////////////////////////////////// + +template +inline napi_status CreateFunction(napi_env env, + const char* utf8name, + napi_callback cb, + CbData* data, + napi_value* result) { + napi_status status = + napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); + if (status == napi_ok) { + status = Napi::details::AttachData(env, *result, data); + } + + return status; +} + +template +inline Function Function::New(napi_env env, const char* utf8name, void* data) { + napi_value result = nullptr; + napi_status status = napi_create_function(env, + utf8name, + NAPI_AUTO_LENGTH, + details::TemplatedVoidCallback, + data, + &result); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, result); +} + +template +inline Function Function::New(napi_env env, const char* utf8name, void* data) { + napi_value result = nullptr; + napi_status status = napi_create_function(env, + utf8name, + NAPI_AUTO_LENGTH, + details::TemplatedCallback, + data, + &result); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, result); +} + +template +inline Function Function::New(napi_env env, + const std::string& utf8name, + void* data) { + return Function::New(env, utf8name.c_str(), data); +} + +template +inline Function Function::New(napi_env env, + const std::string& utf8name, + void* data) { + return Function::New(env, utf8name.c_str(), data); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const char* utf8name, + void* data) { + using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr))); + using CbData = details::CallbackData; + auto callbackData = new CbData{std::move(cb), data}; + + napi_value value; + napi_status status = + CreateFunction(env, utf8name, CbData::Wrapper, callbackData, &value); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, Function()); + } + + return Function(env, value); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data) { + return New(env, cb, utf8name.c_str(), data); +} + +inline void Function::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Function::CheckCast", "empty value"); + + napi_valuetype type; + napi_status status = napi_typeof(env, value, &type); + NAPI_CHECK(status == napi_ok, "Function::CheckCast", "napi_typeof failed"); + NAPI_CHECK(type == napi_function, + "Function::CheckCast", + "value is not napi_function"); +} + +inline Function::Function() : Object() {} + +inline Function::Function(napi_env env, napi_value value) + : Object(env, value) {} + +inline MaybeOrValue Function::operator()( + const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call( + const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call( + const std::vector& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call( + const std::vector& args) const { + return Call(Env().Undefined(), args); +} + +inline MaybeOrValue Function::Call(size_t argc, + const napi_value* args) const { + return Call(Env().Undefined(), argc, args); +} + +inline MaybeOrValue Function::Call( + napi_value recv, const std::initializer_list& args) const { + return Call(recv, args.size(), args.begin()); +} + +inline MaybeOrValue Function::Call( + napi_value recv, const std::vector& args) const { + return Call(recv, args.size(), args.data()); +} + +inline MaybeOrValue Function::Call( + napi_value recv, const std::vector& args) const { + const size_t argc = args.size(); + const size_t stackArgsCount = 6; + napi_value stackArgs[stackArgsCount]; + std::vector heapArgs; + napi_value* argv; + if (argc <= stackArgsCount) { + argv = stackArgs; + } else { + heapArgs.resize(argc); + argv = heapArgs.data(); + } + + for (size_t index = 0; index < argc; index++) { + argv[index] = static_cast(args[index]); + } + + return Call(recv, argc, argv); +} + +inline MaybeOrValue Function::Call(napi_value recv, + size_t argc, + const napi_value* args) const { + napi_value result; + napi_status status = + napi_call_function(_env, recv, _value, argc, args, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Value(_env, result), Napi::Value); +} + +inline MaybeOrValue Function::MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context) const { + return MakeCallback(recv, args.size(), args.begin(), context); +} + +inline MaybeOrValue Function::MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context) const { + return MakeCallback(recv, args.size(), args.data(), context); +} + +inline MaybeOrValue Function::MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context) const { + napi_value result; + napi_status status = + napi_make_callback(_env, context, recv, _value, argc, args, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Value(_env, result), Napi::Value); +} + +inline MaybeOrValue Function::New( + const std::initializer_list& args) const { + return New(args.size(), args.begin()); +} + +inline MaybeOrValue Function::New( + const std::vector& args) const { + return New(args.size(), args.data()); +} + +inline MaybeOrValue Function::New(size_t argc, + const napi_value* args) const { + napi_value result; + napi_status status = napi_new_instance(_env, _value, argc, args, &result); + NAPI_RETURN_OR_THROW_IF_FAILED( + _env, status, Napi::Object(_env, result), Napi::Object); +} + +//////////////////////////////////////////////////////////////////////////////// +// Promise class +//////////////////////////////////////////////////////////////////////////////// + +inline Promise::Deferred Promise::Deferred::New(napi_env env) { + return Promise::Deferred(env); +} + +inline Promise::Deferred::Deferred(napi_env env) : _env(env) { + napi_status status = napi_create_promise(_env, &_deferred, &_promise); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Promise Promise::Deferred::Promise() const { + return Napi::Promise(_env, _promise); +} + +inline Napi::Env Promise::Deferred::Env() const { + return Napi::Env(_env); +} + +inline void Promise::Deferred::Resolve(napi_value value) const { + napi_status status = napi_resolve_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::Deferred::Reject(napi_value value) const { + napi_status status = napi_reject_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Promise::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_promise(env, value, &result); + NAPI_CHECK(status == napi_ok, "Promise::CheckCast", "napi_is_promise failed"); + NAPI_CHECK(result, "Promise::CheckCast", "value is not promise"); +} + +inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {} + +//////////////////////////////////////////////////////////////////////////////// +// Buffer class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Buffer Buffer::New(napi_env env, size_t length) { + napi_value value; + void* data; + napi_status status = + napi_create_buffer(env, length * sizeof(T), &data, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +template +inline Buffer Buffer::New(napi_env env, T* data, size_t length) { + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof(T), data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); + napi_status status = + napi_create_external_buffer(env, + length * sizeof(T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); + napi_status status = napi_create_external_buffer( + env, + length * sizeof(T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +} +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + +template +inline Buffer Buffer::NewOrCopy(napi_env env, T* data, size_t length) { +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof(T), data, nullptr, nullptr, &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + // If we can't create an external buffer, we'll just copy the data. + return Buffer::Copy(env, data, length); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +} + +template +template +inline Buffer Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), nullptr}); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = + napi_create_external_buffer(env, + length * sizeof(T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + // If we can't create an external buffer, we'll just copy the data. + Buffer ret = Buffer::Copy(env, data, length); + details::FinalizeData::Wrapper(env, data, finalizeData); + return ret; +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED +} + +template +template +inline Buffer Buffer::NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + details::FinalizeData* finalizeData = + new details::FinalizeData( + {std::move(finalizeCallback), finalizeHint}); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + napi_value value; + napi_status status = napi_create_external_buffer( + env, + length * sizeof(T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status == details::napi_no_external_buffers_allowed) { +#endif + // If we can't create an external buffer, we'll just copy the data. + Buffer ret = Buffer::Copy(env, data, length); + details::FinalizeData::WrapperWithHint( + env, data, finalizeData); + return ret; +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + } + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value); +#endif +} + +template +inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { + napi_value value; + napi_status status = + napi_create_buffer_copy(env, length * sizeof(T), data, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +template +inline void Buffer::CheckCast(napi_env env, napi_value value) { + NAPI_CHECK(value != nullptr, "Buffer::CheckCast", "empty value"); + + bool result; + napi_status status = napi_is_buffer(env, value, &result); + NAPI_CHECK(status == napi_ok, "Buffer::CheckCast", "napi_is_buffer failed"); + NAPI_CHECK(result, "Buffer::CheckCast", "value is not buffer"); +} + +template +inline Buffer::Buffer() : Uint8Array() {} + +template +inline Buffer::Buffer(napi_env env, napi_value value) + : Uint8Array(env, value) {} + +template +inline size_t Buffer::Length() const { + return ByteLength() / sizeof(T); +} + +template +inline T* Buffer::Data() const { + return reinterpret_cast(const_cast(Uint8Array::Data())); +} + +//////////////////////////////////////////////////////////////////////////////// +// Error class +//////////////////////////////////////////////////////////////////////////////// + +inline Error Error::New(napi_env env) { + napi_status status; + napi_value error = nullptr; + bool is_exception_pending; + napi_extended_error_info last_error_info_copy; + + { + // We must retrieve the last error info before doing anything else because + // doing anything else will replace the last error info. + const napi_extended_error_info* last_error_info; + status = napi_get_last_error_info(env, &last_error_info); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info"); + + // All fields of the `napi_extended_error_info` structure gets reset in + // subsequent Node-API function calls on the same `env`. This includes a + // call to `napi_is_exception_pending()`. So here it is necessary to make a + // copy of the information as the `error_code` field is used later on. + memcpy(&last_error_info_copy, + last_error_info, + sizeof(napi_extended_error_info)); + } + + status = napi_is_exception_pending(env, &is_exception_pending); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending"); + + // A pending exception takes precedence over any internal error status. + if (is_exception_pending) { + status = napi_get_and_clear_last_exception(env, &error); + NAPI_FATAL_IF_FAILED( + status, "Error::New", "napi_get_and_clear_last_exception"); + } else { + const char* error_message = last_error_info_copy.error_message != nullptr + ? last_error_info_copy.error_message + : "Error in native callback"; + + napi_value message; + status = napi_create_string_utf8( + env, error_message, std::strlen(error_message), &message); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8"); + + switch (last_error_info_copy.error_code) { + case napi_object_expected: + case napi_string_expected: + case napi_boolean_expected: + case napi_number_expected: + status = napi_create_type_error(env, nullptr, message, &error); + break; + default: + status = napi_create_error(env, nullptr, message, &error); + break; + } + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error"); + } + + return Error(env, error); +} + +inline Error Error::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), napi_create_error); +} + +inline Error Error::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), napi_create_error); +} + +inline NAPI_NO_RETURN void Error::Fatal(const char* location, + const char* message) { + napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH); +} + +inline Error::Error() : ObjectReference() {} + +inline Error::Error(napi_env env, napi_value value) + : ObjectReference(env, nullptr) { + if (value != nullptr) { + // Attempting to create a reference on the error object. + // If it's not a Object/Function/Symbol, this call will return an error + // status. + napi_status status = napi_create_reference(env, value, 1, &_ref); + + if (status != napi_ok) { + napi_value wrappedErrorObj; + + // Create an error object + status = napi_create_object(env, &wrappedErrorObj); + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_object"); + + // property flag that we attach to show the error object is wrapped + napi_property_descriptor wrapObjFlag = { + ERROR_WRAP_VALUE(), // Unique GUID identifier since Symbol isn't a + // viable option + nullptr, + nullptr, + nullptr, + nullptr, + Value::From(env, value), + napi_enumerable, + nullptr}; + + status = napi_define_properties(env, wrappedErrorObj, 1, &wrapObjFlag); +#ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + if (status == napi_pending_exception) { + // Test if the pending exception was reported because the environment is + // shutting down. We assume that a status of napi_pending_exception + // coupled with the absence of an actual pending exception means that + // the environment is shutting down. If so, we replace the + // napi_pending_exception status with napi_ok. + bool is_exception_pending = false; + status = napi_is_exception_pending(env, &is_exception_pending); + if (status == napi_ok && !is_exception_pending) { + status = napi_ok; + } else { + status = napi_pending_exception; + } + } +#endif // NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_define_properties"); + + // Create a reference on the newly wrapped object + status = napi_create_reference(env, wrappedErrorObj, 1, &_ref); + } + + // Avoid infinite recursion in the failure case. + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference"); + } +} + +inline Object Error::Value() const { + if (_ref == nullptr) { + return Object(_env, nullptr); + } + + napi_value refValue; + napi_status status = napi_get_reference_value(_env, _ref, &refValue); + NAPI_THROW_IF_FAILED(_env, status, Object()); + + napi_valuetype type; + status = napi_typeof(_env, refValue, &type); + NAPI_THROW_IF_FAILED(_env, status, Object()); + + // If refValue isn't a symbol, then we proceed to whether the refValue has the + // wrapped error flag + if (type != napi_symbol) { + // We are checking if the object is wrapped + bool isWrappedObject = false; + + status = napi_has_property(_env, + refValue, + String::From(_env, ERROR_WRAP_VALUE()), + &isWrappedObject); + + // Don't care about status + if (isWrappedObject) { + napi_value unwrappedValue; + status = napi_get_property(_env, + refValue, + String::From(_env, ERROR_WRAP_VALUE()), + &unwrappedValue); + NAPI_THROW_IF_FAILED(_env, status, Object()); + + return Object(_env, unwrappedValue); + } + } + + return Object(_env, refValue); +} + +inline Error::Error(Error&& other) : ObjectReference(std::move(other)) {} + +inline Error& Error::operator=(Error&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline Error::Error(const Error& other) : ObjectReference(other) {} + +inline Error& Error::operator=(const Error& other) { + Reset(); + + _env = other.Env(); + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_THROW_IF_FAILED(_env, status, *this); + } + + return *this; +} + +inline const std::string& Error::Message() const NAPI_NOEXCEPT { + if (_message.size() == 0 && _env != nullptr) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + _message = Get("message").As(); + } catch (...) { + // Catch all errors here, to include e.g. a std::bad_alloc from + // the std::string::operator=, because this method may not throw. + } +#else // NAPI_CPP_EXCEPTIONS +#if defined(NODE_ADDON_API_ENABLE_MAYBE) + Napi::Value message_val; + if (Get("message").UnwrapTo(&message_val)) { + _message = message_val.As(); + } +#else + _message = Get("message").As(); +#endif +#endif // NAPI_CPP_EXCEPTIONS + } + return _message; +} + +// we created an object on the &_ref +inline void Error::ThrowAsJavaScriptException() const { + HandleScope scope(_env); + if (!IsEmpty()) { +#ifdef NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS + bool pendingException = false; + + // check if there is already a pending exception. If so don't try to throw a + // new one as that is not allowed/possible + napi_status status = napi_is_exception_pending(_env, &pendingException); + + if ((status != napi_ok) || + ((status == napi_ok) && (pendingException == false))) { + // We intentionally don't use `NAPI_THROW_*` macros here to ensure + // that there is no possible recursion as `ThrowAsJavaScriptException` + // is part of `NAPI_THROW_*` macro definition for noexcept. + + status = napi_throw(_env, Value()); + + if (status == napi_pending_exception) { + // The environment must be terminating as we checked earlier and there + // was no pending exception. In this case continuing will result + // in a fatal error and there is nothing the author has done incorrectly + // in their code that is worth flagging through a fatal error + return; + } + } else { + status = napi_pending_exception; + } +#else + // We intentionally don't use `NAPI_THROW_*` macros here to ensure + // that there is no possible recursion as `ThrowAsJavaScriptException` + // is part of `NAPI_THROW_*` macro definition for noexcept. + + napi_status status = napi_throw(_env, Value()); +#endif + +#ifdef NAPI_CPP_EXCEPTIONS + if (status != napi_ok) { + throw Error::New(_env); + } +#else // NAPI_CPP_EXCEPTIONS + NAPI_FATAL_IF_FAILED( + status, "Error::ThrowAsJavaScriptException", "napi_throw"); +#endif // NAPI_CPP_EXCEPTIONS + } +} + +#ifdef NAPI_CPP_EXCEPTIONS + +inline const char* Error::what() const NAPI_NOEXCEPT { + return Message().c_str(); +} + +#endif // NAPI_CPP_EXCEPTIONS + +inline const char* Error::ERROR_WRAP_VALUE() NAPI_NOEXCEPT { + return "4bda9e7e-4913-4dbc-95de-891cbf66598e-errorVal"; +} + +template +inline TError Error::New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error) { + napi_value str; + napi_status status = napi_create_string_utf8(env, message, length, &str); + NAPI_THROW_IF_FAILED(env, status, TError()); + + napi_value error; + status = create_error(env, nullptr, str, &error); + NAPI_THROW_IF_FAILED(env, status, TError()); + + return TError(env, error); +} + +inline TypeError TypeError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), napi_create_type_error); +} + +inline TypeError TypeError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), napi_create_type_error); +} + +inline TypeError::TypeError() : Error() {} + +inline TypeError::TypeError(napi_env env, napi_value value) + : Error(env, value) {} + +inline RangeError RangeError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), napi_create_range_error); +} + +inline RangeError RangeError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), napi_create_range_error); +} + +inline RangeError::RangeError() : Error() {} + +inline RangeError::RangeError(napi_env env, napi_value value) + : Error(env, value) {} + +#if NAPI_VERSION > 8 +inline SyntaxError SyntaxError::New(napi_env env, const char* message) { + return Error::New( + env, message, std::strlen(message), node_api_create_syntax_error); +} + +inline SyntaxError SyntaxError::New(napi_env env, const std::string& message) { + return Error::New( + env, message.c_str(), message.size(), node_api_create_syntax_error); +} + +inline SyntaxError::SyntaxError() : Error() {} + +inline SyntaxError::SyntaxError(napi_env env, napi_value value) + : Error(env, value) {} +#endif // NAPI_VERSION > 8 + +//////////////////////////////////////////////////////////////////////////////// +// Reference class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Reference Reference::New(const T& value, + uint32_t initialRefcount) { + napi_env env = value.Env(); + napi_value val = value; + + if (val == nullptr) { + return Reference(env, nullptr); + } + + napi_ref ref; + napi_status status = napi_create_reference(env, value, initialRefcount, &ref); + NAPI_THROW_IF_FAILED(env, status, Reference()); + + return Reference(env, ref); +} + +template +inline Reference::Reference() + : _env(nullptr), _ref(nullptr), _suppressDestruct(false) {} + +template +inline Reference::Reference(napi_env env, napi_ref ref) + : _env(env), _ref(ref), _suppressDestruct(false) {} + +template +inline Reference::~Reference() { + if (_ref != nullptr) { + if (!_suppressDestruct) { + napi_delete_reference(_env, _ref); + } + + _ref = nullptr; + } +} + +template +inline Reference::Reference(Reference&& other) + : _env(other._env), + _ref(other._ref), + _suppressDestruct(other._suppressDestruct) { + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; +} + +template +inline Reference& Reference::operator=(Reference&& other) { + Reset(); + _env = other._env; + _ref = other._ref; + _suppressDestruct = other._suppressDestruct; + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; + return *this; +} + +template +inline Reference::Reference(const Reference& other) + : _env(other._env), _ref(nullptr), _suppressDestruct(false) { + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + // Copying is a limited scenario (currently only used for Error object) and + // always creates a strong reference to the given value even if the incoming + // reference is weak. + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_FATAL_IF_FAILED( + status, "Reference::Reference", "napi_create_reference"); + } +} + +template +inline Reference::operator napi_ref() const { + return _ref; +} + +template +inline bool Reference::operator==(const Reference& other) const { + HandleScope scope(_env); + return this->Value().StrictEquals(other.Value()); +} + +template +inline bool Reference::operator!=(const Reference& other) const { + return !this->operator==(other); +} + +template +inline Napi::Env Reference::Env() const { + return Napi::Env(_env); +} + +template +inline bool Reference::IsEmpty() const { + return _ref == nullptr; +} + +template +inline T Reference::Value() const { + if (_ref == nullptr) { + return T(_env, nullptr); + } + + napi_value value; + napi_status status = napi_get_reference_value(_env, _ref, &value); + NAPI_THROW_IF_FAILED(_env, status, T()); + return T(_env, value); +} + +template +inline uint32_t Reference::Ref() const { + uint32_t result; + napi_status status = napi_reference_ref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +template +inline uint32_t Reference::Unref() const { + uint32_t result; + napi_status status = napi_reference_unref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +template +inline void Reference::Reset() { + if (_ref != nullptr) { + napi_status status = napi_delete_reference(_env, _ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + _ref = nullptr; + } +} + +template +inline void Reference::Reset(const T& value, uint32_t refcount) { + Reset(); + _env = value.Env(); + + napi_value val = value; + if (val != nullptr) { + napi_status status = napi_create_reference(_env, value, refcount, &_ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Reference::SuppressDestruct() { + _suppressDestruct = true; +} + +template +inline Reference Weak(T value) { + return Reference::New(value, 0); +} + +inline ObjectReference Weak(Object value) { + return Reference::New(value, 0); +} + +inline FunctionReference Weak(Function value) { + return Reference::New(value, 0); +} + +template +inline Reference Persistent(T value) { + return Reference::New(value, 1); +} + +inline ObjectReference Persistent(Object value) { + return Reference::New(value, 1); +} + +inline FunctionReference Persistent(Function value) { + return Reference::New(value, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectReference class +//////////////////////////////////////////////////////////////////////////////// + +inline ObjectReference::ObjectReference() : Reference() {} + +inline ObjectReference::ObjectReference(napi_env env, napi_ref ref) + : Reference(env, ref) {} + +inline ObjectReference::ObjectReference(Reference&& other) + : Reference(std::move(other)) {} + +inline ObjectReference& ObjectReference::operator=(Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(ObjectReference&& other) + : Reference(std::move(other)) {} + +inline ObjectReference& ObjectReference::operator=(ObjectReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(const ObjectReference& other) + : Reference(other) {} + +inline MaybeOrValue ObjectReference::Get( + const char* utf8name) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Get(utf8name); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue ObjectReference::Get( + const std::string& utf8name) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Get(utf8name); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + napi_value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + Napi::Value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + const char* utf8value) const { + HandleScope scope(_env); + return Value().Set(utf8name, utf8value); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + bool boolValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, boolValue); +} + +inline MaybeOrValue ObjectReference::Set(const char* utf8name, + double numberValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, numberValue); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + napi_value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + Napi::Value value) const { + HandleScope scope(_env); + return Value().Set(utf8name, value); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + std::string& utf8value) const { + HandleScope scope(_env); + return Value().Set(utf8name, utf8value); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + bool boolValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, boolValue); +} + +inline MaybeOrValue ObjectReference::Set(const std::string& utf8name, + double numberValue) const { + HandleScope scope(_env); + return Value().Set(utf8name, numberValue); +} + +inline MaybeOrValue ObjectReference::Get(uint32_t index) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Get(index); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + napi_value value) const { + HandleScope scope(_env); + return Value().Set(index, value); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + Napi::Value value) const { + HandleScope scope(_env); + return Value().Set(index, value); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + const char* utf8value) const { + HandleScope scope(_env); + return Value().Set(index, utf8value); +} + +inline MaybeOrValue ObjectReference::Set( + uint32_t index, const std::string& utf8value) const { + HandleScope scope(_env); + return Value().Set(index, utf8value); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + bool boolValue) const { + HandleScope scope(_env); + return Value().Set(index, boolValue); +} + +inline MaybeOrValue ObjectReference::Set(uint32_t index, + double numberValue) const { + HandleScope scope(_env); + return Value().Set(index, numberValue); +} + +//////////////////////////////////////////////////////////////////////////////// +// FunctionReference class +//////////////////////////////////////////////////////////////////////////////// + +inline FunctionReference::FunctionReference() : Reference() {} + +inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) + : Reference(env, ref) {} + +inline FunctionReference::FunctionReference(Reference&& other) + : Reference(std::move(other)) {} + +inline FunctionReference& FunctionReference::operator=( + Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline FunctionReference::FunctionReference(FunctionReference&& other) + : Reference(std::move(other)) {} + +inline FunctionReference& FunctionReference::operator=( + FunctionReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline MaybeOrValue FunctionReference::operator()( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value()(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + const std::vector& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + napi_value recv, const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(recv, args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + napi_value recv, const std::vector& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(recv, args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::Call( + napi_value recv, size_t argc, const napi_value* args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().Call(recv, argc, args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().MakeCallback(recv, args, context); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().MakeCallback(recv, args, context); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = + Value().MakeCallback(recv, argc, args, context); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap())); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +#endif +} + +inline MaybeOrValue FunctionReference::New( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().New(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Object(); + } + return scope.Escape(result).As(); +#endif +} + +inline MaybeOrValue FunctionReference::New( + const std::vector& args) const { + EscapableHandleScope scope(_env); + MaybeOrValue result = Value().New(args); +#ifdef NODE_ADDON_API_ENABLE_MAYBE + if (result.IsJust()) { + return Just(scope.Escape(result.Unwrap()).As()); + } + return result; +#else + if (scope.Env().IsExceptionPending()) { + return Object(); + } + return scope.Escape(result).As(); +#endif +} + +//////////////////////////////////////////////////////////////////////////////// +// CallbackInfo class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info) + : _env(env), + _info(info), + _this(nullptr), + _dynamicArgs(nullptr), + _data(nullptr) { + _argc = _staticArgCount; + _argv = _staticArgs; + napi_status status = + napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + if (_argc > _staticArgCount) { + // Use either a fixed-size array (on the stack) or a dynamically-allocated + // array (on the heap) depending on the number of args. + _dynamicArgs = new napi_value[_argc]; + _argv = _dynamicArgs; + + status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +inline CallbackInfo::~CallbackInfo() { + if (_dynamicArgs != nullptr) { + delete[] _dynamicArgs; + } +} + +inline CallbackInfo::operator napi_callback_info() const { + return _info; +} + +inline Value CallbackInfo::NewTarget() const { + napi_value newTarget; + napi_status status = napi_get_new_target(_env, _info, &newTarget); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, newTarget); +} + +inline bool CallbackInfo::IsConstructCall() const { + return !NewTarget().IsEmpty(); +} + +inline Napi::Env CallbackInfo::Env() const { + return Napi::Env(_env); +} + +inline size_t CallbackInfo::Length() const { + return _argc; +} + +inline const Value CallbackInfo::operator[](size_t index) const { + return index < _argc ? Value(_env, _argv[index]) : Env().Undefined(); +} + +inline Value CallbackInfo::This() const { + if (_this == nullptr) { + return Env().Undefined(); + } + return Object(_env, _this); +} + +inline void* CallbackInfo::Data() const { + return _data; +} + +inline void CallbackInfo::SetData(void* data) { + _data = data; +} + +//////////////////////////////////////////////////////////////////////////////// +// PropertyDescriptor class +//////////////////////////////////////////////////////////////////////////////// + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), attributes, data); +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + Name name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.setter = details::TemplatedVoidCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + const std::string& utf8name, + napi_property_attributes attributes, + void* data) { + return Accessor(utf8name.c_str(), attributes, data); +} + +template +PropertyDescriptor PropertyDescriptor::Accessor( + Name name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.setter = details::TemplatedVoidCallback; + desc.attributes = attributes; + desc.data = data; + + return desc; +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + using CbData = details::CallbackData; + auto callbackData = new CbData({getter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(env, object, utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes, + void* data) { + using CbData = details::CallbackData; + auto callbackData = new CbData({getter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + using CbData = details::AccessorCallbackData; + auto callbackData = new CbData({getter, setter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor( + env, object, utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + using CbData = details::AccessorCallbackData; + auto callbackData = new CbData({getter, setter, data}); + + napi_status status = AttachData(env, object, callbackData); + if (status != napi_ok) { + delete callbackData; + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + } + + return PropertyDescriptor({nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object /*object*/, + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, utf8name, data), + attributes, + nullptr}); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(env, object, utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function( + Napi::Env env, + Napi::Object /*object*/, + Name name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({nullptr, + name, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, nullptr, data), + attributes, + nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + const char* utf8name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + value, + attributes, + nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + const std::string& utf8name, + napi_value value, + napi_property_attributes attributes) { + return Value(utf8name.c_str(), value, attributes); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + napi_value name, napi_value value, napi_property_attributes attributes) { + return PropertyDescriptor( + {nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr}); +} + +inline PropertyDescriptor PropertyDescriptor::Value( + Name name, Napi::Value value, napi_property_attributes attributes) { + napi_value nameValue = name; + napi_value valueValue = value; + return PropertyDescriptor::Value(nameValue, valueValue, attributes); +} + +inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc) + : _desc(desc) {} + +inline PropertyDescriptor::operator napi_property_descriptor&() { + return _desc; +} + +inline PropertyDescriptor::operator const napi_property_descriptor&() const { + return _desc; +} + +//////////////////////////////////////////////////////////////////////////////// +// InstanceWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline void InstanceWrap::AttachPropData( + napi_env env, napi_value value, const napi_property_descriptor* prop) { + napi_status status; + if (!(prop->attributes & napi_static)) { + if (prop->method == T::InstanceVoidMethodCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } else if (prop->method == T::InstanceMethodCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } else if (prop->getter == T::InstanceGetterCallbackWrapper || + prop->setter == T::InstanceSetterCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED_VOID(env, status); + } + } +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = + new InstanceMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = + new InstanceMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceVoidMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedInstanceVoidCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedInstanceCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceVoidMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedInstanceVoidCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceMethodCallback method> +inline ClassPropertyDescriptor InstanceWrap::InstanceMethod( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedInstanceCallback; + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceGetterCallback getter, + typename InstanceWrap::InstanceSetterCallback setter> +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = details::TemplatedInstanceCallback; + desc.setter = This::WrapSetter(This::SetterTag()); + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +template ::InstanceGetterCallback getter, + typename InstanceWrap::InstanceSetterCallback setter> +inline ClassPropertyDescriptor InstanceWrap::InstanceAccessor( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = details::TemplatedInstanceCallback; + desc.setter = This::WrapSetter(This::SetterTag()); + desc.data = data; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor InstanceWrap::InstanceValue( + Symbol name, Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline napi_value InstanceWrap::InstanceVoidMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + if (instance) (instance->*cb)(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value InstanceWrap::InstanceMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); + }); +} + +template +inline napi_value InstanceWrap::InstanceGetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->getterCallback; + return instance ? (instance->*cb)(callbackInfo) : Napi::Value(); + }); +} + +template +inline napi_value InstanceWrap::InstanceSetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = T::Unwrap(callbackInfo.This().As()); + auto cb = callbackData->setterCallback; + if (instance) (instance->*cb)(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +template ::InstanceSetterCallback method> +inline napi_value InstanceWrap::WrappedMethod( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + const CallbackInfo cbInfo(env, info); + T* instance = T::Unwrap(cbInfo.This().As()); + if (instance) (instance->*method)(cbInfo, cbInfo[0]); + return nullptr; + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline ObjectWrap::ObjectWrap(const Napi::CallbackInfo& callbackInfo) { + napi_env env = callbackInfo.Env(); + napi_value wrapper = callbackInfo.This(); + napi_status status; + napi_ref ref; + T* instance = static_cast(this); + status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); + NAPI_THROW_IF_FAILED_VOID(env, status); + + Reference* instanceRef = instance; + *instanceRef = Reference(env, ref); +} + +template +inline ObjectWrap::~ObjectWrap() { + // If the JS object still exists at this point, remove the finalizer added + // through `napi_wrap()`. + if (!IsEmpty()) { + Object object = Value(); + // It is not valid to call `napi_remove_wrap()` with an empty `object`. + // This happens e.g. during garbage collection. + if (!object.IsEmpty() && _construction_failed) { + napi_remove_wrap(Env(), object, nullptr); + } + } +} + +template +inline T* ObjectWrap::Unwrap(Object wrapper) { + void* unwrapped; + napi_status status = napi_unwrap(wrapper.Env(), wrapper, &unwrapped); + NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); + return static_cast(unwrapped); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* descriptors, + void* data) { + napi_status status; + std::vector props(props_count); + + // We copy the descriptors to a local array because before defining the class + // we must replace static method property descriptors with value property + // descriptors such that the value is a function-valued `napi_value` created + // with `CreateFunction()`. + // + // This replacement could be made for instance methods as well, but V8 aborts + // if we do that, because it expects methods defined on the prototype template + // to have `FunctionTemplate`s. + for (size_t index = 0; index < props_count; index++) { + props[index] = descriptors[index]; + napi_property_descriptor* prop = &props[index]; + if (prop->method == T::StaticMethodCallbackWrapper) { + status = + CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } else if (prop->method == T::StaticVoidMethodCallbackWrapper) { + status = + CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } + } + + napi_value value; + status = napi_define_class(env, + utf8name, + NAPI_AUTO_LENGTH, + T::ConstructorCallbackWrapper, + data, + props_count, + props.data(), + &value); + NAPI_THROW_IF_FAILED(env, status, Function()); + + // After defining the class we iterate once more over the property descriptors + // and attach the data associated with accessors and instance methods to the + // newly created JavaScript class. + for (size_t idx = 0; idx < props_count; idx++) { + const napi_property_descriptor* prop = &props[idx]; + + if (prop->getter == T::StaticGetterCallbackWrapper || + prop->setter == T::StaticSetterCallbackWrapper) { + status = Napi::details::AttachData( + env, value, static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } else { + // InstanceWrap::AttachPropData is responsible for attaching the data + // of instance methods and accessors. + T::AttachPropData(env, value, prop); + } + } + + return Function(env, value); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list>& properties, + void* data) { + return DefineClass( + env, + utf8name, + properties.size(), + reinterpret_cast(properties.begin()), + data); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::vector>& properties, + void* data) { + return DefineClass( + env, + utf8name, + properties.size(), + reinterpret_cast(properties.data()), + data); +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = + new StaticVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = + new StaticMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = + new StaticVoidMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = + new StaticMethodCallbackData({method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticVoidMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedVoidCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticVoidMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedVoidCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = details::TemplatedCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticMethodCallback method> +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = details::TemplatedCallback; + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({getter, setter, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticGetterCallback getter, + typename ObjectWrap::StaticSetterCallback setter> +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = details::TemplatedCallback; + desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +template ::StaticGetterCallback getter, + typename ObjectWrap::StaticSetterCallback setter> +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, napi_property_attributes attributes, void* data) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = details::TemplatedCallback; + desc.setter = This::WrapStaticSetter(This::StaticSetterTag()); + desc.data = data; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue( + Symbol name, Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = + static_cast(attributes | napi_static); + return desc; +} + +template +inline Value ObjectWrap::OnCalledAsFunction( + const Napi::CallbackInfo& callbackInfo) { + NAPI_THROW( + TypeError::New(callbackInfo.Env(), + "Class constructors cannot be invoked without 'new'"), + Napi::Value()); +} + +template +inline void ObjectWrap::Finalize(Napi::Env /*env*/) {} + +template +inline napi_value ObjectWrap::ConstructorCallbackWrapper( + napi_env env, napi_callback_info info) { + napi_value new_target; + napi_status status = napi_get_new_target(env, info, &new_target); + if (status != napi_ok) return nullptr; + + bool isConstructCall = (new_target != nullptr); + if (!isConstructCall) { + return details::WrapCallback( + [&] { return T::OnCalledAsFunction(CallbackInfo(env, info)); }); + } + + napi_value wrapper = details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + T* instance = new T(callbackInfo); +#ifdef NAPI_CPP_EXCEPTIONS + instance->_construction_failed = false; +#else + if (callbackInfo.Env().IsExceptionPending()) { + // We need to clear the exception so that removing the wrap might work. + Error e = callbackInfo.Env().GetAndClearPendingException(); + delete instance; + e.ThrowAsJavaScriptException(); + } else { + instance->_construction_failed = false; + } +#endif // NAPI_CPP_EXCEPTIONS + return callbackInfo.This(); + }); + + return wrapper; +} + +template +inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value ObjectWrap::StaticMethodCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticGetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticSetterCallbackWrapper( + napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +inline void ObjectWrap::FinalizeCallback(napi_env env, + void* data, + void* /*hint*/) { + HandleScope scope(env); + T* instance = static_cast(data); + instance->Finalize(Napi::Env(env)); + delete instance; +} + +template +template ::StaticSetterCallback method> +inline napi_value ObjectWrap::WrappedMethod( + napi_env env, napi_callback_info info) NAPI_NOEXCEPT { + return details::WrapCallback([&] { + const CallbackInfo cbInfo(env, info); + method(cbInfo, cbInfo[0]); + return nullptr; + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// HandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope) + : _env(env), _scope(scope) {} + +inline HandleScope::HandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline HandleScope::~HandleScope() { + napi_status status = napi_close_handle_scope(_env, _scope); + NAPI_FATAL_IF_FAILED( + status, "HandleScope::~HandleScope", "napi_close_handle_scope"); +} + +inline HandleScope::operator napi_handle_scope() const { + return _scope; +} + +inline Napi::Env HandleScope::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// EscapableHandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline EscapableHandleScope::EscapableHandleScope( + napi_env env, napi_escapable_handle_scope scope) + : _env(env), _scope(scope) {} + +inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_escapable_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline EscapableHandleScope::~EscapableHandleScope() { + napi_status status = napi_close_escapable_handle_scope(_env, _scope); + NAPI_FATAL_IF_FAILED(status, + "EscapableHandleScope::~EscapableHandleScope", + "napi_close_escapable_handle_scope"); +} + +inline EscapableHandleScope::operator napi_escapable_handle_scope() const { + return _scope; +} + +inline Napi::Env EscapableHandleScope::Env() const { + return Napi::Env(_env); +} + +inline Value EscapableHandleScope::Escape(napi_value escapee) { + napi_value result; + napi_status status = napi_escape_handle(_env, _scope, escapee, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +#if (NAPI_VERSION > 2) +//////////////////////////////////////////////////////////////////////////////// +// CallbackScope class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope) + : _env(env), _scope(scope) {} + +inline CallbackScope::CallbackScope(napi_env env, napi_async_context context) + : _env(env) { + napi_status status = + napi_open_callback_scope(_env, Object::New(env), context, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline CallbackScope::~CallbackScope() { + napi_status status = napi_close_callback_scope(_env, _scope); + NAPI_FATAL_IF_FAILED( + status, "CallbackScope::~CallbackScope", "napi_close_callback_scope"); +} + +inline CallbackScope::operator napi_callback_scope() const { + return _scope; +} + +inline Napi::Env CallbackScope::Env() const { + return Napi::Env(_env); +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// AsyncContext class +//////////////////////////////////////////////////////////////////////////////// + +inline AsyncContext::AsyncContext(napi_env env, const char* resource_name) + : AsyncContext(env, resource_name, Object::New(env)) {} + +inline AsyncContext::AsyncContext(napi_env env, + const char* resource_name, + const Object& resource) + : _env(env), _context(nullptr) { + napi_value resource_id; + napi_status status = napi_create_string_utf8( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_async_init(_env, resource, resource_id, &_context); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncContext::~AsyncContext() { + if (_context != nullptr) { + napi_async_destroy(_env, _context); + _context = nullptr; + } +} + +inline AsyncContext::AsyncContext(AsyncContext&& other) { + _env = other._env; + other._env = nullptr; + _context = other._context; + other._context = nullptr; +} + +inline AsyncContext& AsyncContext::operator=(AsyncContext&& other) { + _env = other._env; + other._env = nullptr; + _context = other._context; + other._context = nullptr; + return *this; +} + +inline AsyncContext::operator napi_async_context() const { + return _context; +} + +inline Napi::Env AsyncContext::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// AsyncWorker class +//////////////////////////////////////////////////////////////////////////////// + +#if NAPI_HAS_THREADS + +inline AsyncWorker::AsyncWorker(const Function& callback) + : AsyncWorker(callback, "generic") {} + +inline AsyncWorker::AsyncWorker(const Function& callback, + const char* resource_name) + : AsyncWorker(callback, resource_name, Object::New(callback.Env())) {} + +inline AsyncWorker::AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback) + : AsyncWorker(receiver, callback, "generic") {} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} + +inline AsyncWorker::AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : _env(callback.Env()), + _receiver(Napi::Persistent(receiver)), + _callback(Napi::Persistent(callback)), + _suppress_destruct(false) { + napi_value resource_id; + napi_status status = napi_create_string_latin1( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_create_async_work(_env, + resource, + resource_id, + OnAsyncWorkExecute, + OnAsyncWorkComplete, + this, + &_work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncWorker::AsyncWorker(Napi::Env env) : AsyncWorker(env, "generic") {} + +inline AsyncWorker::AsyncWorker(Napi::Env env, const char* resource_name) + : AsyncWorker(env, resource_name, Object::New(env)) {} + +inline AsyncWorker::AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : _env(env), _receiver(), _callback(), _suppress_destruct(false) { + napi_value resource_id; + napi_status status = napi_create_string_latin1( + _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + status = napi_create_async_work(_env, + resource, + resource_id, + OnAsyncWorkExecute, + OnAsyncWorkComplete, + this, + &_work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline AsyncWorker::~AsyncWorker() { + if (_work != nullptr) { + napi_delete_async_work(_env, _work); + _work = nullptr; + } +} + +inline void AsyncWorker::Destroy() { + delete this; +} + +inline AsyncWorker::operator napi_async_work() const { + return _work; +} + +inline Napi::Env AsyncWorker::Env() const { + return Napi::Env(_env); +} + +inline void AsyncWorker::Queue() { + napi_status status = napi_queue_async_work(_env, _work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void AsyncWorker::Cancel() { + napi_status status = napi_cancel_async_work(_env, _work); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline ObjectReference& AsyncWorker::Receiver() { + return _receiver; +} + +inline FunctionReference& AsyncWorker::Callback() { + return _callback; +} + +inline void AsyncWorker::SuppressDestruct() { + _suppress_destruct = true; +} + +inline void AsyncWorker::OnOK() { + if (!_callback.IsEmpty()) { + _callback.Call(_receiver.Value(), GetResult(_callback.Env())); + } +} + +inline void AsyncWorker::OnError(const Error& e) { + if (!_callback.IsEmpty()) { + _callback.Call(_receiver.Value(), + std::initializer_list{e.Value()}); + } +} + +inline void AsyncWorker::SetError(const std::string& error) { + _error = error; +} + +inline std::vector AsyncWorker::GetResult(Napi::Env /*env*/) { + return {}; +} +// The OnAsyncWorkExecute method receives an napi_env argument. However, do NOT +// use it within this method, as it does not run on the JavaScript thread and +// must not run any method that would cause JavaScript to run. In practice, +// this means that almost any use of napi_env will be incorrect. +inline void AsyncWorker::OnAsyncWorkExecute(napi_env env, void* asyncworker) { + AsyncWorker* self = static_cast(asyncworker); + self->OnExecute(env); +} +// The OnExecute method receives an napi_env argument. However, do NOT +// use it within this method, as it does not run on the JavaScript thread and +// must not run any method that would cause JavaScript to run. In practice, +// this means that almost any use of napi_env will be incorrect. +inline void AsyncWorker::OnExecute(Napi::Env /*DO_NOT_USE*/) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + Execute(); + } catch (const std::exception& e) { + SetError(e.what()); + } +#else // NAPI_CPP_EXCEPTIONS + Execute(); +#endif // NAPI_CPP_EXCEPTIONS +} + +inline void AsyncWorker::OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker) { + AsyncWorker* self = static_cast(asyncworker); + self->OnWorkComplete(env, status); +} +inline void AsyncWorker::OnWorkComplete(Napi::Env /*env*/, napi_status status) { + if (status != napi_cancelled) { + HandleScope scope(_env); + details::WrapCallback([&] { + if (_error.size() == 0) { + OnOK(); + } else { + OnError(Error::New(_env, _error)); + } + return nullptr; + }); + } + if (!_suppress_destruct) { + Destroy(); + } +} + +#endif // NAPI_HAS_THREADS + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) +//////////////////////////////////////////////////////////////////////////////// +// TypedThreadSafeFunction class +//////////////////////////////////////////////////////////////////////////////// + +// Starting with NAPI 5, the JavaScript function `func` parameter of +// `napi_create_threadsafe_function` is optional. +#if NAPI_VERSION > 4 +// static, with Callback [missing] Resource [missing] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [passed] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [missing] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + nullptr, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [missing] Resource [passed] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + nullptr, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} +#endif + +// static, with Callback [passed] Resource [missing] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [passed] Resource [passed] Finalizer [missing] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + TypedThreadSafeFunction tsfn; + + napi_status status = + napi_create_threadsafe_function(env, + callback, + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + nullptr, + nullptr, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with Callback [passed] Resource [missing] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + callback, + nullptr, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +// static, with: Callback [passed] Resource [passed] Finalizer [passed] +template +template +inline TypedThreadSafeFunction +TypedThreadSafeFunction::New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + TypedThreadSafeFunction tsfn; + + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = napi_create_threadsafe_function( + env, + details::DefaultCallbackWrapper< + CallbackType, + TypedThreadSafeFunction>(env, + callback), + resource, + String::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext, + context, + CallJsInternal, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED( + env, status, TypedThreadSafeFunction()); + } + + return tsfn; +} + +template +inline TypedThreadSafeFunction:: + TypedThreadSafeFunction() + : _tsfn() {} + +template +inline TypedThreadSafeFunction:: + TypedThreadSafeFunction(napi_threadsafe_function tsfn) + : _tsfn(tsfn) {} + +template +inline TypedThreadSafeFunction:: +operator napi_threadsafe_function() const { + return _tsfn; +} + +template +inline napi_status +TypedThreadSafeFunction::BlockingCall( + DataType* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); +} + +template +inline napi_status +TypedThreadSafeFunction::NonBlockingCall( + DataType* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); +} + +template +inline void TypedThreadSafeFunction::Ref( + napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_ref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +template +inline void TypedThreadSafeFunction::Unref( + napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_unref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +template +inline napi_status +TypedThreadSafeFunction::Acquire() const { + return napi_acquire_threadsafe_function(_tsfn); +} + +template +inline napi_status +TypedThreadSafeFunction::Release() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); +} + +template +inline napi_status +TypedThreadSafeFunction::Abort() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); +} + +template +inline ContextType* +TypedThreadSafeFunction::GetContext() const { + void* context; + napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); + NAPI_FATAL_IF_FAILED(status, + "TypedThreadSafeFunction::GetContext", + "napi_get_threadsafe_function_context"); + return static_cast(context); +} + +// static +template +void TypedThreadSafeFunction::CallJsInternal( + napi_env env, napi_value jsCallback, void* context, void* data) { + details::CallJsWrapper( + env, jsCallback, context, data); +} + +#if NAPI_VERSION == 4 +// static +template +Napi::Function +TypedThreadSafeFunction::EmptyFunctionFactory( + Napi::Env env) { + return Napi::Function::New(env, [](const CallbackInfo& cb) {}); +} + +// static +template +Napi::Function +TypedThreadSafeFunction::FunctionOrEmpty( + Napi::Env env, Napi::Function& callback) { + if (callback.IsEmpty()) { + return EmptyFunctionFactory(env); + } + return callback; +} + +#else +// static +template +std::nullptr_t +TypedThreadSafeFunction::EmptyFunctionFactory( + Napi::Env /*env*/) { + return nullptr; +} + +// static +template +Napi::Function +TypedThreadSafeFunction::FunctionOrEmpty( + Napi::Env /*env*/, Napi::Function& callback) { + return callback; +} + +#endif + +//////////////////////////////////////////////////////////////////////////////// +// ThreadSafeFunction class +//////////////////////////////////////////////////////////////////////////////// + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New( + env, callback, Object(), resourceName, maxQueueSize, initialThreadCount); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + finalizeCallback); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + finalizeCallback, + data); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + Object(), + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + data); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + [](Env, ContextType*) {} /* empty finalizer */); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */, + finalizeCallback, + static_cast(nullptr) /* data */, + details::ThreadSafeFinalize::Wrapper); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New(env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + static_cast(nullptr) /* context */, + finalizeCallback, + data, + details::ThreadSafeFinalize:: + FinalizeWrapperWithData); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback) { + return New( + env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + static_cast(nullptr) /* data */, + details::ThreadSafeFinalize::FinalizeWrapperWithContext); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data) { + return New( + env, + callback, + resource, + resourceName, + maxQueueSize, + initialThreadCount, + context, + finalizeCallback, + data, + details::ThreadSafeFinalize:: + FinalizeFinalizeWrapperWithDataAndContext); +} + +inline ThreadSafeFunction::ThreadSafeFunction() : _tsfn() {} + +inline ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn) + : _tsfn(tsfn) {} + +inline ThreadSafeFunction::operator napi_threadsafe_function() const { + return _tsfn; +} + +inline napi_status ThreadSafeFunction::BlockingCall() const { + return CallInternal(nullptr, napi_tsfn_blocking); +} + +template <> +inline napi_status ThreadSafeFunction::BlockingCall(void* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_blocking); +} + +template +inline napi_status ThreadSafeFunction::BlockingCall(Callback callback) const { + return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking); +} + +template +inline napi_status ThreadSafeFunction::BlockingCall(DataType* data, + Callback callback) const { + auto wrapper = [data, callback](Env env, Function jsCallback) { + callback(env, jsCallback, data); + }; + return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_blocking); +} + +inline napi_status ThreadSafeFunction::NonBlockingCall() const { + return CallInternal(nullptr, napi_tsfn_nonblocking); +} + +template <> +inline napi_status ThreadSafeFunction::NonBlockingCall(void* data) const { + return napi_call_threadsafe_function(_tsfn, data, napi_tsfn_nonblocking); +} + +template +inline napi_status ThreadSafeFunction::NonBlockingCall( + Callback callback) const { + return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking); +} + +template +inline napi_status ThreadSafeFunction::NonBlockingCall( + DataType* data, Callback callback) const { + auto wrapper = [data, callback](Env env, Function jsCallback) { + callback(env, jsCallback, data); + }; + return CallInternal(new CallbackWrapper(wrapper), napi_tsfn_nonblocking); +} + +inline void ThreadSafeFunction::Ref(napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_ref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +inline void ThreadSafeFunction::Unref(napi_env env) const { + if (_tsfn != nullptr) { + napi_status status = napi_unref_threadsafe_function(env, _tsfn); + NAPI_THROW_IF_FAILED_VOID(env, status); + } +} + +inline napi_status ThreadSafeFunction::Acquire() const { + return napi_acquire_threadsafe_function(_tsfn); +} + +inline napi_status ThreadSafeFunction::Release() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); +} + +inline napi_status ThreadSafeFunction::Abort() const { + return napi_release_threadsafe_function(_tsfn, napi_tsfn_abort); +} + +inline ThreadSafeFunction::ConvertibleContext ThreadSafeFunction::GetContext() + const { + void* context; + napi_status status = napi_get_threadsafe_function_context(_tsfn, &context); + NAPI_FATAL_IF_FAILED(status, + "ThreadSafeFunction::GetContext", + "napi_get_threadsafe_function_context"); + return ConvertibleContext({context}); +} + +// static +template +inline ThreadSafeFunction ThreadSafeFunction::New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper) { + static_assert(details::can_make_string::value || + std::is_convertible::value, + "Resource name should be convertible to the string type"); + + ThreadSafeFunction tsfn; + auto* finalizeData = new details:: + ThreadSafeFinalize( + {data, finalizeCallback}); + napi_status status = + napi_create_threadsafe_function(env, + callback, + resource, + Value::From(env, resourceName), + maxQueueSize, + initialThreadCount, + finalizeData, + wrapper, + context, + CallJS, + &tsfn._tsfn); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ThreadSafeFunction()); + } + + return tsfn; +} + +inline napi_status ThreadSafeFunction::CallInternal( + CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const { + napi_status status = + napi_call_threadsafe_function(_tsfn, callbackWrapper, mode); + if (status != napi_ok && callbackWrapper != nullptr) { + delete callbackWrapper; + } + + return status; +} + +// static +inline void ThreadSafeFunction::CallJS(napi_env env, + napi_value jsCallback, + void* /* context */, + void* data) { + if (env == nullptr && jsCallback == nullptr) { + return; + } + + details::WrapVoidCallback([&]() { + if (data != nullptr) { + auto* callbackWrapper = static_cast(data); + (*callbackWrapper)(env, Function(env, jsCallback)); + delete callbackWrapper; + } else if (jsCallback != nullptr) { + Function(env, jsCallback).Call({}); + } + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Worker Base class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( + const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(receiver, callback, resource_name, resource) { + // Fill all possible arguments to work around ambiguous + // ThreadSafeFunction::New signatures. + _tsfn = ThreadSafeFunction::New(callback.Env(), + callback, + resource, + resource_name, + queue_size, + /** initialThreadCount */ 1, + /** context */ this, + OnThreadSafeFunctionFinalize, + /** finalizeData */ this); +} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressWorkerBase::AsyncProgressWorkerBase( + Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size) + : AsyncWorker(env, resource_name, resource) { + // TODO: Once the changes to make the callback optional for threadsafe + // functions are available on all versions we can remove the dummy Function + // here. + Function callback; + // Fill all possible arguments to work around ambiguous + // ThreadSafeFunction::New signatures. + _tsfn = ThreadSafeFunction::New(env, + callback, + resource, + resource_name, + queue_size, + /** initialThreadCount */ 1, + /** context */ this, + OnThreadSafeFunctionFinalize, + /** finalizeData */ this); +} +#endif + +template +inline AsyncProgressWorkerBase::~AsyncProgressWorkerBase() { + // Abort pending tsfn call. + // Don't send progress events after we've already completed. + // It's ok to call ThreadSafeFunction::Abort and ThreadSafeFunction::Release + // duplicated. + _tsfn.Abort(); +} + +template +inline void AsyncProgressWorkerBase::OnAsyncWorkProgress( + Napi::Env /* env */, Napi::Function /* jsCallback */, void* data) { + ThreadSafeData* tsd = static_cast(data); + tsd->asyncprogressworker()->OnWorkProgress(tsd->data()); + delete tsd; +} + +template +inline napi_status AsyncProgressWorkerBase::NonBlockingCall( + DataType* data) { + auto tsd = new AsyncProgressWorkerBase::ThreadSafeData(this, data); + auto ret = _tsfn.NonBlockingCall(tsd, OnAsyncWorkProgress); + if (ret != napi_ok) { + delete tsd; + } + return ret; +} + +template +inline void AsyncProgressWorkerBase::OnWorkComplete( + Napi::Env /* env */, napi_status status) { + _work_completed = true; + _complete_status = status; + _tsfn.Release(); +} + +template +inline void AsyncProgressWorkerBase::OnThreadSafeFunctionFinalize( + Napi::Env env, void* /* data */, AsyncProgressWorkerBase* context) { + if (context->_work_completed) { + context->AsyncWorker::OnWorkComplete(env, context->_complete_status); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Worker class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback) + : AsyncProgressWorker(callback, "generic") {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, + const char* resource_name) + : AsyncProgressWorker( + callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback) + : AsyncProgressWorker(receiver, callback, "generic") {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name) + : AsyncProgressWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase(receiver, callback, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0), + _signaled(false) {} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env) + : AsyncProgressWorker(env, "generic") {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, + const char* resource_name) + : AsyncProgressWorker(env, resource_name, Object::New(env)) {} + +template +inline AsyncProgressWorker::AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase(env, resource_name, resource), + _asyncdata(nullptr), + _asyncsize(0) {} +#endif + +template +inline AsyncProgressWorker::~AsyncProgressWorker() { + { + std::lock_guard lock(this->_mutex); + _asyncdata = nullptr; + _asyncsize = 0; + } +} + +template +inline void AsyncProgressWorker::Execute() { + ExecutionProgress progress(this); + Execute(progress); +} + +template +inline void AsyncProgressWorker::OnWorkProgress(void*) { + T* data; + size_t size; + bool signaled; + { + std::lock_guard lock(this->_mutex); + data = this->_asyncdata; + size = this->_asyncsize; + signaled = this->_signaled; + this->_asyncdata = nullptr; + this->_asyncsize = 0; + this->_signaled = false; + } + + /** + * The callback of ThreadSafeFunction is not been invoked immediately on the + * callback of uv_async_t (uv io poll), rather the callback of TSFN is + * invoked on the right next uv idle callback. There are chances that during + * the deferring the signal of uv_async_t is been sent again, i.e. potential + * not coalesced two calls of the TSFN callback. + */ + if (data == nullptr && !signaled) { + return; + } + + this->OnProgress(data, size); + delete[] data; +} + +template +inline void AsyncProgressWorker::SendProgress_(const T* data, size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + T* old_data; + { + std::lock_guard lock(this->_mutex); + old_data = _asyncdata; + _asyncdata = new_data; + _asyncsize = count; + _signaled = false; + } + this->NonBlockingCall(nullptr); + + delete[] old_data; +} + +template +inline void AsyncProgressWorker::Signal() { + { + std::lock_guard lock(this->_mutex); + _signaled = true; + } + this->NonBlockingCall(static_cast(nullptr)); +} + +template +inline void AsyncProgressWorker::ExecutionProgress::Signal() const { + this->_worker->Signal(); +} + +template +inline void AsyncProgressWorker::ExecutionProgress::Send( + const T* data, size_t count) const { + _worker->SendProgress_(data, count); +} + +//////////////////////////////////////////////////////////////////////////////// +// Async Progress Queue Worker class +//////////////////////////////////////////////////////////////////////////////// +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback) + : AsyncProgressQueueWorker(callback, "generic") {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback, const char* resource_name) + : AsyncProgressQueueWorker( + callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Function& callback, const char* resource_name, const Object& resource) + : AsyncProgressQueueWorker( + Object::New(callback.Env()), callback, resource_name, resource) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, const Function& callback) + : AsyncProgressQueueWorker(receiver, callback, "generic") {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, const Function& callback, const char* resource_name) + : AsyncProgressQueueWorker( + receiver, callback, resource_name, Object::New(callback.Env())) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource) + : AsyncProgressWorkerBase>( + receiver, + callback, + resource_name, + resource, + /** unlimited queue size */ 0) {} + +#if NAPI_VERSION > 4 +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker(Napi::Env env) + : AsyncProgressQueueWorker(env, "generic") {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + Napi::Env env, const char* resource_name) + : AsyncProgressQueueWorker(env, resource_name, Object::New(env)) {} + +template +inline AsyncProgressQueueWorker::AsyncProgressQueueWorker( + Napi::Env env, const char* resource_name, const Object& resource) + : AsyncProgressWorkerBase>( + env, resource_name, resource, /** unlimited queue size */ 0) {} +#endif + +template +inline void AsyncProgressQueueWorker::Execute() { + ExecutionProgress progress(this); + Execute(progress); +} + +template +inline void AsyncProgressQueueWorker::OnWorkProgress( + std::pair* datapair) { + if (datapair == nullptr) { + return; + } + + T* data = datapair->first; + size_t size = datapair->second; + + this->OnProgress(data, size); + delete datapair; + delete[] data; +} + +template +inline void AsyncProgressQueueWorker::SendProgress_(const T* data, + size_t count) { + T* new_data = new T[count]; + std::copy(data, data + count, new_data); + + auto pair = new std::pair(new_data, count); + this->NonBlockingCall(pair); +} + +template +inline void AsyncProgressQueueWorker::Signal() const { + this->SendProgress_(static_cast(nullptr), 0); +} + +template +inline void AsyncProgressQueueWorker::OnWorkComplete(Napi::Env env, + napi_status status) { + // Draining queued items in TSFN. + AsyncProgressWorkerBase>::OnWorkComplete(env, status); +} + +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Signal() const { + _worker->SendProgress_(static_cast(nullptr), 0); +} + +template +inline void AsyncProgressQueueWorker::ExecutionProgress::Send( + const T* data, size_t count) const { + _worker->SendProgress_(data, count); +} +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS + +//////////////////////////////////////////////////////////////////////////////// +// Memory Management class +//////////////////////////////////////////////////////////////////////////////// + +inline int64_t MemoryManagement::AdjustExternalMemory(Env env, + int64_t change_in_bytes) { + int64_t result; + napi_status status = + napi_adjust_external_memory(env, change_in_bytes, &result); + NAPI_THROW_IF_FAILED(env, status, 0); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Version Management class +//////////////////////////////////////////////////////////////////////////////// + +inline uint32_t VersionManagement::GetNapiVersion(Env env) { + uint32_t result; + napi_status status = napi_get_version(env, &result); + NAPI_THROW_IF_FAILED(env, status, 0); + return result; +} + +inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) { + const napi_node_version* result; + napi_status status = napi_get_node_version(env, &result); + NAPI_THROW_IF_FAILED(env, status, 0); + return result; +} + +#if NAPI_VERSION > 5 +//////////////////////////////////////////////////////////////////////////////// +// Addon class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object Addon::Init(Env env, Object exports) { + T* addon = new T(env, exports); + env.SetInstanceData(addon); + return addon->entry_point_; +} + +template +inline T* Addon::Unwrap(Object wrapper) { + return wrapper.Env().GetInstanceData(); +} + +template +inline void Addon::DefineAddon( + Object exports, const std::initializer_list& props) { + DefineProperties(exports, props); + entry_point_ = exports; +} + +template +inline Napi::Object Addon::DefineProperties( + Object object, const std::initializer_list& props) { + const napi_property_descriptor* properties = + reinterpret_cast(props.begin()); + size_t size = props.size(); + napi_status status = + napi_define_properties(object.Env(), object, size, properties); + NAPI_THROW_IF_FAILED(object.Env(), status, object); + for (size_t idx = 0; idx < size; idx++) + T::AttachPropData(object.Env(), object, &properties[idx]); + return object; +} +#endif // NAPI_VERSION > 5 + +#if NAPI_VERSION > 2 +template +Env::CleanupHook Env::AddCleanupHook(Hook hook, Arg* arg) { + return CleanupHook(*this, hook, arg); +} + +template +Env::CleanupHook Env::AddCleanupHook(Hook hook) { + return CleanupHook(*this, hook); +} + +template +Env::CleanupHook::CleanupHook() { + data = nullptr; +} + +template +Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook) + : wrapper(Env::CleanupHook::Wrapper) { + data = new CleanupData{std::move(hook), nullptr}; + napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); + if (status != napi_ok) { + delete data; + data = nullptr; + } +} + +template +Env::CleanupHook::CleanupHook(Napi::Env env, Hook hook, Arg* arg) + : wrapper(Env::CleanupHook::WrapperWithArg) { + data = new CleanupData{std::move(hook), arg}; + napi_status status = napi_add_env_cleanup_hook(env, wrapper, data); + if (status != napi_ok) { + delete data; + data = nullptr; + } +} + +template +bool Env::CleanupHook::Remove(Env env) { + napi_status status = napi_remove_env_cleanup_hook(env, wrapper, data); + delete data; + data = nullptr; + return status == napi_ok; +} + +template +bool Env::CleanupHook::IsEmpty() const { + return data == nullptr; +} +#endif // NAPI_VERSION > 2 + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +} // namespace NAPI_CPP_CUSTOM_NAMESPACE +#endif + +} // namespace Napi + +#endif // SRC_NAPI_INL_H_ diff --git a/tools/ui/node_modules/node-addon-api/napi.h b/tools/ui/node_modules/node-addon-api/napi.h new file mode 100644 index 0000000000000000000000000000000000000000..9f20cb884ab2a163cc727f814445fc4c2859ab45 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/napi.h @@ -0,0 +1,3201 @@ +#ifndef SRC_NAPI_H_ +#define SRC_NAPI_H_ + +#ifndef NAPI_HAS_THREADS +#if !defined(__wasm__) || (defined(__EMSCRIPTEN_PTHREADS__) || \ + (defined(__wasi__) && defined(_REENTRANT))) +#define NAPI_HAS_THREADS 1 +#else +#define NAPI_HAS_THREADS 0 +#endif +#endif + +#include +#include +#include +#include +#if NAPI_HAS_THREADS +#include +#endif // NAPI_HAS_THREADS +#include +#include + +// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known +// good version) +#if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210 +#define NAPI_HAS_CONSTEXPR 1 +#endif + +// VS2013 does not support char16_t literal strings, so we'll work around it +// using wchar_t strings and casting them. This is safe as long as the character +// sizes are the same. +#if defined(_MSC_VER) && _MSC_VER <= 1800 +static_assert(sizeof(char16_t) == sizeof(wchar_t), + "Size mismatch between char16_t and wchar_t"); +#define NAPI_WIDE_TEXT(x) reinterpret_cast(L##x) +#else +#define NAPI_WIDE_TEXT(x) u##x +#endif + +// If C++ exceptions are not explicitly enabled or disabled, enable them +// if exceptions were enabled in the compiler settings. +#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS) +#if defined(_CPPUNWIND) || defined(__EXCEPTIONS) +#define NAPI_CPP_EXCEPTIONS +#else +#error Exception support not detected. \ + Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS. +#endif +#endif + +// If C++ NAPI_CPP_EXCEPTIONS are enabled, NODE_ADDON_API_ENABLE_MAYBE should +// not be set +#if defined(NAPI_CPP_EXCEPTIONS) && defined(NODE_ADDON_API_ENABLE_MAYBE) +#error NODE_ADDON_API_ENABLE_MAYBE should not be set when \ + NAPI_CPP_EXCEPTIONS is defined. +#endif + +#ifdef _NOEXCEPT +#define NAPI_NOEXCEPT _NOEXCEPT +#else +#define NAPI_NOEXCEPT noexcept +#endif + +#ifdef NAPI_CPP_EXCEPTIONS + +// When C++ exceptions are enabled, Errors are thrown directly. There is no need +// to return anything after the throw statements. The variadic parameter is an +// optional return value that is ignored. +// We need _VOID versions of the macros to avoid warnings resulting from +// leaving the NAPI_THROW_* `...` argument empty. + +#define NAPI_THROW(e, ...) throw e +#define NAPI_THROW_VOID(e) throw e + +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) throw Napi::Error::New(env); + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) throw Napi::Error::New(env); + +#else // NAPI_CPP_EXCEPTIONS + +// When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, +// which are pending until the callback returns to JS. The variadic parameter +// is an optional return value; usually it is an empty result. +// We need _VOID versions of the macros to avoid warnings resulting from +// leaving the NAPI_THROW_* `...` argument empty. + +#define NAPI_THROW(e, ...) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } while (0) + +#define NAPI_THROW_VOID(e) \ + do { \ + (e).ThrowAsJavaScriptException(); \ + return; \ + } while (0) + +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) { \ + Napi::Error::New(env).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) { \ + Napi::Error::New(env).ThrowAsJavaScriptException(); \ + return; \ + } + +#endif // NAPI_CPP_EXCEPTIONS + +#ifdef NODE_ADDON_API_ENABLE_MAYBE +#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ + NAPI_THROW_IF_FAILED(env, status, Napi::Nothing()) + +#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \ + NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \ + return Napi::Just(result); +#else +#define NAPI_MAYBE_THROW_IF_FAILED(env, status, type) \ + NAPI_THROW_IF_FAILED(env, status, type()) + +#define NAPI_RETURN_OR_THROW_IF_FAILED(env, status, result, type) \ + NAPI_MAYBE_THROW_IF_FAILED(env, status, type); \ + return result; +#endif + +#define NAPI_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; +#define NAPI_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; + +#define NAPI_DISALLOW_ASSIGN_COPY(CLASS) \ + NAPI_DISALLOW_ASSIGN(CLASS) \ + NAPI_DISALLOW_COPY(CLASS) + +#define NAPI_CHECK(condition, location, message) \ + do { \ + if (!(condition)) { \ + Napi::Error::Fatal((location), (message)); \ + } \ + } while (0) + +#define NAPI_FATAL_IF_FAILED(status, location, message) \ + NAPI_CHECK((status) == napi_ok, location, message) + +//////////////////////////////////////////////////////////////////////////////// +/// Node-API C++ Wrapper Classes +/// +/// These classes wrap the "Node-API" ABI-stable C APIs for Node.js, providing a +/// C++ object model and C++ exception-handling semantics with low overhead. +/// The wrappers are all header-only so that they do not affect the ABI. +//////////////////////////////////////////////////////////////////////////////// +namespace Napi { + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +// NAPI_CPP_CUSTOM_NAMESPACE can be #define'd per-addon to avoid symbol +// conflicts between different instances of node-addon-api + +// First dummy definition of the namespace to make sure that Napi::(name) still +// refers to the right things inside this file. +namespace NAPI_CPP_CUSTOM_NAMESPACE {} +using namespace NAPI_CPP_CUSTOM_NAMESPACE; + +namespace NAPI_CPP_CUSTOM_NAMESPACE { +#endif + +// Forward declarations +class Env; +class Value; +class Boolean; +class Number; +#if NAPI_VERSION > 5 +class BigInt; +#endif // NAPI_VERSION > 5 +#if (NAPI_VERSION > 4) +class Date; +#endif +class String; +class Object; +class Array; +class ArrayBuffer; +class Function; +class Error; +class PropertyDescriptor; +class CallbackInfo; +class TypedArray; +template +class TypedArrayOf; + +using Int8Array = + TypedArrayOf; ///< Typed-array of signed 8-bit integers +using Uint8Array = + TypedArrayOf; ///< Typed-array of unsigned 8-bit integers +using Int16Array = + TypedArrayOf; ///< Typed-array of signed 16-bit integers +using Uint16Array = + TypedArrayOf; ///< Typed-array of unsigned 16-bit integers +using Int32Array = + TypedArrayOf; ///< Typed-array of signed 32-bit integers +using Uint32Array = + TypedArrayOf; ///< Typed-array of unsigned 32-bit integers +using Float32Array = + TypedArrayOf; ///< Typed-array of 32-bit floating-point values +using Float64Array = + TypedArrayOf; ///< Typed-array of 64-bit floating-point values +#if NAPI_VERSION > 5 +using BigInt64Array = + TypedArrayOf; ///< Typed array of signed 64-bit integers +using BigUint64Array = + TypedArrayOf; ///< Typed array of unsigned 64-bit integers +#endif // NAPI_VERSION > 5 + +/// Defines the signature of a Node-API C++ module's registration callback +/// (init) function. +using ModuleRegisterCallback = Object (*)(Env env, Object exports); + +class MemoryManagement; + +/// A simple Maybe type, representing an object which may or may not have a +/// value. +/// +/// If an API method returns a Maybe<>, the API method can potentially fail +/// either because an exception is thrown, or because an exception is pending, +/// e.g. because a previous API call threw an exception that hasn't been +/// caught yet. In that case, a "Nothing" value is returned. +template +class Maybe { + public: + bool IsNothing() const; + bool IsJust() const; + + /// Short-hand for Unwrap(), which doesn't return a value. Could be used + /// where the actual value of the Maybe is not needed like Object::Set. + /// If this Maybe is nothing (empty), node-addon-api will crash the + /// process. + void Check() const; + + /// Return the value of type T contained in the Maybe. If this Maybe is + /// nothing (empty), node-addon-api will crash the process. + T Unwrap() const; + + /// Return the value of type T contained in the Maybe, or using a default + /// value if this Maybe is nothing (empty). + T UnwrapOr(const T& default_value) const; + + /// Converts this Maybe to a value of type T in the out. If this Maybe is + /// nothing (empty), `false` is returned and `out` is left untouched. + bool UnwrapTo(T* out) const; + + bool operator==(const Maybe& other) const; + bool operator!=(const Maybe& other) const; + + private: + Maybe(); + explicit Maybe(const T& t); + + bool _has_value; + T _value; + + template + friend Maybe Nothing(); + template + friend Maybe Just(const U& u); +}; + +template +inline Maybe Nothing(); + +template +inline Maybe Just(const T& t); + +#if defined(NODE_ADDON_API_ENABLE_MAYBE) +template +using MaybeOrValue = Maybe; +#else +template +using MaybeOrValue = T; +#endif + +/// Environment for Node-API values and operations. +/// +/// All Node-API values and operations must be associated with an environment. +/// An environment instance is always provided to callback functions; that +/// environment must then be used for any creation of Node-API values or other +/// Node-API operations within the callback. (Many methods infer the +/// environment from the `this` instance that the method is called on.) +/// +/// In the future, multiple environments per process may be supported, +/// although current implementations only support one environment per process. +/// +/// In the V8 JavaScript engine, a Node-API environment approximately +/// corresponds to an Isolate. +class Env { + private: + napi_env _env; +#if NAPI_VERSION > 5 + template + static void DefaultFini(Env, T* data); + template + static void DefaultFiniWithHint(Env, DataType* data, HintType* hint); +#endif // NAPI_VERSION > 5 + public: + Env(napi_env env); + + operator napi_env() const; + + Object Global() const; + Value Undefined() const; + Value Null() const; + + bool IsExceptionPending() const; + Error GetAndClearPendingException() const; + + MaybeOrValue RunScript(const char* utf8script) const; + MaybeOrValue RunScript(const std::string& utf8script) const; + MaybeOrValue RunScript(String script) const; + +#if NAPI_VERSION > 2 + template + class CleanupHook; + + template + CleanupHook AddCleanupHook(Hook hook); + + template + CleanupHook AddCleanupHook(Hook hook, Arg* arg); +#endif // NAPI_VERSION > 2 + +#if NAPI_VERSION > 5 + template + T* GetInstanceData() const; + + template + using Finalizer = void (*)(Env, T*); + template fini = Env::DefaultFini> + void SetInstanceData(T* data) const; + + template + using FinalizerWithHint = void (*)(Env, DataType*, HintType*); + template fini = + Env::DefaultFiniWithHint> + void SetInstanceData(DataType* data, HintType* hint) const; +#endif // NAPI_VERSION > 5 + +#if NAPI_VERSION > 2 + template + class CleanupHook { + public: + CleanupHook(); + CleanupHook(Env env, Hook hook, Arg* arg); + CleanupHook(Env env, Hook hook); + bool Remove(Env env); + bool IsEmpty() const; + + private: + static inline void Wrapper(void* data) NAPI_NOEXCEPT; + static inline void WrapperWithArg(void* data) NAPI_NOEXCEPT; + + void (*wrapper)(void* arg); + struct CleanupData { + Hook hook; + Arg* arg; + } * data; + }; +#endif // NAPI_VERSION > 2 + +#if NAPI_VERSION > 8 + const char* GetModuleFileName() const; +#endif // NAPI_VERSION > 8 +}; + +/// A JavaScript value of unknown type. +/// +/// For type-specific operations, convert to one of the Value subclasses using a +/// `To*` or `As()` method. The `To*` methods do type coercion; the `As()` +/// method does not. +/// +/// Napi::Value value = ... +/// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid +/// arg..."); Napi::String str = value.As(); // Cast to a +/// string value +/// +/// Napi::Value anotherValue = ... +/// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value +class Value { + public: + Value(); ///< Creates a new _empty_ Value instance. + Value(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Creates a JS value from a C++ primitive. + /// + /// `value` may be any of: + /// - bool + /// - Any integer type + /// - Any floating point type + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + /// - napi::Value + /// - napi_value + template + static Value From(napi_env env, const T& value); + + /// Converts to a Node-API value primitive. + /// + /// If the instance is _empty_, this returns `nullptr`. + operator napi_value() const; + + /// Tests if this value strictly equals another value. + bool operator==(const Value& other) const; + + /// Tests if this value does not strictly equal another value. + bool operator!=(const Value& other) const; + + /// Tests if this value strictly equals another value. + bool StrictEquals(const Value& other) const; + + /// Gets the environment the value is associated with. + Napi::Env Env() const; + + /// Checks if the value is empty (uninitialized). + /// + /// An empty value is invalid, and most attempts to perform an operation on an + /// empty value will result in an exception. Note an empty value is distinct + /// from JavaScript `null` or `undefined`, which are valid values. + /// + /// When C++ exceptions are disabled at compile time, a method with a `Value` + /// return type may return an empty value to indicate a pending exception. So + /// when not using C++ exceptions, callers should check whether the value is + /// empty before attempting to use it. + bool IsEmpty() const; + + napi_valuetype Type() const; ///< Gets the type of the value. + + bool IsUndefined() + const; ///< Tests if a value is an undefined JavaScript value. + bool IsNull() const; ///< Tests if a value is a null JavaScript value. + bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. + bool IsNumber() const; ///< Tests if a value is a JavaScript number. +#if NAPI_VERSION > 5 + bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. +#endif // NAPI_VERSION > 5 +#if (NAPI_VERSION > 4) + bool IsDate() const; ///< Tests if a value is a JavaScript date. +#endif + bool IsString() const; ///< Tests if a value is a JavaScript string. + bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. + bool IsArray() const; ///< Tests if a value is a JavaScript array. + bool IsArrayBuffer() + const; ///< Tests if a value is a JavaScript array buffer. + bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. + bool IsObject() const; ///< Tests if a value is a JavaScript object. + bool IsFunction() const; ///< Tests if a value is a JavaScript function. + bool IsPromise() const; ///< Tests if a value is a JavaScript promise. + bool IsDataView() const; ///< Tests if a value is a JavaScript data view. + bool IsBuffer() const; ///< Tests if a value is a Node buffer. + bool IsExternal() const; ///< Tests if a value is a pointer to external data. + + /// Casts to another type of `Napi::Value`, when the actual type is known or + /// assumed. + /// + /// This conversion does NOT coerce the type. Calling any methods + /// inappropriate for the actual value type will throw `Napi::Error`. + /// + /// If `NODE_ADDON_API_ENABLE_TYPE_CHECK_ON_AS` is defined, this method + /// asserts that the actual type is the expected type. + template + T As() const; + + MaybeOrValue ToBoolean() + const; ///< Coerces a value to a JavaScript boolean. + MaybeOrValue ToNumber() + const; ///< Coerces a value to a JavaScript number. + MaybeOrValue ToString() + const; ///< Coerces a value to a JavaScript string. + MaybeOrValue ToObject() + const; ///< Coerces a value to a JavaScript object. + + protected: + /// !cond INTERNAL + napi_env _env; + napi_value _value; + /// !endcond +}; + +/// A JavaScript boolean value. +class Boolean : public Value { + public: + static Boolean New(napi_env env, ///< Node-API environment + bool value ///< Boolean value + ); + + static void CheckCast(napi_env env, napi_value value); + + Boolean(); ///< Creates a new _empty_ Boolean instance. + Boolean(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator bool() const; ///< Converts a Boolean value to a boolean primitive. + bool Value() const; ///< Converts a Boolean value to a boolean primitive. +}; + +/// A JavaScript number value. +class Number : public Value { + public: + static Number New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + static void CheckCast(napi_env env, napi_value value); + + Number(); ///< Creates a new _empty_ Number instance. + Number(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator int32_t() + const; ///< Converts a Number value to a 32-bit signed integer value. + operator uint32_t() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + operator int64_t() + const; ///< Converts a Number value to a 64-bit signed integer value. + operator float() + const; ///< Converts a Number value to a 32-bit floating-point value. + operator double() + const; ///< Converts a Number value to a 64-bit floating-point value. + + int32_t Int32Value() + const; ///< Converts a Number value to a 32-bit signed integer value. + uint32_t Uint32Value() + const; ///< Converts a Number value to a 32-bit unsigned integer value. + int64_t Int64Value() + const; ///< Converts a Number value to a 64-bit signed integer value. + float FloatValue() + const; ///< Converts a Number value to a 32-bit floating-point value. + double DoubleValue() + const; ///< Converts a Number value to a 64-bit floating-point value. +}; + +#if NAPI_VERSION > 5 +/// A JavaScript bigint value. +class BigInt : public Value { + public: + static BigInt New(napi_env env, ///< Node-API environment + int64_t value ///< Number value + ); + static BigInt New(napi_env env, ///< Node-API environment + uint64_t value ///< Number value + ); + + /// Creates a new BigInt object using a specified sign bit and a + /// specified list of digits/words. + /// The resulting number is calculated as: + /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) + static BigInt New(napi_env env, ///< Node-API environment + int sign_bit, ///< Sign bit. 1 if negative. + size_t word_count, ///< Number of words in array + const uint64_t* words ///< Array of words + ); + + static void CheckCast(napi_env env, napi_value value); + + BigInt(); ///< Creates a new _empty_ BigInt instance. + BigInt(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + int64_t Int64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit signed integer value. + uint64_t Uint64Value(bool* lossless) + const; ///< Converts a BigInt value to a 64-bit unsigned integer value. + + size_t WordCount() const; ///< The number of 64-bit words needed to store + ///< the result of ToWords(). + + /// Writes the contents of this BigInt to a specified memory location. + /// `sign_bit` must be provided and will be set to 1 if this BigInt is + /// negative. + /// `*word_count` has to be initialized to the length of the `words` array. + /// Upon return, it will be set to the actual number of words that would + /// be needed to store this BigInt (i.e. the return value of `WordCount()`). + void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); +}; +#endif // NAPI_VERSION > 5 + +#if (NAPI_VERSION > 4) +/// A JavaScript date value. +class Date : public Value { + public: + /// Creates a new Date value from a double primitive. + static Date New(napi_env env, ///< Node-API environment + double value ///< Number value + ); + + static void CheckCast(napi_env env, napi_value value); + + Date(); ///< Creates a new _empty_ Date instance. + Date(napi_env env, napi_value value); ///< Wraps a Node-API value primitive. + operator double() const; ///< Converts a Date value to double primitive + + double ValueOf() const; ///< Converts a Date value to a double primitive. +}; +#endif + +/// A JavaScript string or symbol value (that can be used as a property name). +class Name : public Value { + public: + static void CheckCast(napi_env env, napi_value value); + + Name(); ///< Creates a new _empty_ Name instance. + Name(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. +}; + +/// A JavaScript string value. +class String : public Name { + public: + /// Creates a new String value from a UTF-8 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::string& value ///< UTF-8 encoded C++ string + ); + + /// Creates a new String value from a UTF-16 encoded C++ string. + static String New(napi_env env, ///< Node-API environment + const std::u16string& value ///< UTF-16 encoded C++ string + ); + + /// Creates a new String value from a UTF-8 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char* value ///< UTF-8 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-16 encoded C string. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value ///< UTF-16 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-8 encoded C string with specified + /// length. + static String New(napi_env env, ///< Node-API environment + const char* value, ///< UTF-8 encoded C string (not + ///< necessarily null-terminated) + size_t length ///< length of the string in bytes + ); + + /// Creates a new String value from a UTF-16 encoded C string with specified + /// length. + static String New( + napi_env env, ///< Node-API environment + const char16_t* value, ///< UTF-16 encoded C string (not necessarily + ///< null-terminated) + size_t length ///< Length of the string in 2-byte code units + ); + + /// Creates a new String based on the original object's type. + /// + /// `value` may be any of: + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + template + static String From(napi_env env, const T& value); + + static void CheckCast(napi_env env, napi_value value); + + String(); ///< Creates a new _empty_ String instance. + String(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + operator std::string() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + operator std::u16string() + const; ///< Converts a String value to a UTF-16 encoded C++ string. + std::string Utf8Value() + const; ///< Converts a String value to a UTF-8 encoded C++ string. + std::u16string Utf16Value() + const; ///< Converts a String value to a UTF-16 encoded C++ string. +}; + +/// A JavaScript symbol value. +class Symbol : public Name { + public: + /// Creates a new Symbol value with an optional description. + static Symbol New( + napi_env env, ///< Node-API environment + const char* description = + nullptr ///< Optional UTF-8 encoded null-terminated C string + /// describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + const std::string& + description ///< UTF-8 encoded C++ string describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New(napi_env env, ///< Node-API environment + String description ///< String value describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< Node-API environment + napi_value description ///< String value describing the symbol + ); + + /// Get a public Symbol (e.g. Symbol.iterator). + static MaybeOrValue WellKnown(napi_env, const std::string& name); + + // Create a symbol in the global registry, UTF-8 Encoded cpp string + static MaybeOrValue For(napi_env env, const std::string& description); + + // Create a symbol in the global registry, C style string (null terminated) + static MaybeOrValue For(napi_env env, const char* description); + + // Create a symbol in the global registry, String value describing the symbol + static MaybeOrValue For(napi_env env, String description); + + // Create a symbol in the global registry, napi_value describing the symbol + static MaybeOrValue For(napi_env env, napi_value description); + + static void CheckCast(napi_env env, napi_value value); + + Symbol(); ///< Creates a new _empty_ Symbol instance. + Symbol(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. +}; + +class TypeTaggable : public Value { + public: +#if NAPI_VERSION >= 8 + void TypeTag(const napi_type_tag* type_tag) const; + bool CheckTypeTag(const napi_type_tag* type_tag) const; +#endif // NAPI_VERSION >= 8 + protected: + TypeTaggable(); + TypeTaggable(napi_env env, napi_value value); +}; + +/// A JavaScript object value. +class Object : public TypeTaggable { + public: + /// Enables property and element assignments using indexing syntax. + /// + /// This is a convenient helper to get and set object properties. As + /// getting and setting object properties may throw with JavaScript + /// exceptions, it is notable that these operations may fail. + /// When NODE_ADDON_API_ENABLE_MAYBE is defined, the process will abort + /// on JavaScript exceptions. + /// + /// Example: + /// + /// Napi::Value propertyValue = object1['A']; + /// object2['A'] = propertyValue; + /// Napi::Value elementValue = array[0]; + /// array[1] = elementValue; + template + class PropertyLValue { + public: + /// Converts an L-value to a value. + operator Value() const; + + /// Assigns a value to the property. The type of value can be + /// anything supported by `Object::Set`. + template + PropertyLValue& operator=(ValueType value); + + private: + PropertyLValue() = delete; + PropertyLValue(Object object, Key key); + napi_env _env; + napi_value _object; + Key _key; + + friend class Napi::Object; + }; + + /// Creates a new Object value. + static Object New(napi_env env ///< Node-API environment + ); + + static void CheckCast(napi_env env, napi_value value); + + Object(); ///< Creates a new _empty_ Object instance. + Object(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + /// Gets or sets a named property. + PropertyLValue operator[]( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Gets or sets a named property. + PropertyLValue operator[]( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator[]( + uint32_t index /// Property / element index + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator[](Value index /// Property / element index + ) const; + + /// Gets a named property. + MaybeOrValue operator[]( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + MaybeOrValue operator[]( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets an indexed property or array element. + MaybeOrValue operator[](uint32_t index ///< Property / element index + ) const; + + /// Checks whether a property is present. + MaybeOrValue Has(napi_value key ///< Property key primitive + ) const; + + /// Checks whether a property is present. + MaybeOrValue Has(Value key ///< Property key + ) const; + + /// Checks whether a named property is present. + MaybeOrValue Has( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a named property is present. + MaybeOrValue Has( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty(napi_value key ///< Property key primitive + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty(Value key ///< Property key + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a own property is present. + MaybeOrValue HasOwnProperty( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets a property. + MaybeOrValue Get(napi_value key ///< Property key primitive + ) const; + + /// Gets a property. + MaybeOrValue Get(Value key ///< Property key + ) const; + + /// Gets a named property. + MaybeOrValue Get( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + MaybeOrValue Get( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Sets a property. + template + MaybeOrValue Set(napi_value key, ///< Property key primitive + const ValueType& value ///< Property value primitive + ) const; + + /// Sets a property. + template + MaybeOrValue Set(Value key, ///< Property key + const ValueType& value ///< Property value + ) const; + + /// Sets a named property. + template + MaybeOrValue Set( + const char* utf8name, ///< UTF-8 encoded null-terminated property name + const ValueType& value) const; + + /// Sets a named property. + template + MaybeOrValue Set( + const std::string& utf8name, ///< UTF-8 encoded property name + const ValueType& value ///< Property value primitive + ) const; + + /// Delete property. + MaybeOrValue Delete(napi_value key ///< Property key primitive + ) const; + + /// Delete property. + MaybeOrValue Delete(Value key ///< Property key + ) const; + + /// Delete property. + MaybeOrValue Delete( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Delete property. + MaybeOrValue Delete( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether an indexed property is present. + MaybeOrValue Has(uint32_t index ///< Property / element index + ) const; + + /// Gets an indexed property or array element. + MaybeOrValue Get(uint32_t index ///< Property / element index + ) const; + + /// Sets an indexed property or array element. + template + MaybeOrValue Set(uint32_t index, ///< Property / element index + const ValueType& value ///< Property value primitive + ) const; + + /// Deletes an indexed property or array element. + MaybeOrValue Delete(uint32_t index ///< Property / element index + ) const; + + /// This operation can fail in case of Proxy.[[OwnPropertyKeys]] and + /// Proxy.[[GetOwnProperty]] calling into JavaScript. See: + /// - + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys + /// - + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p + MaybeOrValue GetPropertyNames() const; ///< Get all property names + + /// Defines a property on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperty( + const PropertyDescriptor& + property ///< Descriptor for the property to be defined + ) const; + + /// Defines properties on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperties( + const std::initializer_list& properties + ///< List of descriptors for the properties to be defined + ) const; + + /// Defines properties on the object. + /// + /// This operation can fail in case of Proxy.[[DefineOwnProperty]] calling + /// into JavaScript. See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc + MaybeOrValue DefineProperties( + const std::vector& properties + ///< Vector of descriptors for the properties to be defined + ) const; + + /// Checks if an object is an instance created by a constructor function. + /// + /// This is equivalent to the JavaScript `instanceof` operator. + /// + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue InstanceOf( + const Function& constructor ///< Constructor function + ) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, T* data) const; + + template + inline void AddFinalizer(Finalizer finalizeCallback, + T* data, + Hint* finalizeHint) const; + +#ifdef NAPI_CPP_EXCEPTIONS + class const_iterator; + + inline const_iterator begin() const; + + inline const_iterator end() const; + + class iterator; + + inline iterator begin(); + + inline iterator end(); +#endif // NAPI_CPP_EXCEPTIONS + +#if NAPI_VERSION >= 8 + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue Freeze() const; + /// This operation can fail in case of Proxy.[[GetPrototypeOf]] calling into + /// JavaScript. + /// See + /// https://tc39.es/ecma262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof + MaybeOrValue Seal() const; +#endif // NAPI_VERSION >= 8 +}; + +template +class External : public TypeTaggable { + public: + static External New(napi_env env, T* data); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static External New(napi_env env, T* data, Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static void CheckCast(napi_env env, napi_value value); + + External(); + External(napi_env env, napi_value value); + + T* Data() const; +}; + +class Array : public Object { + public: + static Array New(napi_env env); + static Array New(napi_env env, size_t length); + + static void CheckCast(napi_env env, napi_value value); + + Array(); + Array(napi_env env, napi_value value); + + uint32_t Length() const; +}; + +#ifdef NAPI_CPP_EXCEPTIONS +class Object::const_iterator { + private: + enum class Type { BEGIN, END }; + + inline const_iterator(const Object* object, const Type type); + + public: + inline const_iterator& operator++(); + + inline bool operator==(const const_iterator& other) const; + + inline bool operator!=(const const_iterator& other) const; + + inline const std::pair> operator*() + const; + + private: + const Napi::Object* _object; + Array _keys; + uint32_t _index; + + friend class Object; +}; + +class Object::iterator { + private: + enum class Type { BEGIN, END }; + + inline iterator(Object* object, const Type type); + + public: + inline iterator& operator++(); + + inline bool operator==(const iterator& other) const; + + inline bool operator!=(const iterator& other) const; + + inline std::pair> operator*(); + + private: + Napi::Object* _object; + Array _keys; + uint32_t _index; + + friend class Object; +}; +#endif // NAPI_CPP_EXCEPTIONS + +/// A JavaScript array buffer value. +class ArrayBuffer : public Object { + public: + /// Creates a new ArrayBuffer instance over a new automatically-allocated + /// buffer. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + size_t byteLength ///< Length of the buffer to be allocated, in bytes + ); + +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength ///< Length of the external buffer to be used by the + ///< array, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env env, + /// void* externalData)` + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with + /// specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< Node-API environment + void* externalData, ///< Pointer to the external buffer to be used by + ///< the array + size_t byteLength, ///< Length of the external buffer to be used by the + ///< array, + /// in bytes + Finalizer finalizeCallback, ///< Function to be called when the array + ///< buffer is destroyed; + /// must implement `void operator()(Env + /// env, void* externalData, Hint* hint)` + Hint* finalizeHint ///< Hint (second parameter) to be passed to the + ///< finalize callback + ); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + + static void CheckCast(napi_env env, napi_value value); + + ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. + ArrayBuffer(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + void* Data(); ///< Gets a pointer to the data buffer. + size_t ByteLength(); ///< Gets the length of the array buffer in bytes. + +#if NAPI_VERSION >= 7 + bool IsDetached() const; + void Detach(); +#endif // NAPI_VERSION >= 7 +}; + +/// A JavaScript typed-array value with unknown array type. +/// +/// For type-specific operations, cast to a `TypedArrayOf` instance using the +/// `As()` method: +/// +/// Napi::TypedArray array = ... +/// if (t.TypedArrayType() == napi_int32_array) { +/// Napi::Int32Array int32Array = t.As(); +/// } +class TypedArray : public Object { + public: + static void CheckCast(napi_env env, napi_value value); + + TypedArray(); ///< Creates a new _empty_ TypedArray instance. + TypedArray(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + napi_typedarray_type TypedArrayType() + const; ///< Gets the type of this typed-array. + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + + uint8_t ElementSize() + const; ///< Gets the size in bytes of one element in the array. + size_t ElementLength() const; ///< Gets the number of elements in the array. + size_t ByteOffset() + const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + protected: + /// !cond INTERNAL + napi_typedarray_type _type; + size_t _length; + + TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length); + + template + static +#if defined(NAPI_HAS_CONSTEXPR) + constexpr +#endif + napi_typedarray_type + TypedArrayTypeForPrimitiveType() { + return std::is_same::value ? napi_int8_array + : std::is_same::value ? napi_uint8_array + : std::is_same::value ? napi_int16_array + : std::is_same::value ? napi_uint16_array + : std::is_same::value ? napi_int32_array + : std::is_same::value ? napi_uint32_array + : std::is_same::value ? napi_float32_array + : std::is_same::value ? napi_float64_array +#if NAPI_VERSION > 5 + : std::is_same::value ? napi_bigint64_array + : std::is_same::value ? napi_biguint64_array +#endif // NAPI_VERSION > 5 + : napi_int8_array; + } + /// !endcond +}; + +/// A JavaScript typed-array value with known array type. +/// +/// Note while it is possible to create and access Uint8 "clamped" arrays using +/// this class, the _clamping_ behavior is only applied in JavaScript. +template +class TypedArrayOf : public TypedArray { + public: + /// Creates a new TypedArray instance over a new automatically-allocated array + /// buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + + /// Creates a new TypedArray instance over a provided array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred + /// from the template parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< Node-API environment + size_t elementLength, ///< Length of the created array, as a number of + ///< elements + Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the + ///< typed-array starts +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = + TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the + ///< template parameter T. + ); + + static void CheckCast(napi_env env, napi_value value); + + TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. + TypedArrayOf(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + T& operator[](size_t index); ///< Gets or sets an element in the array. + const T& operator[](size_t index) const; ///< Gets an element in the array. + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, + /// because the typed-array may have a non-zero `ByteOffset()` into the + /// `ArrayBuffer`. + T* Data(); + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, + /// because the typed-array may have a non-zero `ByteOffset()` into the + /// `ArrayBuffer`. + const T* Data() const; + + private: + T* _data; + + TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data); +}; + +/// The DataView provides a low-level interface for reading/writing multiple +/// number types in an ArrayBuffer irrespective of the platform's endianness. +class DataView : public Object { + public: + static DataView New(napi_env env, Napi::ArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); + + static void CheckCast(napi_env env, napi_value value); + + DataView(); ///< Creates a new _empty_ DataView instance. + DataView(napi_env env, + napi_value value); ///< Wraps a Node-API value primitive. + + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + size_t ByteOffset() + const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + void* Data() const; + + float GetFloat32(size_t byteOffset) const; + double GetFloat64(size_t byteOffset) const; + int8_t GetInt8(size_t byteOffset) const; + int16_t GetInt16(size_t byteOffset) const; + int32_t GetInt32(size_t byteOffset) const; + uint8_t GetUint8(size_t byteOffset) const; + uint16_t GetUint16(size_t byteOffset) const; + uint32_t GetUint32(size_t byteOffset) const; + + void SetFloat32(size_t byteOffset, float value) const; + void SetFloat64(size_t byteOffset, double value) const; + void SetInt8(size_t byteOffset, int8_t value) const; + void SetInt16(size_t byteOffset, int16_t value) const; + void SetInt32(size_t byteOffset, int32_t value) const; + void SetUint8(size_t byteOffset, uint8_t value) const; + void SetUint16(size_t byteOffset, uint16_t value) const; + void SetUint32(size_t byteOffset, uint32_t value) const; + + private: + template + T ReadData(size_t byteOffset) const; + + template + void WriteData(size_t byteOffset, T value) const; + + void* _data; + size_t _length; +}; + +class Function : public Object { + public: + using VoidCallback = void (*)(const CallbackInfo& info); + using Callback = Value (*)(const CallbackInfo& info); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const char* utf8name = nullptr, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + template + static Function New(napi_env env, + const std::string& utf8name, + void* data = nullptr); + + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const char* utf8name = nullptr, + void* data = nullptr); + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data = nullptr); + + static void CheckCast(napi_env env, napi_value value); + + Function(); + Function(napi_env env, napi_value value); + + MaybeOrValue operator()( + const std::initializer_list& args) const; + + MaybeOrValue Call(const std::initializer_list& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call(size_t argc, const napi_value* args) const; + MaybeOrValue Call(napi_value recv, + const std::initializer_list& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + size_t argc, + const napi_value* args) const; + + MaybeOrValue MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback(napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback(napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + MaybeOrValue New(const std::initializer_list& args) const; + MaybeOrValue New(const std::vector& args) const; + MaybeOrValue New(size_t argc, const napi_value* args) const; +}; + +class Promise : public Object { + public: + class Deferred { + public: + static Deferred New(napi_env env); + Deferred(napi_env env); + + Napi::Promise Promise() const; + Napi::Env Env() const; + + void Resolve(napi_value value) const; + void Reject(napi_value value) const; + + private: + napi_env _env; + napi_deferred _deferred; + napi_value _promise; + }; + + static void CheckCast(napi_env env, napi_value value); + + Promise(napi_env env, napi_value value); +}; + +template +class Buffer : public Uint8Array { + public: + static Buffer New(napi_env env, size_t length); +#ifndef NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + static Buffer New(napi_env env, T* data, size_t length); + + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static Buffer New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); +#endif // NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED + + static Buffer NewOrCopy(napi_env env, T* data, size_t length); + // Finalizer must implement `void operator()(Env env, T* data)`. + template + static Buffer NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. + template + static Buffer NewOrCopy(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static Buffer Copy(napi_env env, const T* data, size_t length); + + static void CheckCast(napi_env env, napi_value value); + + Buffer(); + Buffer(napi_env env, napi_value value); + size_t Length() const; + T* Data() const; + + private: +}; + +/// Holds a counted reference to a value; initially a weak reference unless +/// otherwise specified, may be changed to/from a strong reference by adjusting +/// the refcount. +/// +/// The referenced value is not immediately destroyed when the reference count +/// is zero; it is merely then eligible for garbage-collection if there are no +/// other references to the value. +template +class Reference { + public: + static Reference New(const T& value, uint32_t initialRefcount = 0); + + Reference(); + Reference(napi_env env, napi_ref ref); + ~Reference(); + + // A reference can be moved but cannot be copied. + Reference(Reference&& other); + Reference& operator=(Reference&& other); + NAPI_DISALLOW_ASSIGN(Reference) + + operator napi_ref() const; + bool operator==(const Reference& other) const; + bool operator!=(const Reference& other) const; + + Napi::Env Env() const; + bool IsEmpty() const; + + // Note when getting the value of a Reference it is usually correct to do so + // within a HandleScope so that the value handle gets cleaned up efficiently. + T Value() const; + + uint32_t Ref() const; + uint32_t Unref() const; + void Reset(); + void Reset(const T& value, uint32_t refcount = 0); + + // Call this on a reference that is declared as static data, to prevent its + // destructor from running at program shutdown time, which would attempt to + // reset the reference when the environment is no longer valid. Avoid using + // this if at all possible. If you do need to use static data, MAKE SURE to + // warn your users that your addon is NOT threadsafe. + void SuppressDestruct(); + + protected: + Reference(const Reference&); + + /// !cond INTERNAL + napi_env _env; + napi_ref _ref; + /// !endcond + + private: + bool _suppressDestruct; +}; + +class ObjectReference : public Reference { + public: + ObjectReference(); + ObjectReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + ObjectReference(Reference&& other); + ObjectReference& operator=(Reference&& other); + ObjectReference(ObjectReference&& other); + ObjectReference& operator=(ObjectReference&& other); + NAPI_DISALLOW_ASSIGN(ObjectReference) + + MaybeOrValue Get(const char* utf8name) const; + MaybeOrValue Get(const std::string& utf8name) const; + MaybeOrValue Set(const char* utf8name, napi_value value) const; + MaybeOrValue Set(const char* utf8name, Napi::Value value) const; + MaybeOrValue Set(const char* utf8name, const char* utf8value) const; + MaybeOrValue Set(const char* utf8name, bool boolValue) const; + MaybeOrValue Set(const char* utf8name, double numberValue) const; + MaybeOrValue Set(const std::string& utf8name, napi_value value) const; + MaybeOrValue Set(const std::string& utf8name, Napi::Value value) const; + MaybeOrValue Set(const std::string& utf8name, + std::string& utf8value) const; + MaybeOrValue Set(const std::string& utf8name, bool boolValue) const; + MaybeOrValue Set(const std::string& utf8name, double numberValue) const; + + MaybeOrValue Get(uint32_t index) const; + MaybeOrValue Set(uint32_t index, const napi_value value) const; + MaybeOrValue Set(uint32_t index, const Napi::Value value) const; + MaybeOrValue Set(uint32_t index, const char* utf8value) const; + MaybeOrValue Set(uint32_t index, const std::string& utf8value) const; + MaybeOrValue Set(uint32_t index, bool boolValue) const; + MaybeOrValue Set(uint32_t index, double numberValue) const; + + protected: + ObjectReference(const ObjectReference&); +}; + +class FunctionReference : public Reference { + public: + FunctionReference(); + FunctionReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + FunctionReference(Reference&& other); + FunctionReference& operator=(Reference&& other); + FunctionReference(FunctionReference&& other); + FunctionReference& operator=(FunctionReference&& other); + NAPI_DISALLOW_ASSIGN_COPY(FunctionReference) + + MaybeOrValue operator()( + const std::initializer_list& args) const; + + MaybeOrValue Call( + const std::initializer_list& args) const; + MaybeOrValue Call(const std::vector& args) const; + MaybeOrValue Call( + napi_value recv, const std::initializer_list& args) const; + MaybeOrValue Call(napi_value recv, + const std::vector& args) const; + MaybeOrValue Call(napi_value recv, + size_t argc, + const napi_value* args) const; + + MaybeOrValue MakeCallback( + napi_value recv, + const std::initializer_list& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback( + napi_value recv, + const std::vector& args, + napi_async_context context = nullptr) const; + MaybeOrValue MakeCallback( + napi_value recv, + size_t argc, + const napi_value* args, + napi_async_context context = nullptr) const; + + MaybeOrValue New(const std::initializer_list& args) const; + MaybeOrValue New(const std::vector& args) const; +}; + +// Shortcuts to creating a new reference with inferred type and refcount = 0. +template +Reference Weak(T value); +ObjectReference Weak(Object value); +FunctionReference Weak(Function value); + +// Shortcuts to creating a new reference with inferred type and refcount = 1. +template +Reference Persistent(T value); +ObjectReference Persistent(Object value); +FunctionReference Persistent(Function value); + +/// A persistent reference to a JavaScript error object. Use of this class +/// depends somewhat on whether C++ exceptions are enabled at compile time. +/// +/// ### Handling Errors With C++ Exceptions +/// +/// If C++ exceptions are enabled, then the `Error` class extends +/// `std::exception` and enables integrated error-handling for C++ exceptions +/// and JavaScript exceptions. +/// +/// If a Node-API call fails without executing any JavaScript code (for +/// example due to an invalid argument), then the Node-API wrapper +/// automatically converts and throws the error as a C++ exception of type +/// `Napi::Error`. Or if a JavaScript function called by C++ code via Node-API +/// throws a JavaScript exception, then the Node-API wrapper automatically +/// converts and throws it as a C++ exception of type `Napi::Error`. +/// +/// If a C++ exception of type `Napi::Error` escapes from a Node-API C++ +/// callback, then the Node-API wrapper automatically converts and throws it +/// as a JavaScript exception. Therefore, catching a C++ exception of type +/// `Napi::Error` prevents a JavaScript exception from being thrown. +/// +/// #### Example 1A - Throwing a C++ exception: +/// +/// Napi::Env env = ... +/// throw Napi::Error::New(env, "Example exception"); +/// +/// Following C++ statements will not be executed. The exception will bubble +/// up as a C++ exception of type `Napi::Error`, until it is either caught +/// while still in C++, or else automatically propataged as a JavaScript +/// exception when the callback returns to JavaScript. +/// +/// #### Example 2A - Propagating a Node-API C++ exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// +/// Following C++ statements will not be executed. The exception will bubble +/// up as a C++ exception of type `Napi::Error`, until it is either caught +/// while still in C++, or else automatically propagated as a JavaScript +/// exception when the callback returns to JavaScript. +/// +/// #### Example 3A - Handling a Node-API C++ exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result; +/// try { +/// result = jsFunctionThatThrows({ arg1, arg2 }); +/// } catch (const Napi::Error& e) { +/// cerr << "Caught JavaScript exception: " + e.what(); +/// } +/// +/// Since the exception was caught here, it will not be propagated as a +/// JavaScript exception. +/// +/// ### Handling Errors Without C++ Exceptions +/// +/// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) +/// then this class does not extend `std::exception`, and APIs in the `Napi` +/// namespace do not throw C++ exceptions when they fail. Instead, they raise +/// _pending_ JavaScript exceptions and return _empty_ `Value`s. Calling code +/// should check `Value::IsEmpty()` before attempting to use a returned value, +/// and may use methods on the `Env` class to check for, get, and clear a +/// pending JavaScript exception. If the pending exception is not cleared, it +/// will be thrown when the native callback returns to JavaScript. +/// +/// #### Example 1B - Throwing a JS exception +/// +/// Napi::Env env = ... +/// Napi::Error::New(env, "Example +/// exception").ThrowAsJavaScriptException(); return; +/// +/// After throwing a JS exception, the code should generally return +/// immediately from the native callback, after performing any necessary +/// cleanup. +/// +/// #### Example 2B - Propagating a Node-API JS exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// if (result.IsEmpty()) return; +/// +/// An empty value result from a Node-API call indicates an error occurred, +/// and a JavaScript exception is pending. To let the exception propagate, the +/// code should generally return immediately from the native callback, after +/// performing any necessary cleanup. +/// +/// #### Example 3B - Handling a Node-API JS exception: +/// +/// Napi::Function jsFunctionThatThrows = someObj.As(); +/// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); +/// if (result.IsEmpty()) { +/// Napi::Error e = env.GetAndClearPendingException(); +/// cerr << "Caught JavaScript exception: " + e.Message(); +/// } +/// +/// Since the exception was cleared here, it will not be propagated as a +/// JavaScript exception after the native callback returns. +class Error : public ObjectReference +#ifdef NAPI_CPP_EXCEPTIONS + , + public std::exception +#endif // NAPI_CPP_EXCEPTIONS +{ + public: + static Error New(napi_env env); + static Error New(napi_env env, const char* message); + static Error New(napi_env env, const std::string& message); + + static NAPI_NO_RETURN void Fatal(const char* location, const char* message); + + Error(); + Error(napi_env env, napi_value value); + + // An error can be moved or copied. + Error(Error&& other); + Error& operator=(Error&& other); + Error(const Error&); + Error& operator=(const Error&); + + const std::string& Message() const NAPI_NOEXCEPT; + void ThrowAsJavaScriptException() const; + + Object Value() const; + +#ifdef NAPI_CPP_EXCEPTIONS + const char* what() const NAPI_NOEXCEPT override; +#endif // NAPI_CPP_EXCEPTIONS + + protected: + /// !cond INTERNAL + using create_error_fn = napi_status (*)(napi_env envb, + napi_value code, + napi_value msg, + napi_value* result); + + template + static TError New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error); + /// !endcond + + private: + static inline const char* ERROR_WRAP_VALUE() NAPI_NOEXCEPT; + mutable std::string _message; +}; + +class TypeError : public Error { + public: + static TypeError New(napi_env env, const char* message); + static TypeError New(napi_env env, const std::string& message); + + TypeError(); + TypeError(napi_env env, napi_value value); +}; + +class RangeError : public Error { + public: + static RangeError New(napi_env env, const char* message); + static RangeError New(napi_env env, const std::string& message); + + RangeError(); + RangeError(napi_env env, napi_value value); +}; + +#if NAPI_VERSION > 8 +class SyntaxError : public Error { + public: + static SyntaxError New(napi_env env, const char* message); + static SyntaxError New(napi_env env, const std::string& message); + + SyntaxError(); + SyntaxError(napi_env env, napi_value value); +}; +#endif // NAPI_VERSION > 8 + +class CallbackInfo { + public: + CallbackInfo(napi_env env, napi_callback_info info); + ~CallbackInfo(); + + // Disallow copying to prevent multiple free of _dynamicArgs + NAPI_DISALLOW_ASSIGN_COPY(CallbackInfo) + + Napi::Env Env() const; + Value NewTarget() const; + bool IsConstructCall() const; + size_t Length() const; + const Value operator[](size_t index) const; + Value This() const; + void* Data() const; + void SetData(void* data); + explicit operator napi_callback_info() const; + + private: + const size_t _staticArgCount = 6; + napi_env _env; + napi_callback_info _info; + napi_value _this; + size_t _argc; + napi_value* _argv; + napi_value _staticArgs[6]; + napi_value* _dynamicArgs; + void* _data; +}; + +class PropertyDescriptor { + public: + using GetterCallback = Napi::Value (*)(const Napi::CallbackInfo& info); + using SetterCallback = void (*)(const Napi::CallbackInfo& info); + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED + template + static PropertyDescriptor Accessor( + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + napi_value name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + napi_value name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + + template + static PropertyDescriptor Accessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + const std::string& utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Name name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor( + Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function( + Napi::Env env, + Napi::Object object, + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor Value( + const char* utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + const std::string& utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + napi_value name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value( + Name name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + PropertyDescriptor(napi_property_descriptor desc); + + operator napi_property_descriptor&(); + operator const napi_property_descriptor&() const; + + private: + napi_property_descriptor _desc; +}; + +/// Property descriptor for use with `ObjectWrap::DefineClass()`. +/// +/// This is different from the standalone `PropertyDescriptor` because it is +/// specific to each `ObjectWrap` subclass. This prevents using descriptors +/// from a different class when defining a new class (preventing the callbacks +/// from having incorrect `this` pointers). +template +class ClassPropertyDescriptor { + public: + ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} + + operator napi_property_descriptor&() { return _desc; } + operator const napi_property_descriptor&() const { return _desc; } + + private: + napi_property_descriptor _desc; +}; + +template +struct MethodCallbackData { + TCallback callback; + void* data; +}; + +template +struct AccessorCallbackData { + TGetterCallback getterCallback; + TSetterCallback setterCallback; + void* data; +}; + +template +class InstanceWrap { + public: + using InstanceVoidMethodCallback = void (T::*)(const CallbackInfo& info); + using InstanceMethodCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info); + using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static PropertyDescriptor InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor InstanceAccessor( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor InstanceValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + protected: + static void AttachPropData(napi_env env, + napi_value value, + const napi_property_descriptor* prop); + + private: + using This = InstanceWrap; + + using InstanceVoidMethodCallbackData = + MethodCallbackData; + using InstanceMethodCallbackData = + MethodCallbackData; + using InstanceAccessorCallbackData = + AccessorCallbackData; + + static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceGetterCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value InstanceSetterCallbackWrapper(napi_env env, + napi_callback_info info); + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template + struct SetterTag {}; + + template + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapSetter(SetterTag) NAPI_NOEXCEPT { + return nullptr; + } +}; + +/// Base class to be extended by C++ classes exposed to JavaScript; each C++ +/// class instance gets "wrapped" by a JavaScript object that is managed by this +/// class. +/// +/// At initialization time, the `DefineClass()` method must be used to +/// hook up the accessor and method callbacks. It takes a list of +/// property descriptors, which can be constructed via the various +/// static methods on the base class. +/// +/// #### Example: +/// +/// class Example: public Napi::ObjectWrap { +/// public: +/// static void Initialize(Napi::Env& env, Napi::Object& target) { +/// Napi::Function constructor = DefineClass(env, "Example", { +/// InstanceAccessor<&Example::GetSomething, +/// &Example::SetSomething>("value"), +/// InstanceMethod<&Example::DoSomething>("doSomething"), +/// }); +/// target.Set("Example", constructor); +/// } +/// +/// Example(const Napi::CallbackInfo& info); // Constructor +/// Napi::Value GetSomething(const Napi::CallbackInfo& info); +/// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& +/// value); Napi::Value DoSomething(const Napi::CallbackInfo& info); +/// } +template +class ObjectWrap : public InstanceWrap, public Reference { + public: + ObjectWrap(const CallbackInfo& callbackInfo); + virtual ~ObjectWrap(); + + static T* Unwrap(Object wrapper); + + // Methods exposed to JavaScript must conform to one of these callback + // signatures. + using StaticVoidMethodCallback = void (*)(const CallbackInfo& info); + using StaticMethodCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticGetterCallback = Napi::Value (*)(const CallbackInfo& info); + using StaticSetterCallback = void (*)(const CallbackInfo& info, + const Napi::Value& value); + + using PropertyDescriptor = ClassPropertyDescriptor; + + static Function DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list& properties, + void* data = nullptr); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::vector& properties, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticMethod( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor( + const char* utf8name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor StaticAccessor( + Symbol name, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor StaticValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& callbackInfo); + virtual void Finalize(Napi::Env env); + + private: + using This = ObjectWrap; + + static napi_value ConstructorCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticVoidMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticMethodCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticGetterCallbackWrapper(napi_env env, + napi_callback_info info); + static napi_value StaticSetterCallbackWrapper(napi_env env, + napi_callback_info info); + static void FinalizeCallback(napi_env env, void* data, void* hint); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* props, + void* data = nullptr); + + using StaticVoidMethodCallbackData = + MethodCallbackData; + using StaticMethodCallbackData = MethodCallbackData; + + using StaticAccessorCallbackData = + AccessorCallbackData; + + template + static napi_value WrappedMethod(napi_env env, + napi_callback_info info) NAPI_NOEXCEPT; + + template + struct StaticSetterTag {}; + + template + static napi_callback WrapStaticSetter(StaticSetterTag) NAPI_NOEXCEPT { + return &This::WrappedMethod; + } + static napi_callback WrapStaticSetter(StaticSetterTag) + NAPI_NOEXCEPT { + return nullptr; + } + + bool _construction_failed = true; +}; + +class HandleScope { + public: + HandleScope(napi_env env, napi_handle_scope scope); + explicit HandleScope(Napi::Env env); + ~HandleScope(); + + // Disallow copying to prevent double close of napi_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(HandleScope) + + operator napi_handle_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_handle_scope _scope; +}; + +class EscapableHandleScope { + public: + EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); + explicit EscapableHandleScope(Napi::Env env); + ~EscapableHandleScope(); + + // Disallow copying to prevent double close of napi_escapable_handle_scope + NAPI_DISALLOW_ASSIGN_COPY(EscapableHandleScope) + + operator napi_escapable_handle_scope() const; + + Napi::Env Env() const; + Value Escape(napi_value escapee); + + private: + napi_env _env; + napi_escapable_handle_scope _scope; +}; + +#if (NAPI_VERSION > 2) +class CallbackScope { + public: + CallbackScope(napi_env env, napi_callback_scope scope); + CallbackScope(napi_env env, napi_async_context context); + virtual ~CallbackScope(); + + // Disallow copying to prevent double close of napi_callback_scope + NAPI_DISALLOW_ASSIGN_COPY(CallbackScope) + + operator napi_callback_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_callback_scope _scope; +}; +#endif + +class AsyncContext { + public: + explicit AsyncContext(napi_env env, const char* resource_name); + explicit AsyncContext(napi_env env, + const char* resource_name, + const Object& resource); + virtual ~AsyncContext(); + + AsyncContext(AsyncContext&& other); + AsyncContext& operator=(AsyncContext&& other); + NAPI_DISALLOW_ASSIGN_COPY(AsyncContext) + + operator napi_async_context() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_async_context _context; +}; + +#if NAPI_HAS_THREADS +class AsyncWorker { + public: + virtual ~AsyncWorker(); + + NAPI_DISALLOW_ASSIGN_COPY(AsyncWorker) + + operator napi_async_work() const; + + Napi::Env Env() const; + + void Queue(); + void Cancel(); + void SuppressDestruct(); + + ObjectReference& Receiver(); + FunctionReference& Callback(); + + virtual void OnExecute(Napi::Env env); + virtual void OnWorkComplete(Napi::Env env, napi_status status); + + protected: + explicit AsyncWorker(const Function& callback); + explicit AsyncWorker(const Function& callback, const char* resource_name); + explicit AsyncWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncWorker(const Object& receiver, const Function& callback); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + + explicit AsyncWorker(Napi::Env env); + explicit AsyncWorker(Napi::Env env, const char* resource_name); + explicit AsyncWorker(Napi::Env env, + const char* resource_name, + const Object& resource); + + virtual void Execute() = 0; + virtual void OnOK(); + virtual void OnError(const Error& e); + virtual void Destroy(); + virtual std::vector GetResult(Napi::Env env); + + void SetError(const std::string& error); + + private: + static inline void OnAsyncWorkExecute(napi_env env, void* asyncworker); + static inline void OnAsyncWorkComplete(napi_env env, + napi_status status, + void* asyncworker); + + napi_env _env; + napi_async_work _work; + ObjectReference _receiver; + FunctionReference _callback; + std::string _error; + bool _suppress_destruct; +}; +#endif // NAPI_HAS_THREADS + +#if (NAPI_VERSION > 3 && NAPI_HAS_THREADS) +class ThreadSafeFunction { + public: + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + Finalizer finalizeCallback, + FinalizerDataType* data); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback); + + // This API may only be called from the main thread. + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data); + + ThreadSafeFunction(); + ThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall() const; + + // This API may be called from any thread. + template + napi_status BlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status BlockingCall(DataType* data, Callback callback) const; + + // This API may be called from any thread. + napi_status NonBlockingCall() const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(Callback callback) const; + + // This API may be called from any thread. + template + napi_status NonBlockingCall(DataType* data, Callback callback) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release() const; + + // This API may be called from any thread. + napi_status Abort() const; + + struct ConvertibleContext { + template + operator T*() { + return static_cast(context); + } + void* context; + }; + + // This API may be called from any thread. + ConvertibleContext GetContext() const; + + private: + using CallbackWrapper = std::function; + + template + static ThreadSafeFunction New(napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + napi_status CallInternal(CallbackWrapper* callbackWrapper, + napi_threadsafe_function_call_mode mode) const; + + static void CallJS(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + napi_threadsafe_function _tsfn; +}; + +// A TypedThreadSafeFunction by default has no context (nullptr) and can +// accept any type (void) to its CallJs. +template +class TypedThreadSafeFunction { + public: + // This API may only be called from the main thread. + // Helper function that returns nullptr if running Node-API 5+, otherwise a + // non-empty, no-op Function. This provides the ability to specify at + // compile-time a callback parameter to `New` that safely does no action + // when targeting _any_ Node-API version. +#if NAPI_VERSION > 4 + static std::nullptr_t EmptyFunctionFactory(Napi::Env env); +#else + static Napi::Function EmptyFunctionFactory(Napi::Env env); +#endif + static Napi::Function FunctionOrEmpty(Napi::Env env, + Napi::Function& callback); + +#if NAPI_VERSION > 4 + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [missing] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); +#endif + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [missing] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [missing] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + // This API may only be called from the main thread. + // Creates a new threadsafe function with: + // Callback [passed] Resource [passed] Finalizer [passed] + template + static TypedThreadSafeFunction New( + napi_env env, + CallbackType callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data = nullptr); + + TypedThreadSafeFunction(); + TypedThreadSafeFunction(napi_threadsafe_function tsFunctionValue); + + operator napi_threadsafe_function() const; + + // This API may be called from any thread. + napi_status BlockingCall(DataType* data = nullptr) const; + + // This API may be called from any thread. + napi_status NonBlockingCall(DataType* data = nullptr) const; + + // This API may only be called from the main thread. + void Ref(napi_env env) const; + + // This API may only be called from the main thread. + void Unref(napi_env env) const; + + // This API may be called from any thread. + napi_status Acquire() const; + + // This API may be called from any thread. + napi_status Release() const; + + // This API may be called from any thread. + napi_status Abort() const; + + // This API may be called from any thread. + ContextType* GetContext() const; + + private: + template + static TypedThreadSafeFunction New( + napi_env env, + const Function& callback, + const Object& resource, + ResourceString resourceName, + size_t maxQueueSize, + size_t initialThreadCount, + ContextType* context, + Finalizer finalizeCallback, + FinalizerDataType* data, + napi_finalize wrapper); + + static void CallJsInternal(napi_env env, + napi_value jsCallback, + void* context, + void* data); + + protected: + napi_threadsafe_function _tsfn; +}; +template +class AsyncProgressWorkerBase : public AsyncWorker { + public: + virtual void OnWorkProgress(DataType* data) = 0; + class ThreadSafeData { + public: + ThreadSafeData(AsyncProgressWorkerBase* asyncprogressworker, DataType* data) + : _asyncprogressworker(asyncprogressworker), _data(data) {} + + AsyncProgressWorkerBase* asyncprogressworker() { + return _asyncprogressworker; + }; + DataType* data() { return _data; }; + + private: + AsyncProgressWorkerBase* _asyncprogressworker; + DataType* _data; + }; + void OnWorkComplete(Napi::Env env, napi_status status) override; + + protected: + explicit AsyncProgressWorkerBase(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); + virtual ~AsyncProgressWorkerBase(); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressWorkerBase(Napi::Env env, + const char* resource_name, + const Object& resource, + size_t queue_size = 1); +#endif + + static inline void OnAsyncWorkProgress(Napi::Env env, + Napi::Function jsCallback, + void* data); + + napi_status NonBlockingCall(DataType* data); + + private: + ThreadSafeFunction _tsfn; + bool _work_completed = false; + napi_status _complete_status; + static inline void OnThreadSafeFunctionFinalize( + Napi::Env env, void* data, AsyncProgressWorkerBase* context); +}; + +template +class AsyncProgressWorker : public AsyncProgressWorkerBase { + public: + virtual ~AsyncProgressWorker(); + + class ExecutionProgress { + friend class AsyncProgressWorker; + + public: + void Signal() const; + void Send(const T* data, size_t count) const; + + private: + explicit ExecutionProgress(AsyncProgressWorker* worker) : _worker(worker) {} + AsyncProgressWorker* const _worker; + }; + + void OnWorkProgress(void*) override; + + protected: + explicit AsyncProgressWorker(const Function& callback); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressWorker(Napi::Env env); + explicit AsyncProgressWorker(Napi::Env env, const char* resource_name); + explicit AsyncProgressWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal(); + void SendProgress_(const T* data, size_t count); + + std::mutex _mutex; + T* _asyncdata; + size_t _asyncsize; + bool _signaled; +}; + +template +class AsyncProgressQueueWorker + : public AsyncProgressWorkerBase> { + public: + virtual ~AsyncProgressQueueWorker(){}; + + class ExecutionProgress { + friend class AsyncProgressQueueWorker; + + public: + void Signal() const; + void Send(const T* data, size_t count) const; + + private: + explicit ExecutionProgress(AsyncProgressQueueWorker* worker) + : _worker(worker) {} + AsyncProgressQueueWorker* const _worker; + }; + + void OnWorkComplete(Napi::Env env, napi_status status) override; + void OnWorkProgress(std::pair*) override; + + protected: + explicit AsyncProgressQueueWorker(const Function& callback); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Function& callback, + const char* resource_name, + const Object& resource); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name); + explicit AsyncProgressQueueWorker(const Object& receiver, + const Function& callback, + const char* resource_name, + const Object& resource); + +// Optional callback of Napi::ThreadSafeFunction only available after +// NAPI_VERSION 4. Refs: https://github.com/nodejs/node/pull/27791 +#if NAPI_VERSION > 4 + explicit AsyncProgressQueueWorker(Napi::Env env); + explicit AsyncProgressQueueWorker(Napi::Env env, const char* resource_name); + explicit AsyncProgressQueueWorker(Napi::Env env, + const char* resource_name, + const Object& resource); +#endif + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void OnProgress(const T* data, size_t count) = 0; + + private: + void Execute() override; + void Signal() const; + void SendProgress_(const T* data, size_t count); +}; +#endif // NAPI_VERSION > 3 && NAPI_HAS_THREADS + +// Memory management. +class MemoryManagement { + public: + static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); +}; + +// Version management +class VersionManagement { + public: + static uint32_t GetNapiVersion(Env env); + static const napi_node_version* GetNodeVersion(Env env); +}; + +#if NAPI_VERSION > 5 +template +class Addon : public InstanceWrap { + public: + static inline Object Init(Env env, Object exports); + static T* Unwrap(Object wrapper); + + protected: + using AddonProp = ClassPropertyDescriptor; + void DefineAddon(Object exports, + const std::initializer_list& props); + Napi::Object DefineProperties(Object object, + const std::initializer_list& props); + + private: + Object entry_point_; +}; +#endif // NAPI_VERSION > 5 + +#ifdef NAPI_CPP_CUSTOM_NAMESPACE +} // namespace NAPI_CPP_CUSTOM_NAMESPACE +#endif + +} // namespace Napi + +// Inline implementations of all the above class methods are included here. +#include "napi-inl.h" + +#endif // SRC_NAPI_H_ diff --git a/tools/ui/node_modules/node-addon-api/node_addon_api.gyp b/tools/ui/node_modules/node-addon-api/node_addon_api.gyp new file mode 100644 index 0000000000000000000000000000000000000000..29905ed473b0c8ca54d7e039249e8bce46e2f0ba --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/node_addon_api.gyp @@ -0,0 +1,32 @@ +{ + 'targets': [ + { + 'target_name': 'node_addon_api', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['noexcept.gypi'], + } + }, + { + 'target_name': 'node_addon_api_except', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['except.gypi'], + } + }, + { + 'target_name': 'node_addon_api_maybe', + 'type': 'none', + 'sources': [ 'napi.h', 'napi-inl.h' ], + 'direct_dependent_settings': { + 'include_dirs': [ '.' ], + 'includes': ['noexcept.gypi'], + 'defines': ['NODE_ADDON_API_ENABLE_MAYBE'] + } + }, + ] +} diff --git a/tools/ui/node_modules/node-addon-api/node_api.gyp b/tools/ui/node_modules/node-addon-api/node_api.gyp new file mode 100644 index 0000000000000000000000000000000000000000..4ff0ae7df3abb2a17e47db0075c5119ef1028e89 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/node_api.gyp @@ -0,0 +1,9 @@ +{ + 'targets': [ + { + 'target_name': 'nothing', + 'type': 'static_library', + 'sources': [ 'nothing.c' ] + } + ] +} diff --git a/tools/ui/node_modules/node-addon-api/noexcept.gypi b/tools/ui/node_modules/node-addon-api/noexcept.gypi new file mode 100644 index 0000000000000000000000000000000000000000..404a05f3004bfff6ba4549b01ef7e1e4acdbd1a3 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/noexcept.gypi @@ -0,0 +1,26 @@ +{ + 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ], + 'cflags': [ '-fno-exceptions' ], + 'cflags_cc': [ '-fno-exceptions' ], + 'conditions': [ + ["OS=='win'", { + # _HAS_EXCEPTIONS is already defined and set to 0 in common.gypi + #"defines": [ + # "_HAS_EXCEPTIONS=0" + #], + "msvs_settings": { + "VCCLCompilerTool": { + 'ExceptionHandling': 0, + 'EnablePREfast': 'true', + }, + }, + }], + ["OS=='mac'", { + 'xcode_settings': { + 'CLANG_CXX_LIBRARY': 'libc++', + 'MACOSX_DEPLOYMENT_TARGET': '10.7', + 'GCC_ENABLE_CPP_EXCEPTIONS': 'NO', + }, + }], + ], +} diff --git a/tools/ui/node_modules/node-addon-api/nothing.c b/tools/ui/node_modules/node-addon-api/nothing.c new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tools/ui/node_modules/node-addon-api/package-support.json b/tools/ui/node_modules/node-addon-api/package-support.json new file mode 100644 index 0000000000000000000000000000000000000000..10d3607ac46569c9e5e1c890996cc5ab6bbb07d1 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/package-support.json @@ -0,0 +1,21 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "active" + }, + "response": { + "type": "time-permitting", + "paid": false, + "contact": { + "name": "node-addon-api team", + "url": "https://github.com/nodejs/node-addon-api/issues" + } + }, + "backing": [ { "project": "https://github.com/nodejs" }, + { "foundation": "https://openjsf.org/" } + ] + } + ] +} diff --git a/tools/ui/node_modules/node-addon-api/package.json b/tools/ui/node_modules/node-addon-api/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d772ddc955609ebf5bfd0206ea5b3bde5e264b75 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/package.json @@ -0,0 +1,480 @@ +{ + "bugs": { + "url": "https://github.com/nodejs/node-addon-api/issues" + }, + "contributors": [ + { + "name": "Abhishek Kumar Singh", + "url": "https://github.com/abhi11210646" + }, + { + "name": "Alba Mendez", + "url": "https://github.com/jmendeth" + }, + { + "name": "Alexander Floh", + "url": "https://github.com/alexanderfloh" + }, + { + "name": "Ammar Faizi", + "url": "https://github.com/ammarfaizi2" + }, + { + "name": "András Timár, Dr", + "url": "https://github.com/timarandras" + }, + { + "name": "Andrew Petersen", + "url": "https://github.com/kirbysayshi" + }, + { + "name": "Anisha Rohra", + "url": "https://github.com/anisha-rohra" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax" + }, + { + "name": "Arnaud Botella", + "url": "https://github.com/BotellaA" + }, + { + "name": "Arunesh Chandra", + "url": "https://github.com/aruneshchandra" + }, + { + "name": "Azlan Mukhtar", + "url": "https://github.com/azlan" + }, + { + "name": "Ben Berman", + "url": "https://github.com/rivertam" + }, + { + "name": "Benjamin Byholm", + "url": "https://github.com/kkoopa" + }, + { + "name": "Bill Gallafent", + "url": "https://github.com/gallafent" + }, + { + "name": "blagoev", + "url": "https://github.com/blagoev" + }, + { + "name": "Bruce A. MacNaughton", + "url": "https://github.com/bmacnaughton" + }, + { + "name": "Cory Mickelson", + "url": "https://github.com/corymickelson" + }, + { + "name": "Daniel Bevenius", + "url": "https://github.com/danbev" + }, + { + "name": "Dante Calderón", + "url": "https://github.com/dantehemerson" + }, + { + "name": "Darshan Sen", + "url": "https://github.com/RaisinTen" + }, + { + "name": "David Halls", + "url": "https://github.com/davedoesdev" + }, + { + "name": "Deepak Rajamohan", + "url": "https://github.com/deepakrkris" + }, + { + "name": "Dmitry Ashkadov", + "url": "https://github.com/dmitryash" + }, + { + "name": "Dongjin Na", + "url": "https://github.com/nadongguri" + }, + { + "name": "Doni Rubiagatra", + "url": "https://github.com/rubiagatra" + }, + { + "name": "Eric Bickle", + "url": "https://github.com/ebickle" + }, + { + "name": "extremeheat", + "url": "https://github.com/extremeheat" + }, + { + "name": "Feng Yu", + "url": "https://github.com/F3n67u" + }, + { + "name": "Ferdinand Holzer", + "url": "https://github.com/fholzer" + }, + { + "name": "Gabriel Schulhof", + "url": "https://github.com/gabrielschulhof" + }, + { + "name": "Guenter Sandner", + "url": "https://github.com/gms1" + }, + { + "name": "Gus Caplan", + "url": "https://github.com/devsnek" + }, + { + "name": "Helio Frota", + "url": "https://github.com/helio-frota" + }, + { + "name": "Hitesh Kanwathirtha", + "url": "https://github.com/digitalinfinity" + }, + { + "name": "ikokostya", + "url": "https://github.com/ikokostya" + }, + { + "name": "Jack Xia", + "url": "https://github.com/JckXia" + }, + { + "name": "Jake Barnes", + "url": "https://github.com/DuBistKomisch" + }, + { + "name": "Jake Yoon", + "url": "https://github.com/yjaeseok" + }, + { + "name": "Jason Ginchereau", + "url": "https://github.com/jasongin" + }, + { + "name": "Jenny", + "url": "https://github.com/egg-bread" + }, + { + "name": "Jeroen Janssen", + "url": "https://github.com/japj" + }, + { + "name": "Jim Schlight", + "url": "https://github.com/jschlight" + }, + { + "name": "Jinho Bang", + "url": "https://github.com/romandev" + }, + { + "name": "José Expósito", + "url": "https://github.com/JoseExposito" + }, + { + "name": "joshgarde", + "url": "https://github.com/joshgarde" + }, + { + "name": "Julian Mesa", + "url": "https://github.com/julianmesa-gitkraken" + }, + { + "name": "Kasumi Hanazuki", + "url": "https://github.com/hanazuki" + }, + { + "name": "Kelvin", + "url": "https://github.com/kelvinhammond" + }, + { + "name": "Kevin Eady", + "url": "https://github.com/KevinEady" + }, + { + "name": "Kévin VOYER", + "url": "https://github.com/kecsou" + }, + { + "name": "kidneysolo", + "url": "https://github.com/kidneysolo" + }, + { + "name": "Koki Nishihara", + "url": "https://github.com/Nishikoh" + }, + { + "name": "Konstantin Tarkus", + "url": "https://github.com/koistya" + }, + { + "name": "Kyle Farnung", + "url": "https://github.com/kfarnung" + }, + { + "name": "Kyle Kovacs", + "url": "https://github.com/nullromo" + }, + { + "name": "legendecas", + "url": "https://github.com/legendecas" + }, + { + "name": "LongYinan", + "url": "https://github.com/Brooooooklyn" + }, + { + "name": "Lovell Fuller", + "url": "https://github.com/lovell" + }, + { + "name": "Luciano Martorella", + "url": "https://github.com/lmartorella" + }, + { + "name": "mastergberry", + "url": "https://github.com/mastergberry" + }, + { + "name": "Mathias Küsel", + "url": "https://github.com/mathiask88" + }, + { + "name": "Mathias Stearn", + "url": "https://github.com/RedBeard0531" + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina" + }, + { + "name": "Michael Dawson", + "url": "https://github.com/mhdawson" + }, + { + "name": "Michael Price", + "url": "https://github.com/mikepricedev" + }, + { + "name": "Michele Campus", + "url": "https://github.com/kYroL01" + }, + { + "name": "Mikhail Cheshkov", + "url": "https://github.com/mcheshkov" + }, + { + "name": "nempoBu4", + "url": "https://github.com/nempoBu4" + }, + { + "name": "Nicola Del Gobbo", + "url": "https://github.com/NickNaso" + }, + { + "name": "Nick Soggin", + "url": "https://github.com/iSkore" + }, + { + "name": "Nikolai Vavilov", + "url": "https://github.com/seishun" + }, + { + "name": "Nurbol Alpysbayev", + "url": "https://github.com/anurbol" + }, + { + "name": "pacop", + "url": "https://github.com/pacop" + }, + { + "name": "Peter Šándor", + "url": "https://github.com/petersandor" + }, + { + "name": "Philipp Renoth", + "url": "https://github.com/DaAitch" + }, + { + "name": "rgerd", + "url": "https://github.com/rgerd" + }, + { + "name": "Richard Lau", + "url": "https://github.com/richardlau" + }, + { + "name": "Rolf Timmermans", + "url": "https://github.com/rolftimmermans" + }, + { + "name": "Ross Weir", + "url": "https://github.com/ross-weir" + }, + { + "name": "Ryuichi Okumura", + "url": "https://github.com/okuryu" + }, + { + "name": "Saint Gabriel", + "url": "https://github.com/chineduG" + }, + { + "name": "Sampson Gao", + "url": "https://github.com/sampsongao" + }, + { + "name": "Sam Roberts", + "url": "https://github.com/sam-github" + }, + { + "name": "strager", + "url": "https://github.com/strager" + }, + { + "name": "Taylor Woll", + "url": "https://github.com/boingoing" + }, + { + "name": "Thomas Gentilhomme", + "url": "https://github.com/fraxken" + }, + { + "name": "Tim Rach", + "url": "https://github.com/timrach" + }, + { + "name": "Tobias Nießen", + "url": "https://github.com/tniessen" + }, + { + "name": "todoroff", + "url": "https://github.com/todoroff" + }, + { + "name": "Toyo Li", + "url": "https://github.com/toyobayashi" + }, + { + "name": "Tux3", + "url": "https://github.com/tux3" + }, + { + "name": "Vlad Velmisov", + "url": "https://github.com/Velmisov" + }, + { + "name": "Vladimir Morozov", + "url": "https://github.com/vmoroz" + + }, + { + "name": "WenheLI", + "url": "https://github.com/WenheLI" + }, + { + "name": "Xuguang Mei", + "url": "https://github.com/meixg" + }, + { + "name": "Yohei Kishimoto", + "url": "https://github.com/morokosi" + }, + { + "name": "Yulong Wang", + "url": "https://github.com/fs-eire" + }, + { + "name": "Ziqiu Zhao", + "url": "https://github.com/ZzqiZQute" + }, + { + "name": "Feng Yu", + "url": "https://github.com/F3n67u" + }, + { + "name": "wanlu wang", + "url": "https://github.com/wanlu" + }, + { + "name": "Caleb Hearon", + "url": "https://github.com/chearon" + }, + { + "name": "Marx", + "url": "https://github.com/MarxJiao" + }, + { + "name": "Ömer AKGÜL", + "url": "https://github.com/tuhalf" + } + ], + "description": "Node.js API (Node-API)", + "devDependencies": { + "benchmark": "^2.1.4", + "bindings": "^1.5.0", + "clang-format": "^1.4.0", + "eslint": "^7.32.0", + "eslint-config-semistandard": "^16.0.0", + "eslint-config-standard": "^16.0.3", + "eslint-plugin-import": "^2.24.2", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-promise": "^5.1.0", + "fs-extra": "^11.1.1", + "path": "^0.12.7", + "pre-commit": "^1.2.2", + "safe-buffer": "^5.1.1" + }, + "directories": {}, + "gypfile": false, + "homepage": "https://github.com/nodejs/node-addon-api", + "keywords": [ + "n-api", + "napi", + "addon", + "native", + "bindings", + "c", + "c++", + "nan", + "node-addon-api" + ], + "license": "MIT", + "main": "index.js", + "name": "node-addon-api", + "readme": "README.md", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/node-addon-api.git" + }, + "files": [ + "*.{c,h,gyp,gypi}", + "package-support.json", + "tools/" + ], + "scripts": { + "prebenchmark": "node-gyp rebuild -C benchmark", + "benchmark": "node benchmark", + "pretest": "node-gyp rebuild -C test", + "test": "node test", + "test:debug": "node-gyp rebuild -C test --debug && NODE_API_BUILD_CONFIG=Debug node ./test/index.js", + "predev": "node-gyp rebuild -C test --debug", + "dev": "node test", + "predev:incremental": "node-gyp configure build -C test --debug", + "dev:incremental": "node test", + "doc": "doxygen doc/Doxyfile", + "lint": "node tools/eslint-format && node tools/clang-format", + "lint:fix": "node tools/clang-format --fix && node tools/eslint-format --fix" + }, + "pre-commit": "lint", + "version": "7.1.1", + "support": true +} diff --git a/tools/ui/node_modules/node-addon-api/tools/README.md b/tools/ui/node_modules/node-addon-api/tools/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6b80e94f52d5eaf51333018d6f5694164aa53376 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/tools/README.md @@ -0,0 +1,73 @@ +# Tools + +## clang-format + +The clang-format checking tools is designed to check changed lines of code compared to given git-refs. + +## Migration Script + +The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. + +### How To Use + +To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. +``` +npm install node-addon-api +``` + +Then run the script passing your project directory +``` +node ./node_modules/node-addon-api/tools/conversion.js ./ +``` + +After finish, recompile and debug things that are missed by the script. + + +### Quick Fixes +Here is the list of things that can be fixed easily. + 1. Change your methods' return value to void if it doesn't return value to JavaScript. + 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. + 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); + + +### Major Reconstructions +The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. + +So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. + + 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as +``` +[ClassName](const Napi::CallbackInfo& info); +``` +and define it as +``` +[ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ + ... +} +``` +This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. + + 2. Move your original constructor code into the new constructor. Delete your original constructor. + 3. In your class initialization function, associate native methods in the following way. +``` +Napi::FunctionReference constructor; + +void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { + Napi::HandleScope scope(env); + Napi::Function ctor = DefineClass(env, "Canvas", { + InstanceMethod<&[ClassName]::Func1>("Func1"), + InstanceMethod<&[ClassName]::Func2>("Func2"), + InstanceAccessor<&[ClassName]::ValueGetter>("Value"), + StaticMethod<&[ClassName]::StaticMethod>("MethodName"), + InstanceValue("Value", Napi::[Type]::New(env, value)), + }); + + constructor = Napi::Persistent(ctor); + constructor .SuppressDestruct(); + exports.Set("[ClassName]", ctor); +} +``` + 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. + + +If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. diff --git a/tools/ui/node_modules/node-addon-api/tools/check-napi.js b/tools/ui/node_modules/node-addon-api/tools/check-napi.js new file mode 100644 index 0000000000000000000000000000000000000000..9199af334ecad323c039b148d4037700d1a29fa5 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/tools/check-napi.js @@ -0,0 +1,99 @@ +'use strict'; +// Descend into a directory structure and, for each file matching *.node, output +// based on the imports found in the file whether it's an N-API module or not. + +const fs = require('fs'); +const path = require('path'); + +// Read the output of the command, break it into lines, and use the reducer to +// decide whether the file is an N-API module or not. +function checkFile (file, command, argv, reducer) { + const child = require('child_process').spawn(command, argv, { + stdio: ['inherit', 'pipe', 'inherit'] + }); + let leftover = ''; + let isNapi; + child.stdout.on('data', (chunk) => { + if (isNapi === undefined) { + chunk = (leftover + chunk.toString()).split(/[\r\n]+/); + leftover = chunk.pop(); + isNapi = chunk.reduce(reducer, isNapi); + if (isNapi !== undefined) { + child.kill(); + } + } + }); + child.on('close', (code, signal) => { + if ((code === null && signal !== null) || (code !== 0)) { + console.log( + command + ' exited with code: ' + code + ' and signal: ' + signal); + } else { + // Green if it's a N-API module, red otherwise. + console.log( + '\x1b[' + (isNapi ? '42' : '41') + 'm' + + (isNapi ? ' N-API' : 'Not N-API') + + '\x1b[0m: ' + file); + } + }); +} + +// Use nm -a to list symbols. +function checkFileUNIX (file) { + checkFile(file, 'nm', ['-a', file], (soFar, line) => { + if (soFar === undefined) { + line = line.match(/([0-9a-f]*)? ([a-zA-Z]) (.*$)/); + if (line[2] === 'U') { + if (/^napi/.test(line[3])) { + soFar = true; + } + } + } + return soFar; + }); +} + +// Use dumpbin /imports to list symbols. +function checkFileWin32 (file) { + checkFile(file, 'dumpbin', ['/imports', file], (soFar, line) => { + if (soFar === undefined) { + line = line.match(/([0-9a-f]*)? +([a-zA-Z0-9]) (.*$)/); + if (line && /^napi/.test(line[line.length - 1])) { + soFar = true; + } + } + return soFar; + }); +} + +// Descend into a directory structure and pass each file ending in '.node' to +// one of the above checks, depending on the OS. +function recurse (top) { + fs.readdir(top, (error, items) => { + if (error) { + throw new Error('error reading directory ' + top + ': ' + error); + } + items.forEach((item) => { + item = path.join(top, item); + fs.stat(item, ((item) => (error, stats) => { + if (error) { + throw new Error('error about ' + item + ': ' + error); + } + if (stats.isDirectory()) { + recurse(item); + } else if (/[.]node$/.test(item) && + // Explicitly ignore files called 'nothing.node' because they are + // artefacts of node-addon-api having identified a version of + // Node.js that ships with a correct implementation of N-API. + path.basename(item) !== 'nothing.node') { + process.platform === 'win32' + ? checkFileWin32(item) + : checkFileUNIX(item); + } + })(item)); + }); + }); +} + +// Start with the directory given on the command line or the current directory +// if nothing was given. +recurse(process.argv.length > 3 ? process.argv[2] : '.'); diff --git a/tools/ui/node_modules/node-addon-api/tools/clang-format.js b/tools/ui/node_modules/node-addon-api/tools/clang-format.js new file mode 100644 index 0000000000000000000000000000000000000000..e4bb4f52e07f371cce8f42c280178398b3965415 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/tools/clang-format.js @@ -0,0 +1,71 @@ +#!/usr/bin/env node + +const spawn = require('child_process').spawnSync; +const path = require('path'); + +const filesToCheck = ['*.h', '*.cc']; +const FORMAT_START = process.env.FORMAT_START || 'main'; + +function main (args) { + let fix = false; + while (args.length > 0) { + switch (args[0]) { + case '-f': + case '--fix': + fix = true; + break; + default: + } + args.shift(); + } + + const clangFormatPath = path.dirname(require.resolve('clang-format')); + const binary = process.platform === 'win32' + ? 'node_modules\\.bin\\clang-format.cmd' + : 'node_modules/.bin/clang-format'; + const options = ['--binary=' + binary, '--style=file']; + if (fix) { + options.push(FORMAT_START); + } else { + options.push('--diff', FORMAT_START); + } + + const gitClangFormatPath = path.join(clangFormatPath, 'bin/git-clang-format'); + const result = spawn( + 'python', + [gitClangFormatPath, ...options, '--', ...filesToCheck], + { encoding: 'utf-8' } + ); + + if (result.stderr) { + console.error('Error running git-clang-format:', result.stderr); + return 2; + } + + const clangFormatOutput = result.stdout.trim(); + // Bail fast if in fix mode. + if (fix) { + console.log(clangFormatOutput); + return 0; + } + // Detect if there is any complains from clang-format + if ( + clangFormatOutput !== '' && + clangFormatOutput !== 'no modified files to format' && + clangFormatOutput !== 'clang-format did not modify any files' + ) { + console.error(clangFormatOutput); + const fixCmd = 'npm run lint:fix'; + console.error(` + ERROR: please run "${fixCmd}" to format changes in your commit + Note that when running the command locally, please keep your local + main branch and working branch up to date with nodejs/node-addon-api + to exclude un-related complains. + Or you can run "env FORMAT_START=upstream/main ${fixCmd}".`); + return 1; + } +} + +if (require.main === module) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/tools/ui/node_modules/node-addon-api/tools/conversion.js b/tools/ui/node_modules/node-addon-api/tools/conversion.js new file mode 100644 index 0000000000000000000000000000000000000000..f89245ac69b6f92e399330678da4430261bd614a --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/tools/conversion.js @@ -0,0 +1,301 @@ +#! /usr/bin/env node + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const args = process.argv.slice(2); +const dir = args[0]; +if (!dir) { + console.log('Usage: node ' + path.basename(__filename) + ' '); + process.exit(1); +} + +const NodeApiVersion = require('../package.json').version; + +const disable = args[1]; +let ConfigFileOperations; +if (disable !== '--disable' && dir !== '--disable') { + ConfigFileOperations = { + 'package.json': [ + [/([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], + [/[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, ''] + ], + 'binding.gyp': [ + [/([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'], + [/Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'], + [/Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'], + [/Nan::New\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)'], + [/Nan::New\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);'], + [/Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'], + [/Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'], + + // FunctionTemplate to FunctionReference + [/Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference'], + [/Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference'], + [/v8::Local/g, 'Napi::FunctionReference'], + [/Local/g, 'Napi::FunctionReference'], + [/v8::FunctionTemplate/g, 'Napi::FunctionReference'], + [/FunctionTemplate/g, 'Napi::FunctionReference'], + + [/([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),'], + [/([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm, + '});\n\n' + + '$1constructor = Napi::Persistent($3);\n' + + '$1constructor.SuppressDestruct();\n' + + '$1target.Set("$2", $3);'], + + // TODO: Other attribute combinations + [/static_cast\(ReadOnly\s*\|\s*DontDelete\)/gm, + 'static_cast(napi_enumerable | napi_configurable)'], + + [/([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()'], + + [/\*Nan::Utf8String\(([^)]+)\)/g, '$1->As().Utf8Value().c_str()'], + [/Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As()'], + [/Nan::Utf8String/g, 'std::string'], + + [/v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'], + [/String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'], + [/\.length\(\)/g, '.Length()'], + + [/Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,'], + + [/class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>'], + [/(\w+)\(([^)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3'], + + // HandleOKCallback to OnOK + [/HandleOKCallback/g, 'OnOK'], + // HandleErrorCallback to OnError + [/HandleErrorCallback/g, 'OnError'], + + // ex. .As() to .As() + [/\.As\(\)/g, '.As()'], + [/\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As()'], + + // ex. Nan::New(info[0]) to Napi::Number::New(info[0]) + [/Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)'], + [/Nan::New\(([0-9.]+)\)/g, 'Napi::Number::New(env, $1)'], + [/Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")'], + [/Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")'], + [/Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)'], + [/Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)'], + [/Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, '], + [/Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, '], + [/Nan::NewBuffer\(/g, 'Napi::Buffer::New(env, '], + // TODO: Properly handle this + [/Nan::New\(/g, 'Napi::New(env, '], + + [/\.IsInt32\(\)/g, '.IsNumber()'], + [/->IsInt32\(\)/g, '.IsNumber()'], + + [/(.+?)->BooleanValue\(\)/g, '$1.As().Value()'], + [/(.+?)->Int32Value\(\)/g, '$1.As().Int32Value()'], + [/(.+?)->Uint32Value\(\)/g, '$1.As().Uint32Value()'], + [/(.+?)->IntegerValue\(\)/g, '$1.As().Int64Value()'], + [/(.+?)->NumberValue\(\)/g, '$1.As().DoubleValue()'], + + // ex. Nan::To(info[0]) to info[0].Value() + [/Nan::To\((.+?)\)/g, '$2.To()'], + [/Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To()'], + // ex. Nan::To(info[0]) to info[0].As().Value() + [/Nan::To\((.+?)\)/g, '$1.As().Value()'], + // ex. Nan::To(info[0]) to info[0].As().Int32Value() + [/Nan::To\((.+?)\)/g, '$1.As().Int32Value()'], + // ex. Nan::To(info[0]) to info[0].As().Int32Value() + [/Nan::To\((.+?)\)/g, '$1.As().Int32Value()'], + // ex. Nan::To(info[0]) to info[0].As().Uint32Value() + [/Nan::To\((.+?)\)/g, '$1.As().Uint32Value()'], + // ex. Nan::To(info[0]) to info[0].As().Int64Value() + [/Nan::To\((.+?)\)/g, '$1.As().Int64Value()'], + // ex. Nan::To(info[0]) to info[0].As().FloatValue() + [/Nan::To\((.+?)\)/g, '$1.As().FloatValue()'], + // ex. Nan::To(info[0]) to info[0].As().DoubleValue() + [/Nan::To\((.+?)\)/g, '$1.As().DoubleValue()'], + + [/Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())'], + + [/Nan::Has\(([^,]+),\s*/gm, '($1).Has('], + [/\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)'], + [/\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)'], + + [/Nan::Get\(([^,]+),\s*/gm, '($1).Get('], + [/\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)'], + [/\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)'], + + [/Nan::Set\(([^,]+),\s*/gm, '($1).Set('], + [/\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,'], + [/\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,'], + + // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer() + [/node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()'], + // ex. node::Buffer::Length(info[0]) to info[0].Length() + [/node::Buffer::Length\((.+?)\)/g, '$1.As>().Length()'], + // ex. node::Buffer::Data(info[0]) to info[0].Data() + [/node::Buffer::Data\((.+?)\)/g, '$1.As>().Data()'], + [/Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, '], + + // Nan::AsyncQueueWorker(worker) + [/Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();'], + [/Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()'], + + // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException() + [/([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();'], + [/Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();'], + [/Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n'], + // Nan::RangeError(error) to Napi::RangeError::New(env, error) + [/Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)'], + + [/Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)'], + + [/Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);'], + [/Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope'], + [/Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty('], + [/\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", '], + // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ], + [/Nan::Equals\(([^,]+),/g, '$1.StrictEquals('], + + [/(.+)->Set\(/g, '$1.Set('], + + [/Nan::Callback/g, 'Napi::FunctionReference'], + + [/Nan::Persistent/g, 'Napi::ObjectReference'], + [/Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target'], + + [/(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;'], + [/Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();'], + + [/Nan::NAN_METHOD_RETURN_TYPE/g, 'void'], + [/NAN_INLINE/g, 'inline'], + + [/Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&'], + [/NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [/static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [/NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [/static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'], + [/NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'], + [/void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)'], + [/NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);'], + [/NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)'], + + [/::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)'], + [/constructor_template/g, 'constructor'], + + [/Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2'], + [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);'], + [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&'], + + [/Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()'], + + [/info\[(\d+)\]->/g, 'info[$1].'], + [/info\[([\w\d]+)\]->/g, 'info[$1].'], + [/info\.This\(\)->/g, 'info.This().'], + [/->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()'], + [/info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()'], + [/info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;'], + + // ex. Local to Napi::Value + [/v8::Local/g, 'Napi::$1'], + [/Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1'], + + // Declare an env in helper functions that take a Napi::Value + [/(\w+)\(Napi::Value (\w+)(,\s*[^()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4'], + + // delete #include and/or + [/#include +(<|")(?:node|nan).h("|>)/g, '#include $1napi.h$2\n#include $1uv.h$2'], + // NODE_MODULE to NODE_API_MODULE + [/NODE_MODULE/g, 'NODE_API_MODULE'], + [/Nan::/g, 'Napi::'], + [/nan.h/g, 'napi.h'], + + // delete .FromJust() + [/\.FromJust\(\)/g, ''], + // delete .ToLocalCheck() + [/\.ToLocalChecked\(\)/g, ''], + [/^.*->SetInternalFieldCount\(.*$/gm, ''], + + // replace using node; and/or using v8; to using Napi; + [/using (node|v8);/g, 'using Napi;'], + [/using namespace (node|Nan|v8);/g, 'using namespace Napi;'], + // delete using v8::Local; + [/using v8::Local;\n/g, ''], + // replace using v8::XXX; with using Napi::XXX + [/using v8::([A-Za-z]+);/g, 'using Napi::$1;'] + +]; + +const paths = listFiles(dir); +paths.forEach(function (dirEntry) { + const filename = dirEntry.split('\\').pop().split('/').pop(); + + // Check whether the file is a source file or a config file + // then execute function accordingly + const sourcePattern = /.+\.h|.+\.cc|.+\.cpp/; + if (sourcePattern.test(filename)) { + convertFile(dirEntry, SourceFileOperations); + } else if (ConfigFileOperations[filename] != null) { + convertFile(dirEntry, ConfigFileOperations[filename]); + } +}); + +function listFiles (dir, filelist) { + const files = fs.readdirSync(dir); + filelist = filelist || []; + files.forEach(function (file) { + if (file === 'node_modules') { + return; + } + + if (fs.statSync(path.join(dir, file)).isDirectory()) { + filelist = listFiles(path.join(dir, file), filelist); + } else { + filelist.push(path.join(dir, file)); + } + }); + return filelist; +} + +function convert (content, operations) { + for (let i = 0; i < operations.length; i++) { + const operation = operations[i]; + content = content.replace(operation[0], operation[1]); + } + return content; +} + +function convertFile (fileName, operations) { + fs.readFile(fileName, 'utf-8', function (err, file) { + if (err) throw err; + + file = convert(file, operations); + + fs.writeFile(fileName, file, function (err) { + if (err) throw err; + }); + }); +} diff --git a/tools/ui/node_modules/node-addon-api/tools/eslint-format.js b/tools/ui/node_modules/node-addon-api/tools/eslint-format.js new file mode 100644 index 0000000000000000000000000000000000000000..6923ab7b656cf75bdf664731cea809e868b95e29 --- /dev/null +++ b/tools/ui/node_modules/node-addon-api/tools/eslint-format.js @@ -0,0 +1,79 @@ +#!/usr/bin/env node + +const spawn = require('child_process').spawnSync; + +const filesToCheck = '*.js'; +const FORMAT_START = process.env.FORMAT_START || 'main'; +const IS_WIN = process.platform === 'win32'; +const ESLINT_PATH = IS_WIN ? 'node_modules\\.bin\\eslint.cmd' : 'node_modules/.bin/eslint'; + +function main (args) { + let fix = false; + while (args.length > 0) { + switch (args[0]) { + case '-f': + case '--fix': + fix = true; + break; + default: + } + args.shift(); + } + + // Check js files that change on unstaged file + const fileUnStaged = spawn( + 'git', + ['diff', '--name-only', '--diff-filter=d', FORMAT_START, filesToCheck], + { + encoding: 'utf-8' + } + ); + + // Check js files that change on staged file + const fileStaged = spawn( + 'git', + ['diff', '--name-only', '--cached', '--diff-filter=d', FORMAT_START, filesToCheck], + { + encoding: 'utf-8' + } + ); + + const options = [ + ...fileStaged.stdout.split('\n').filter((f) => f !== ''), + ...fileUnStaged.stdout.split('\n').filter((f) => f !== '') + ]; + + if (fix) { + options.push('--fix'); + } + + const result = spawn(ESLINT_PATH, [...options], { + encoding: 'utf-8' + }); + + if (result.error && result.error.errno === 'ENOENT') { + console.error('Eslint not found! Eslint is supposed to be found at ', ESLINT_PATH); + return 2; + } + + if (result.status === 1) { + console.error('Eslint error:', result.stdout); + const fixCmd = 'npm run lint:fix'; + console.error(`ERROR: please run "${fixCmd}" to format changes in your commit + Note that when running the command locally, please keep your local + main branch and working branch up to date with nodejs/node-addon-api + to exclude un-related complains. + Or you can run "env FORMAT_START=upstream/main ${fixCmd}". + Also fix JS files by yourself if necessary.`); + return 1; + } + + if (result.stderr) { + console.error('Error running eslint:', result.stderr); + return 2; + } +} + +if (require.main === module) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/tools/ui/node_modules/node-releases/LICENSE b/tools/ui/node_modules/node-releases/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea39e4f9b798bd59194c506f5b711380affb3b29 --- /dev/null +++ b/tools/ui/node_modules/node-releases/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2017 Sergey Rubanov (https://github.com/chicoxyzzy) + +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. diff --git a/tools/ui/node_modules/node-releases/README.md b/tools/ui/node_modules/node-releases/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56f6166725ea2c22ec131f292d5672f9ae28f9f7 --- /dev/null +++ b/tools/ui/node_modules/node-releases/README.md @@ -0,0 +1,32 @@ +# Node.js releases data + +[![npm version](https://img.shields.io/npm/v/node-releases.svg)](https://www.npmjs.com/package/node-releases) +[![License: MIT](https://img.shields.io/npm/l/node-releases.svg)](./LICENSE) + +All data is located in `data` directory. + +`data/processed` contains `envs.json` with node.js releases data preprocessed to be used by [Browserslist](https://github.com/ai/browserslist) and other projects. Each version in this file contains only necessary info: version, release date, LTS flag/name, and security flag. + +`data/release-schedule` contains `release-schedule.json` with node.js releases date and end of life date. + +## Installation + +```bash +npm install node-releases +``` + +## Usage + +```js +// CommonJS +const envs = require('node-releases/data/processed/envs.json'); +const schedule = require('node-releases/data/release-schedule/release-schedule.json'); + +// ESM (Node.js 22+) +import envs from 'node-releases/data/processed/envs.json' with { type: 'json' }; +import schedule from 'node-releases/data/release-schedule/release-schedule.json' with { type: 'json' }; +``` + +## Releases + +Releases are published automatically by a nightly GitHub Actions workflow whenever upstream Node.js release data changes. Publishing uses [npm trusted publishing](https://docs.npmjs.com/trusted-publishers) (OIDC, no long-lived tokens) and ships [provenance attestations](https://docs.npmjs.com/generating-provenance-statements). diff --git a/tools/ui/node_modules/node-releases/data/processed/envs.json b/tools/ui/node_modules/node-releases/data/processed/envs.json new file mode 100644 index 0000000000000000000000000000000000000000..c80abb50a5ac9068ea41b7df98ce7c7226b1628e --- /dev/null +++ b/tools/ui/node_modules/node-releases/data/processed/envs.json @@ -0,0 +1,2930 @@ +[ + { + "name": "nodejs", + "version": "0.2.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "2.3.8.0" + }, + { + "name": "nodejs", + "version": "0.3.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "2.5.1.0" + }, + { + "name": "nodejs", + "version": "0.4.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "3.1.2.0" + }, + { + "name": "nodejs", + "version": "0.5.0", + "date": "2011-08-26", + "lts": false, + "security": false, + "v8": "3.1.8.25" + }, + { + "name": "nodejs", + "version": "0.6.0", + "date": "2011-11-04", + "lts": false, + "security": false, + "v8": "3.6.6.6" + }, + { + "name": "nodejs", + "version": "0.7.0", + "date": "2012-01-17", + "lts": false, + "security": false, + "v8": "3.8.6.0" + }, + { + "name": "nodejs", + "version": "0.8.0", + "date": "2012-06-22", + "lts": false, + "security": false, + "v8": "3.11.10.10" + }, + { + "name": "nodejs", + "version": "0.9.0", + "date": "2012-07-20", + "lts": false, + "security": false, + "v8": "3.11.10.15" + }, + { + "name": "nodejs", + "version": "0.10.0", + "date": "2013-03-11", + "lts": false, + "security": false, + "v8": "3.14.5.8" + }, + { + "name": "nodejs", + "version": "0.11.0", + "date": "2013-03-28", + "lts": false, + "security": false, + "v8": "3.17.13.0" + }, + { + "name": "nodejs", + "version": "0.12.0", + "date": "2015-02-06", + "lts": false, + "security": false, + "v8": "3.28.73.0" + }, + { + "name": "nodejs", + "version": "4.0.0", + "date": "2015-09-08", + "lts": false, + "security": false, + "v8": "4.5.103.30" + }, + { + "name": "nodejs", + "version": "4.1.0", + "date": "2015-09-17", + "lts": false, + "security": false, + "v8": "4.5.103.33" + }, + { + "name": "nodejs", + "version": "4.2.0", + "date": "2015-10-12", + "lts": "Argon", + "security": false, + "v8": "4.5.103.35" + }, + { + "name": "nodejs", + "version": "4.3.0", + "date": "2016-02-09", + "lts": "Argon", + "security": false, + "v8": "4.5.103.35" + }, + { + "name": "nodejs", + "version": "4.4.0", + "date": "2016-03-08", + "lts": "Argon", + "security": false, + "v8": "4.5.103.35" + }, + { + "name": "nodejs", + "version": "4.5.0", + "date": "2016-08-16", + "lts": "Argon", + "security": false, + "v8": "4.5.103.37" + }, + { + "name": "nodejs", + "version": "4.6.0", + "date": "2016-09-27", + "lts": "Argon", + "security": true, + "v8": "4.5.103.37" + }, + { + "name": "nodejs", + "version": "4.7.0", + "date": "2016-12-06", + "lts": "Argon", + "security": false, + "v8": "4.5.103.43" + }, + { + "name": "nodejs", + "version": "4.8.0", + "date": "2017-02-21", + "lts": "Argon", + "security": false, + "v8": "4.5.103.45" + }, + { + "name": "nodejs", + "version": "4.9.0", + "date": "2018-03-28", + "lts": "Argon", + "security": true, + "v8": "4.5.103.53" + }, + { + "name": "nodejs", + "version": "5.0.0", + "date": "2015-10-29", + "lts": false, + "security": false, + "v8": "4.6.85.28" + }, + { + "name": "nodejs", + "version": "5.1.0", + "date": "2015-11-17", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.2.0", + "date": "2015-12-09", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.3.0", + "date": "2015-12-15", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.4.0", + "date": "2016-01-06", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.5.0", + "date": "2016-01-21", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.6.0", + "date": "2016-02-09", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.7.0", + "date": "2016-02-23", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.8.0", + "date": "2016-03-09", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.9.0", + "date": "2016-03-16", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.10.0", + "date": "2016-04-01", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.11.0", + "date": "2016-04-21", + "lts": false, + "security": false, + "v8": "4.6.85.31" + }, + { + "name": "nodejs", + "version": "5.12.0", + "date": "2016-06-23", + "lts": false, + "security": false, + "v8": "4.6.85.32" + }, + { + "name": "nodejs", + "version": "6.0.0", + "date": "2016-04-26", + "lts": false, + "security": false, + "v8": "5.0.71.35" + }, + { + "name": "nodejs", + "version": "6.1.0", + "date": "2016-05-05", + "lts": false, + "security": false, + "v8": "5.0.71.35" + }, + { + "name": "nodejs", + "version": "6.2.0", + "date": "2016-05-17", + "lts": false, + "security": false, + "v8": "5.0.71.47" + }, + { + "name": "nodejs", + "version": "6.3.0", + "date": "2016-07-06", + "lts": false, + "security": false, + "v8": "5.0.71.52" + }, + { + "name": "nodejs", + "version": "6.4.0", + "date": "2016-08-12", + "lts": false, + "security": false, + "v8": "5.0.71.60" + }, + { + "name": "nodejs", + "version": "6.5.0", + "date": "2016-08-26", + "lts": false, + "security": false, + "v8": "5.1.281.81" + }, + { + "name": "nodejs", + "version": "6.6.0", + "date": "2016-09-14", + "lts": false, + "security": false, + "v8": "5.1.281.83" + }, + { + "name": "nodejs", + "version": "6.7.0", + "date": "2016-09-27", + "lts": false, + "security": true, + "v8": "5.1.281.83" + }, + { + "name": "nodejs", + "version": "6.8.0", + "date": "2016-10-12", + "lts": false, + "security": false, + "v8": "5.1.281.84" + }, + { + "name": "nodejs", + "version": "6.9.0", + "date": "2016-10-18", + "lts": "Boron", + "security": false, + "v8": "5.1.281.84" + }, + { + "name": "nodejs", + "version": "6.10.0", + "date": "2017-02-21", + "lts": "Boron", + "security": false, + "v8": "5.1.281.93" + }, + { + "name": "nodejs", + "version": "6.11.0", + "date": "2017-06-06", + "lts": "Boron", + "security": false, + "v8": "5.1.281.102" + }, + { + "name": "nodejs", + "version": "6.12.0", + "date": "2017-11-06", + "lts": "Boron", + "security": false, + "v8": "5.1.281.108" + }, + { + "name": "nodejs", + "version": "6.13.0", + "date": "2018-02-10", + "lts": "Boron", + "security": false, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.14.0", + "date": "2018-03-28", + "lts": "Boron", + "security": true, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.15.0", + "date": "2018-11-27", + "lts": "Boron", + "security": true, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.16.0", + "date": "2018-12-26", + "lts": "Boron", + "security": false, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "6.17.0", + "date": "2019-02-28", + "lts": "Boron", + "security": true, + "v8": "5.1.281.111" + }, + { + "name": "nodejs", + "version": "7.0.0", + "date": "2016-10-25", + "lts": false, + "security": false, + "v8": "5.4.500.36" + }, + { + "name": "nodejs", + "version": "7.1.0", + "date": "2016-11-08", + "lts": false, + "security": false, + "v8": "5.4.500.36" + }, + { + "name": "nodejs", + "version": "7.2.0", + "date": "2016-11-22", + "lts": false, + "security": false, + "v8": "5.4.500.43" + }, + { + "name": "nodejs", + "version": "7.3.0", + "date": "2016-12-20", + "lts": false, + "security": false, + "v8": "5.4.500.45" + }, + { + "name": "nodejs", + "version": "7.4.0", + "date": "2017-01-04", + "lts": false, + "security": false, + "v8": "5.4.500.45" + }, + { + "name": "nodejs", + "version": "7.5.0", + "date": "2017-01-31", + "lts": false, + "security": false, + "v8": "5.4.500.48" + }, + { + "name": "nodejs", + "version": "7.6.0", + "date": "2017-02-21", + "lts": false, + "security": false, + "v8": "5.5.372.40" + }, + { + "name": "nodejs", + "version": "7.7.0", + "date": "2017-02-28", + "lts": false, + "security": false, + "v8": "5.5.372.41" + }, + { + "name": "nodejs", + "version": "7.8.0", + "date": "2017-03-29", + "lts": false, + "security": false, + "v8": "5.5.372.43" + }, + { + "name": "nodejs", + "version": "7.9.0", + "date": "2017-04-11", + "lts": false, + "security": false, + "v8": "5.5.372.43" + }, + { + "name": "nodejs", + "version": "7.10.0", + "date": "2017-05-02", + "lts": false, + "security": false, + "v8": "5.5.372.43" + }, + { + "name": "nodejs", + "version": "8.0.0", + "date": "2017-05-30", + "lts": false, + "security": false, + "v8": "5.8.283.41" + }, + { + "name": "nodejs", + "version": "8.1.0", + "date": "2017-06-08", + "lts": false, + "security": false, + "v8": "5.8.283.41" + }, + { + "name": "nodejs", + "version": "8.2.0", + "date": "2017-07-19", + "lts": false, + "security": false, + "v8": "5.8.283.41" + }, + { + "name": "nodejs", + "version": "8.3.0", + "date": "2017-08-08", + "lts": false, + "security": false, + "v8": "6.0.286.52" + }, + { + "name": "nodejs", + "version": "8.4.0", + "date": "2017-08-15", + "lts": false, + "security": false, + "v8": "6.0.286.52" + }, + { + "name": "nodejs", + "version": "8.5.0", + "date": "2017-09-12", + "lts": false, + "security": false, + "v8": "6.0.287.53" + }, + { + "name": "nodejs", + "version": "8.6.0", + "date": "2017-09-26", + "lts": false, + "security": false, + "v8": "6.0.287.53" + }, + { + "name": "nodejs", + "version": "8.7.0", + "date": "2017-10-11", + "lts": false, + "security": false, + "v8": "6.1.534.42" + }, + { + "name": "nodejs", + "version": "8.8.0", + "date": "2017-10-24", + "lts": false, + "security": false, + "v8": "6.1.534.42" + }, + { + "name": "nodejs", + "version": "8.9.0", + "date": "2017-10-31", + "lts": "Carbon", + "security": false, + "v8": "6.1.534.46" + }, + { + "name": "nodejs", + "version": "8.10.0", + "date": "2018-03-06", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.50" + }, + { + "name": "nodejs", + "version": "8.11.0", + "date": "2018-03-28", + "lts": "Carbon", + "security": true, + "v8": "6.2.414.50" + }, + { + "name": "nodejs", + "version": "8.12.0", + "date": "2018-09-10", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.66" + }, + { + "name": "nodejs", + "version": "8.13.0", + "date": "2018-11-20", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.72" + }, + { + "name": "nodejs", + "version": "8.14.0", + "date": "2018-11-27", + "lts": "Carbon", + "security": true, + "v8": "6.2.414.72" + }, + { + "name": "nodejs", + "version": "8.15.0", + "date": "2018-12-26", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.75" + }, + { + "name": "nodejs", + "version": "8.16.0", + "date": "2019-04-16", + "lts": "Carbon", + "security": false, + "v8": "6.2.414.77" + }, + { + "name": "nodejs", + "version": "8.17.0", + "date": "2019-12-17", + "lts": "Carbon", + "security": true, + "v8": "6.2.414.78" + }, + { + "name": "nodejs", + "version": "9.0.0", + "date": "2017-10-31", + "lts": false, + "security": false, + "v8": "6.2.414.32" + }, + { + "name": "nodejs", + "version": "9.1.0", + "date": "2017-11-07", + "lts": false, + "security": false, + "v8": "6.2.414.32" + }, + { + "name": "nodejs", + "version": "9.2.0", + "date": "2017-11-14", + "lts": false, + "security": false, + "v8": "6.2.414.44" + }, + { + "name": "nodejs", + "version": "9.3.0", + "date": "2017-12-12", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.4.0", + "date": "2018-01-10", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.5.0", + "date": "2018-01-31", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.6.0", + "date": "2018-02-21", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.7.0", + "date": "2018-03-01", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.8.0", + "date": "2018-03-07", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.9.0", + "date": "2018-03-21", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.10.0", + "date": "2018-03-28", + "lts": false, + "security": true, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "9.11.0", + "date": "2018-04-04", + "lts": false, + "security": false, + "v8": "6.2.414.46" + }, + { + "name": "nodejs", + "version": "10.0.0", + "date": "2018-04-24", + "lts": false, + "security": false, + "v8": "6.6.346.24" + }, + { + "name": "nodejs", + "version": "10.1.0", + "date": "2018-05-08", + "lts": false, + "security": false, + "v8": "6.6.346.27" + }, + { + "name": "nodejs", + "version": "10.2.0", + "date": "2018-05-23", + "lts": false, + "security": false, + "v8": "6.6.346.32" + }, + { + "name": "nodejs", + "version": "10.3.0", + "date": "2018-05-29", + "lts": false, + "security": false, + "v8": "6.6.346.32" + }, + { + "name": "nodejs", + "version": "10.4.0", + "date": "2018-06-06", + "lts": false, + "security": false, + "v8": "6.7.288.43" + }, + { + "name": "nodejs", + "version": "10.5.0", + "date": "2018-06-20", + "lts": false, + "security": false, + "v8": "6.7.288.46" + }, + { + "name": "nodejs", + "version": "10.6.0", + "date": "2018-07-04", + "lts": false, + "security": false, + "v8": "6.7.288.46" + }, + { + "name": "nodejs", + "version": "10.7.0", + "date": "2018-07-18", + "lts": false, + "security": false, + "v8": "6.7.288.49" + }, + { + "name": "nodejs", + "version": "10.8.0", + "date": "2018-08-01", + "lts": false, + "security": false, + "v8": "6.7.288.49" + }, + { + "name": "nodejs", + "version": "10.9.0", + "date": "2018-08-15", + "lts": false, + "security": false, + "v8": "6.8.275.24" + }, + { + "name": "nodejs", + "version": "10.10.0", + "date": "2018-09-06", + "lts": false, + "security": false, + "v8": "6.8.275.30" + }, + { + "name": "nodejs", + "version": "10.11.0", + "date": "2018-09-19", + "lts": false, + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.12.0", + "date": "2018-10-10", + "lts": false, + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.13.0", + "date": "2018-10-30", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.14.0", + "date": "2018-11-27", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.15.0", + "date": "2018-12-26", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.16.0", + "date": "2019-05-28", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.17.0", + "date": "2019-10-22", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.18.0", + "date": "2019-12-17", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.19.0", + "date": "2020-02-05", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.20.0", + "date": "2020-03-26", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.21.0", + "date": "2020-06-02", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.22.0", + "date": "2020-07-21", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.23.0", + "date": "2020-10-27", + "lts": "Dubnium", + "security": false, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "10.24.0", + "date": "2021-02-23", + "lts": "Dubnium", + "security": true, + "v8": "6.8.275.32" + }, + { + "name": "nodejs", + "version": "11.0.0", + "date": "2018-10-23", + "lts": false, + "security": false, + "v8": "7.0.276.28" + }, + { + "name": "nodejs", + "version": "11.1.0", + "date": "2018-10-30", + "lts": false, + "security": false, + "v8": "7.0.276.32" + }, + { + "name": "nodejs", + "version": "11.2.0", + "date": "2018-11-15", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.3.0", + "date": "2018-11-27", + "lts": false, + "security": true, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.4.0", + "date": "2018-12-07", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.5.0", + "date": "2018-12-18", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.6.0", + "date": "2018-12-26", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.7.0", + "date": "2019-01-17", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.8.0", + "date": "2019-01-24", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.9.0", + "date": "2019-01-30", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.10.0", + "date": "2019-02-14", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.11.0", + "date": "2019-03-05", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.12.0", + "date": "2019-03-14", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.13.0", + "date": "2019-03-28", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.14.0", + "date": "2019-04-10", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "11.15.0", + "date": "2019-04-30", + "lts": false, + "security": false, + "v8": "7.0.276.38" + }, + { + "name": "nodejs", + "version": "12.0.0", + "date": "2019-04-23", + "lts": false, + "security": false, + "v8": "7.4.288.21" + }, + { + "name": "nodejs", + "version": "12.1.0", + "date": "2019-04-29", + "lts": false, + "security": false, + "v8": "7.4.288.21" + }, + { + "name": "nodejs", + "version": "12.2.0", + "date": "2019-05-07", + "lts": false, + "security": false, + "v8": "7.4.288.21" + }, + { + "name": "nodejs", + "version": "12.3.0", + "date": "2019-05-21", + "lts": false, + "security": false, + "v8": "7.4.288.27" + }, + { + "name": "nodejs", + "version": "12.4.0", + "date": "2019-06-04", + "lts": false, + "security": false, + "v8": "7.4.288.27" + }, + { + "name": "nodejs", + "version": "12.5.0", + "date": "2019-06-26", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.6.0", + "date": "2019-07-03", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.7.0", + "date": "2019-07-23", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.8.0", + "date": "2019-08-06", + "lts": false, + "security": false, + "v8": "7.5.288.22" + }, + { + "name": "nodejs", + "version": "12.9.0", + "date": "2019-08-20", + "lts": false, + "security": false, + "v8": "7.6.303.29" + }, + { + "name": "nodejs", + "version": "12.10.0", + "date": "2019-09-04", + "lts": false, + "security": false, + "v8": "7.6.303.29" + }, + { + "name": "nodejs", + "version": "12.11.0", + "date": "2019-09-25", + "lts": false, + "security": false, + "v8": "7.7.299.11" + }, + { + "name": "nodejs", + "version": "12.12.0", + "date": "2019-10-11", + "lts": false, + "security": false, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.13.0", + "date": "2019-10-21", + "lts": "Erbium", + "security": false, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.14.0", + "date": "2019-12-17", + "lts": "Erbium", + "security": true, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.15.0", + "date": "2020-02-05", + "lts": "Erbium", + "security": true, + "v8": "7.7.299.13" + }, + { + "name": "nodejs", + "version": "12.16.0", + "date": "2020-02-11", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.17.0", + "date": "2020-05-26", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.18.0", + "date": "2020-06-02", + "lts": "Erbium", + "security": true, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.19.0", + "date": "2020-10-06", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.20.0", + "date": "2020-11-24", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.21.0", + "date": "2021-02-23", + "lts": "Erbium", + "security": true, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "12.22.0", + "date": "2021-03-30", + "lts": "Erbium", + "security": false, + "v8": "7.8.279.23" + }, + { + "name": "nodejs", + "version": "13.0.0", + "date": "2019-10-22", + "lts": false, + "security": false, + "v8": "7.8.279.17" + }, + { + "name": "nodejs", + "version": "13.1.0", + "date": "2019-11-05", + "lts": false, + "security": false, + "v8": "7.8.279.17" + }, + { + "name": "nodejs", + "version": "13.2.0", + "date": "2019-11-21", + "lts": false, + "security": false, + "v8": "7.9.317.23" + }, + { + "name": "nodejs", + "version": "13.3.0", + "date": "2019-12-03", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.4.0", + "date": "2019-12-17", + "lts": false, + "security": true, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.5.0", + "date": "2019-12-18", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.6.0", + "date": "2020-01-07", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.7.0", + "date": "2020-01-21", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.8.0", + "date": "2020-02-05", + "lts": false, + "security": true, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.9.0", + "date": "2020-02-18", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.10.0", + "date": "2020-03-04", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.11.0", + "date": "2020-03-12", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.12.0", + "date": "2020-03-26", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.13.0", + "date": "2020-04-14", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "13.14.0", + "date": "2020-04-29", + "lts": false, + "security": false, + "v8": "7.9.317.25" + }, + { + "name": "nodejs", + "version": "14.0.0", + "date": "2020-04-21", + "lts": false, + "security": false, + "v8": "8.1.307.30" + }, + { + "name": "nodejs", + "version": "14.1.0", + "date": "2020-04-29", + "lts": false, + "security": false, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.2.0", + "date": "2020-05-05", + "lts": false, + "security": false, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.3.0", + "date": "2020-05-19", + "lts": false, + "security": false, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.4.0", + "date": "2020-06-02", + "lts": false, + "security": true, + "v8": "8.1.307.31" + }, + { + "name": "nodejs", + "version": "14.5.0", + "date": "2020-06-30", + "lts": false, + "security": false, + "v8": "8.3.110.9" + }, + { + "name": "nodejs", + "version": "14.6.0", + "date": "2020-07-20", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.7.0", + "date": "2020-07-29", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.8.0", + "date": "2020-08-11", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.9.0", + "date": "2020-08-27", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.10.0", + "date": "2020-09-08", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.11.0", + "date": "2020-09-15", + "lts": false, + "security": true, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.12.0", + "date": "2020-09-22", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.13.0", + "date": "2020-09-29", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.14.0", + "date": "2020-10-15", + "lts": false, + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.15.0", + "date": "2020-10-27", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.16.0", + "date": "2021-02-23", + "lts": "Fermium", + "security": true, + "v8": "8.4.371.19" + }, + { + "name": "nodejs", + "version": "14.17.0", + "date": "2021-05-11", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.18.0", + "date": "2021-09-28", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.19.0", + "date": "2022-02-01", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.20.0", + "date": "2022-07-07", + "lts": "Fermium", + "security": true, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "14.21.0", + "date": "2022-11-01", + "lts": "Fermium", + "security": false, + "v8": "8.4.371.23" + }, + { + "name": "nodejs", + "version": "15.0.0", + "date": "2020-10-20", + "lts": false, + "security": false, + "v8": "8.6.395.16" + }, + { + "name": "nodejs", + "version": "15.1.0", + "date": "2020-11-04", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.2.0", + "date": "2020-11-10", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.3.0", + "date": "2020-11-24", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.4.0", + "date": "2020-12-09", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.5.0", + "date": "2020-12-22", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.6.0", + "date": "2021-01-14", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.7.0", + "date": "2021-01-25", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.8.0", + "date": "2021-02-02", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.9.0", + "date": "2021-02-18", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.10.0", + "date": "2021-02-23", + "lts": false, + "security": true, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.11.0", + "date": "2021-03-03", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.12.0", + "date": "2021-03-17", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.13.0", + "date": "2021-03-31", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "15.14.0", + "date": "2021-04-06", + "lts": false, + "security": false, + "v8": "8.6.395.17" + }, + { + "name": "nodejs", + "version": "16.0.0", + "date": "2021-04-20", + "lts": false, + "security": false, + "v8": "9.0.257.17" + }, + { + "name": "nodejs", + "version": "16.1.0", + "date": "2021-05-04", + "lts": false, + "security": false, + "v8": "9.0.257.24" + }, + { + "name": "nodejs", + "version": "16.2.0", + "date": "2021-05-19", + "lts": false, + "security": false, + "v8": "9.0.257.25" + }, + { + "name": "nodejs", + "version": "16.3.0", + "date": "2021-06-03", + "lts": false, + "security": false, + "v8": "9.0.257.25" + }, + { + "name": "nodejs", + "version": "16.4.0", + "date": "2021-06-23", + "lts": false, + "security": false, + "v8": "9.1.269.36" + }, + { + "name": "nodejs", + "version": "16.5.0", + "date": "2021-07-14", + "lts": false, + "security": false, + "v8": "9.1.269.38" + }, + { + "name": "nodejs", + "version": "16.6.0", + "date": "2021-07-29", + "lts": false, + "security": true, + "v8": "9.2.230.21" + }, + { + "name": "nodejs", + "version": "16.7.0", + "date": "2021-08-18", + "lts": false, + "security": false, + "v8": "9.2.230.21" + }, + { + "name": "nodejs", + "version": "16.8.0", + "date": "2021-08-25", + "lts": false, + "security": false, + "v8": "9.2.230.21" + }, + { + "name": "nodejs", + "version": "16.9.0", + "date": "2021-09-07", + "lts": false, + "security": false, + "v8": "9.3.345.16" + }, + { + "name": "nodejs", + "version": "16.10.0", + "date": "2021-09-22", + "lts": false, + "security": false, + "v8": "9.3.345.19" + }, + { + "name": "nodejs", + "version": "16.11.0", + "date": "2021-10-08", + "lts": false, + "security": false, + "v8": "9.4.146.19" + }, + { + "name": "nodejs", + "version": "16.12.0", + "date": "2021-10-20", + "lts": false, + "security": false, + "v8": "9.4.146.19" + }, + { + "name": "nodejs", + "version": "16.13.0", + "date": "2021-10-26", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.19" + }, + { + "name": "nodejs", + "version": "16.14.0", + "date": "2022-02-08", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.24" + }, + { + "name": "nodejs", + "version": "16.15.0", + "date": "2022-04-26", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.24" + }, + { + "name": "nodejs", + "version": "16.16.0", + "date": "2022-07-07", + "lts": "Gallium", + "security": true, + "v8": "9.4.146.24" + }, + { + "name": "nodejs", + "version": "16.17.0", + "date": "2022-08-16", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "16.18.0", + "date": "2022-10-12", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "16.19.0", + "date": "2022-12-13", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "16.20.0", + "date": "2023-03-28", + "lts": "Gallium", + "security": false, + "v8": "9.4.146.26" + }, + { + "name": "nodejs", + "version": "17.0.0", + "date": "2021-10-19", + "lts": false, + "security": false, + "v8": "9.5.172.21" + }, + { + "name": "nodejs", + "version": "17.1.0", + "date": "2021-11-09", + "lts": false, + "security": false, + "v8": "9.5.172.25" + }, + { + "name": "nodejs", + "version": "17.2.0", + "date": "2021-11-30", + "lts": false, + "security": false, + "v8": "9.6.180.14" + }, + { + "name": "nodejs", + "version": "17.3.0", + "date": "2021-12-17", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.4.0", + "date": "2022-01-18", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.5.0", + "date": "2022-02-10", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.6.0", + "date": "2022-02-22", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.7.0", + "date": "2022-03-09", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.8.0", + "date": "2022-03-22", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "17.9.0", + "date": "2022-04-07", + "lts": false, + "security": false, + "v8": "9.6.180.15" + }, + { + "name": "nodejs", + "version": "18.0.0", + "date": "2022-04-18", + "lts": false, + "security": false, + "v8": "10.1.124.8" + }, + { + "name": "nodejs", + "version": "18.1.0", + "date": "2022-05-03", + "lts": false, + "security": false, + "v8": "10.1.124.8" + }, + { + "name": "nodejs", + "version": "18.2.0", + "date": "2022-05-17", + "lts": false, + "security": false, + "v8": "10.1.124.8" + }, + { + "name": "nodejs", + "version": "18.3.0", + "date": "2022-06-02", + "lts": false, + "security": false, + "v8": "10.2.154.4" + }, + { + "name": "nodejs", + "version": "18.4.0", + "date": "2022-06-16", + "lts": false, + "security": false, + "v8": "10.2.154.4" + }, + { + "name": "nodejs", + "version": "18.5.0", + "date": "2022-07-06", + "lts": false, + "security": true, + "v8": "10.2.154.4" + }, + { + "name": "nodejs", + "version": "18.6.0", + "date": "2022-07-13", + "lts": false, + "security": false, + "v8": "10.2.154.13" + }, + { + "name": "nodejs", + "version": "18.7.0", + "date": "2022-07-26", + "lts": false, + "security": false, + "v8": "10.2.154.13" + }, + { + "name": "nodejs", + "version": "18.8.0", + "date": "2022-08-24", + "lts": false, + "security": false, + "v8": "10.2.154.13" + }, + { + "name": "nodejs", + "version": "18.9.0", + "date": "2022-09-07", + "lts": false, + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.10.0", + "date": "2022-09-28", + "lts": false, + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.11.0", + "date": "2022-10-13", + "lts": false, + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.12.0", + "date": "2022-10-25", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.15" + }, + { + "name": "nodejs", + "version": "18.13.0", + "date": "2023-01-05", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.23" + }, + { + "name": "nodejs", + "version": "18.14.0", + "date": "2023-02-01", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.23" + }, + { + "name": "nodejs", + "version": "18.15.0", + "date": "2023-03-05", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.16.0", + "date": "2023-04-12", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.17.0", + "date": "2023-07-18", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.18.0", + "date": "2023-09-18", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.19.0", + "date": "2023-11-29", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "18.20.0", + "date": "2024-03-26", + "lts": "Hydrogen", + "security": false, + "v8": "10.2.154.26" + }, + { + "name": "nodejs", + "version": "19.0.0", + "date": "2022-10-17", + "lts": false, + "security": false, + "v8": "10.7.193.13" + }, + { + "name": "nodejs", + "version": "19.1.0", + "date": "2022-11-14", + "lts": false, + "security": false, + "v8": "10.7.193.20" + }, + { + "name": "nodejs", + "version": "19.2.0", + "date": "2022-11-29", + "lts": false, + "security": false, + "v8": "10.8.168.20" + }, + { + "name": "nodejs", + "version": "19.3.0", + "date": "2022-12-14", + "lts": false, + "security": false, + "v8": "10.8.168.21" + }, + { + "name": "nodejs", + "version": "19.4.0", + "date": "2023-01-05", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.5.0", + "date": "2023-01-24", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.6.0", + "date": "2023-02-01", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.7.0", + "date": "2023-02-21", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.8.0", + "date": "2023-03-14", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "19.9.0", + "date": "2023-04-10", + "lts": false, + "security": false, + "v8": "10.8.168.25" + }, + { + "name": "nodejs", + "version": "20.0.0", + "date": "2023-04-17", + "lts": false, + "security": false, + "v8": "11.3.244.4" + }, + { + "name": "nodejs", + "version": "20.1.0", + "date": "2023-05-03", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.2.0", + "date": "2023-05-16", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.3.0", + "date": "2023-06-08", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.4.0", + "date": "2023-07-04", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.5.0", + "date": "2023-07-19", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.6.0", + "date": "2023-08-23", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.7.0", + "date": "2023-09-18", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.8.0", + "date": "2023-09-28", + "lts": false, + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.9.0", + "date": "2023-10-24", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.10.0", + "date": "2023-11-22", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.11.0", + "date": "2024-01-09", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.12.0", + "date": "2024-03-26", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.13.0", + "date": "2024-05-07", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.14.0", + "date": "2024-05-28", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.15.0", + "date": "2024-06-20", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.16.0", + "date": "2024-07-24", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.17.0", + "date": "2024-08-21", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.18.0", + "date": "2024-10-03", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.19.0", + "date": "2025-03-13", + "lts": "Iron", + "security": false, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "20.20.0", + "date": "2026-01-12", + "lts": "Iron", + "security": true, + "v8": "11.3.244.8" + }, + { + "name": "nodejs", + "version": "21.0.0", + "date": "2023-10-17", + "lts": false, + "security": false, + "v8": "11.8.172.13" + }, + { + "name": "nodejs", + "version": "21.1.0", + "date": "2023-10-24", + "lts": false, + "security": false, + "v8": "11.8.172.15" + }, + { + "name": "nodejs", + "version": "21.2.0", + "date": "2023-11-14", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.3.0", + "date": "2023-11-30", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.4.0", + "date": "2023-12-05", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.5.0", + "date": "2023-12-19", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.6.0", + "date": "2024-01-14", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "21.7.0", + "date": "2024-03-06", + "lts": false, + "security": false, + "v8": "11.8.172.17" + }, + { + "name": "nodejs", + "version": "22.0.0", + "date": "2024-04-24", + "lts": false, + "security": false, + "v8": "12.4.254.14" + }, + { + "name": "nodejs", + "version": "22.1.0", + "date": "2024-05-02", + "lts": false, + "security": false, + "v8": "12.4.254.14" + }, + { + "name": "nodejs", + "version": "22.2.0", + "date": "2024-05-15", + "lts": false, + "security": false, + "v8": "12.4.254.14" + }, + { + "name": "nodejs", + "version": "22.3.0", + "date": "2024-06-11", + "lts": false, + "security": false, + "v8": "12.4.254.20" + }, + { + "name": "nodejs", + "version": "22.4.0", + "date": "2024-07-02", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.5.0", + "date": "2024-07-17", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.6.0", + "date": "2024-08-06", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.7.0", + "date": "2024-08-21", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.8.0", + "date": "2024-09-03", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.9.0", + "date": "2024-09-17", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.10.0", + "date": "2024-10-16", + "lts": false, + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.11.0", + "date": "2024-10-29", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.12.0", + "date": "2024-12-02", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.13.0", + "date": "2025-01-06", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.14.0", + "date": "2025-02-11", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.15.0", + "date": "2025-04-22", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.16.0", + "date": "2025-05-20", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.17.0", + "date": "2025-06-24", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.18.0", + "date": "2025-07-31", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.19.0", + "date": "2025-08-28", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.20.0", + "date": "2025-09-24", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.21.0", + "date": "2025-10-20", + "lts": "Jod", + "security": false, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "22.22.0", + "date": "2026-01-12", + "lts": "Jod", + "security": true, + "v8": "12.4.254.21" + }, + { + "name": "nodejs", + "version": "23.0.0", + "date": "2024-10-16", + "lts": false, + "security": false, + "v8": "12.9.202.26" + }, + { + "name": "nodejs", + "version": "23.1.0", + "date": "2024-10-24", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.2.0", + "date": "2024-11-11", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.3.0", + "date": "2024-11-20", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.4.0", + "date": "2024-12-10", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.5.0", + "date": "2024-12-19", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.6.0", + "date": "2025-01-07", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.7.0", + "date": "2025-01-30", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.8.0", + "date": "2025-02-13", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.9.0", + "date": "2025-02-26", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.10.0", + "date": "2025-03-13", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "23.11.0", + "date": "2025-04-01", + "lts": false, + "security": false, + "v8": "12.9.202.28" + }, + { + "name": "nodejs", + "version": "24.0.0", + "date": "2025-05-06", + "lts": false, + "security": false, + "v8": "13.6.233.8" + }, + { + "name": "nodejs", + "version": "24.1.0", + "date": "2025-05-20", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.2.0", + "date": "2025-06-09", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.3.0", + "date": "2025-06-24", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.4.0", + "date": "2025-07-09", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.5.0", + "date": "2025-07-31", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.6.0", + "date": "2025-08-14", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.7.0", + "date": "2025-08-27", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.8.0", + "date": "2025-09-10", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.9.0", + "date": "2025-09-25", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.10.0", + "date": "2025-10-08", + "lts": false, + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.11.0", + "date": "2025-10-28", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.10" + }, + { + "name": "nodejs", + "version": "24.12.0", + "date": "2025-12-10", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.13.0", + "date": "2026-01-12", + "lts": "Krypton", + "security": true, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.14.0", + "date": "2026-02-24", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.15.0", + "date": "2026-04-15", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "24.16.0", + "date": "2026-05-21", + "lts": "Krypton", + "security": false, + "v8": "13.6.233.17" + }, + { + "name": "nodejs", + "version": "25.0.0", + "date": "2025-10-15", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.1.0", + "date": "2025-10-28", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.2.0", + "date": "2025-11-11", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.3.0", + "date": "2026-01-12", + "lts": false, + "security": true, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.4.0", + "date": "2026-01-19", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.5.0", + "date": "2026-01-26", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.6.0", + "date": "2026-02-02", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.7.0", + "date": "2026-02-24", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.8.0", + "date": "2026-03-03", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "25.9.0", + "date": "2026-03-31", + "lts": false, + "security": false, + "v8": "14.1.146.11" + }, + { + "name": "nodejs", + "version": "26.0.0", + "date": "2026-05-05", + "lts": false, + "security": false, + "v8": "14.6.202.33" + }, + { + "name": "nodejs", + "version": "26.1.0", + "date": "2026-05-06", + "lts": false, + "security": false, + "v8": "14.6.202.34" + }, + { + "name": "nodejs", + "version": "26.2.0", + "date": "2026-05-20", + "lts": false, + "security": false, + "v8": "14.6.202.34" + }, + { + "name": "nodejs", + "version": "26.3.0", + "date": "2026-06-01", + "lts": false, + "security": false, + "v8": "14.6.202.34" + } +] diff --git a/tools/ui/node_modules/node-releases/data/release-schedule/release-schedule.json b/tools/ui/node_modules/node-releases/data/release-schedule/release-schedule.json new file mode 100644 index 0000000000000000000000000000000000000000..3a6af719fb943a16a672eeb81dec0a04500d7a59 --- /dev/null +++ b/tools/ui/node_modules/node-releases/data/release-schedule/release-schedule.json @@ -0,0 +1,160 @@ +{ + "v0.8": { + "start": "2012-06-25", + "end": "2014-07-31" + }, + "v0.10": { + "start": "2013-03-11", + "end": "2016-10-31" + }, + "v0.12": { + "start": "2015-02-06", + "end": "2016-12-31" + }, + "v4": { + "start": "2015-09-08", + "lts": "2015-10-12", + "maintenance": "2017-04-01", + "end": "2018-04-30", + "codename": "Argon" + }, + "v5": { + "start": "2015-10-29", + "maintenance": "2016-04-30", + "end": "2016-06-30" + }, + "v6": { + "start": "2016-04-26", + "lts": "2016-10-18", + "maintenance": "2018-04-30", + "end": "2019-04-30", + "codename": "Boron" + }, + "v7": { + "start": "2016-10-25", + "maintenance": "2017-04-30", + "end": "2017-06-30" + }, + "v8": { + "start": "2017-05-30", + "lts": "2017-10-31", + "maintenance": "2019-01-01", + "end": "2019-12-31", + "codename": "Carbon" + }, + "v9": { + "start": "2017-10-01", + "maintenance": "2018-04-01", + "end": "2018-06-30" + }, + "v10": { + "start": "2018-04-24", + "lts": "2018-10-30", + "maintenance": "2020-05-19", + "end": "2021-04-30", + "codename": "Dubnium" + }, + "v11": { + "start": "2018-10-23", + "maintenance": "2019-04-22", + "end": "2019-06-01" + }, + "v12": { + "start": "2019-04-23", + "lts": "2019-10-21", + "maintenance": "2020-11-30", + "end": "2022-04-30", + "codename": "Erbium" + }, + "v13": { + "start": "2019-10-22", + "maintenance": "2020-04-01", + "end": "2020-06-01" + }, + "v14": { + "start": "2020-04-21", + "lts": "2020-10-27", + "maintenance": "2021-10-19", + "end": "2023-04-30", + "codename": "Fermium" + }, + "v15": { + "start": "2020-10-20", + "maintenance": "2021-04-01", + "end": "2021-06-01" + }, + "v16": { + "start": "2021-04-20", + "lts": "2021-10-26", + "maintenance": "2022-10-18", + "end": "2023-09-11", + "codename": "Gallium" + }, + "v17": { + "start": "2021-10-19", + "maintenance": "2022-04-01", + "end": "2022-06-01" + }, + "v18": { + "start": "2022-04-19", + "lts": "2022-10-25", + "maintenance": "2023-10-18", + "end": "2025-04-30", + "codename": "Hydrogen" + }, + "v19": { + "start": "2022-10-18", + "maintenance": "2023-04-01", + "end": "2023-06-01" + }, + "v20": { + "start": "2023-04-18", + "lts": "2023-10-24", + "maintenance": "2024-10-22", + "end": "2026-04-30", + "codename": "Iron" + }, + "v21": { + "start": "2023-10-17", + "maintenance": "2024-04-01", + "end": "2024-06-01" + }, + "v22": { + "start": "2024-04-24", + "lts": "2024-10-29", + "maintenance": "2025-10-21", + "end": "2027-04-30", + "codename": "Jod" + }, + "v23": { + "start": "2024-10-16", + "maintenance": "2025-04-01", + "end": "2025-06-01" + }, + "v24": { + "start": "2025-05-06", + "lts": "2025-10-28", + "maintenance": "2026-10-20", + "end": "2028-04-30", + "codename": "Krypton" + }, + "v25": { + "start": "2025-10-15", + "maintenance": "2026-04-01", + "end": "2026-06-01" + }, + "v26": { + "start": "2026-05-05", + "lts": "2026-10-28", + "maintenance": "2027-10-20", + "end": "2029-04-30", + "codename": "" + }, + "v27": { + "alpha": "2026-10-28", + "start": "2027-04-22", + "maintenance": "2027-10-20", + "end": "2030-04-30", + "codename": "" + } +} diff --git a/tools/ui/node_modules/node-releases/package.json b/tools/ui/node_modules/node-releases/package.json new file mode 100644 index 0000000000000000000000000000000000000000..10547bbc7bb18709d6ea0afbfac11496aeaedbde --- /dev/null +++ b/tools/ui/node_modules/node-releases/package.json @@ -0,0 +1,28 @@ +{ + "name": "node-releases", + "version": "2.0.47", + "description": "Node.js releases data", + "type": "module", + "files": [ + "data" + ], + "scripts": { + "build": "node scripts/build.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/chicoxyzzy/node-releases.git" + }, + "keywords": [ + "nodejs", + "releases" + ], + "author": "Sergey Rubanov ", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "devDependencies": { + "semver": "^7.3.5" + } +} diff --git a/tools/ui/node_modules/object-assign/index.js b/tools/ui/node_modules/object-assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0930cf8890b9af66125c222c29d7bd75614ac6b4 --- /dev/null +++ b/tools/ui/node_modules/object-assign/index.js @@ -0,0 +1,90 @@ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; diff --git a/tools/ui/node_modules/object-assign/license b/tools/ui/node_modules/object-assign/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/tools/ui/node_modules/object-assign/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/tools/ui/node_modules/object-assign/package.json b/tools/ui/node_modules/object-assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..503eb1e6d0f5a1404c8e7f6c09fbda7e40fd29b4 --- /dev/null +++ b/tools/ui/node_modules/object-assign/package.json @@ -0,0 +1,42 @@ +{ + "name": "object-assign", + "version": "4.1.1", + "description": "ES2015 `Object.assign()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/object-assign", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava", + "bench": "matcha bench.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "assign", + "extend", + "properties", + "es2015", + "ecmascript", + "harmony", + "ponyfill", + "prollyfill", + "polyfill", + "shim", + "browser" + ], + "devDependencies": { + "ava": "^0.16.0", + "lodash": "^4.16.4", + "matcha": "^0.7.0", + "xo": "^0.16.0" + } +} diff --git a/tools/ui/node_modules/object-assign/readme.md b/tools/ui/node_modules/object-assign/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1be09d35c776cc0e9cc59519c2de6b9eecf8aa68 --- /dev/null +++ b/tools/ui/node_modules/object-assign/readme.md @@ -0,0 +1,61 @@ +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign) + +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com) + + +## Use the built-in + +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari), +support `Object.assign()` :tada:. If you target only those environments, then by all +means, use `Object.assign()` instead of this package. + + +## Install + +``` +$ npm install --save object-assign +``` + + +## Usage + +```js +const objectAssign = require('object-assign'); + +objectAssign({foo: 0}, {bar: 1}); +//=> {foo: 0, bar: 1} + +// multiple sources +objectAssign({foo: 0}, {bar: 1}, {baz: 2}); +//=> {foo: 0, bar: 1, baz: 2} + +// overwrites equal keys +objectAssign({foo: 0}, {foo: 1}, {foo: 2}); +//=> {foo: 2} + +// ignores null and undefined sources +objectAssign({foo: 0}, null, {bar: 1}, undefined); +//=> {foo: 0, bar: 1} +``` + + +## API + +### objectAssign(target, [source, ...]) + +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones. + + +## Resources + +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign) + + +## Related + +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/ui/node_modules/object-inspect/.eslintrc b/tools/ui/node_modules/object-inspect/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..21f903923ef11aef5d6ca8ade40028520b82a37a --- /dev/null +++ b/tools/ui/node_modules/object-inspect/.eslintrc @@ -0,0 +1,53 @@ +{ + "root": true, + "extends": "@ljharb", + "rules": { + "complexity": 0, + "func-style": [2, "declaration"], + "indent": [2, 4], + "max-lines": 1, + "max-lines-per-function": 1, + "max-params": [2, 4], + "max-statements": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "no-param-reassign": 1, + "strict": 0, // TODO + }, + "overrides": [ + { + "files": ["test/**", "test-*", "example/**"], + "extends": "@ljharb/eslint-config/tests", + "rules": { + "id-length": 0, + }, + }, + { + "files": ["example/**"], + "rules": { + "no-console": 0, + }, + }, + { + "files": ["test/browser/**"], + "env": { + "browser": true, + }, + }, + { + "files": ["test/bigint*"], + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["BigInt"] }], + }, + }, + { + "files": "index.js", + "globals": { + "HTMLElement": false, + }, + "rules": { + "no-use-before-define": 1, + }, + }, + ], +} diff --git a/tools/ui/node_modules/object-inspect/.github/FUNDING.yml b/tools/ui/node_modules/object-inspect/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..730276bd121df856ede4c51d6e7b63d071242487 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object-inspect +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tools/ui/node_modules/object-inspect/.nycrc b/tools/ui/node_modules/object-inspect/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..58a5db7834ad50f2f9a5814f49d98db106381316 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "instrumentation": false, + "sourceMap": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/tools/ui/node_modules/object-inspect/CHANGELOG.md b/tools/ui/node_modules/object-inspect/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..bdf9002747e971f342607364e8557fc8bd3e80ec --- /dev/null +++ b/tools/ui/node_modules/object-inspect/CHANGELOG.md @@ -0,0 +1,424 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.13.4](https://github.com/inspect-js/object-inspect/compare/v1.13.3...v1.13.4) - 2025-02-04 + +### Commits + +- [Fix] avoid being fooled by a `Symbol.toStringTag` [`fa5870d`](https://github.com/inspect-js/object-inspect/commit/fa5870da468a525d2f20193700f70752f506cbf7) +- [Tests] fix tests in node v6.0 - v6.4 [`2abfe1b`](https://github.com/inspect-js/object-inspect/commit/2abfe1bc3c69f9293c07c5cd65a9d7d87a628b84) +- [Dev Deps] update `es-value-fixtures`, `for-each`, `has-symbols` [`3edfb01`](https://github.com/inspect-js/object-inspect/commit/3edfb01cc8cce220fba0dfdfe2dc8bc955758cdd) + +## [v1.13.3](https://github.com/inspect-js/object-inspect/compare/v1.13.2...v1.13.3) - 2024-11-09 + +### Commits + +- [actions] split out node 10-20, and 20+ [`44395a8`](https://github.com/inspect-js/object-inspect/commit/44395a8fc1deda6718a5e125e86b9ffcaa1c7580) +- [Fix] `quoteStyle`: properly escape only the containing quotes [`5137f8f`](https://github.com/inspect-js/object-inspect/commit/5137f8f7bea69a7fc671bb683fd35f244f38fc52) +- [Refactor] clean up `quoteStyle` code [`450680c`](https://github.com/inspect-js/object-inspect/commit/450680cd50de4e689ee3b8e1d6db3a1bcf3fc18c) +- [Tests] add `quoteStyle` escaping tests [`e997c59`](https://github.com/inspect-js/object-inspect/commit/e997c595aeaea84fd98ca35d7e1c3b5ab3ae26e0) +- [Dev Deps] update `auto-changelog`, `es-value-fixtures`, `tape` [`d5a469c`](https://github.com/inspect-js/object-inspect/commit/d5a469c99ec07ccaeafc36ac4b36a93285086d48) +- [Tests] replace `aud` with `npm audit` [`fb7815f`](https://github.com/inspect-js/object-inspect/commit/fb7815f9b72cae277a04f65bbb0543f85b88be62) +- [Dev Deps] update `mock-property` [`11c817b`](https://github.com/inspect-js/object-inspect/commit/11c817bf10392aa017755962ba6bc89d731359ee) + +## [v1.13.2](https://github.com/inspect-js/object-inspect/compare/v1.13.1...v1.13.2) - 2024-06-21 + +### Commits + +- [readme] update badges [`8a51e6b`](https://github.com/inspect-js/object-inspect/commit/8a51e6bedaf389ec40cc4659e9df53e8543d176e) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`ef05f58`](https://github.com/inspect-js/object-inspect/commit/ef05f58c9761a41416ab907299bf0fa79517014b) +- [Dev Deps] update `error-cause`, `has-tostringtag`, `tape` [`c0c6c26`](https://github.com/inspect-js/object-inspect/commit/c0c6c26c44cee6671f7c5d43d2b91d27c5c00d90) +- [Fix] Don't throw when `global` is not defined [`d4d0965`](https://github.com/inspect-js/object-inspect/commit/d4d096570f7dbd0e03266a96de11d05eb7b63e0f) +- [meta] add missing `engines.node` [`17a352a`](https://github.com/inspect-js/object-inspect/commit/17a352af6fe1ba6b70a19081674231eb1a50c940) +- [Dev Deps] update `globalthis` [`9c08884`](https://github.com/inspect-js/object-inspect/commit/9c08884aa662a149e2f11403f413927736b97da7) +- [Dev Deps] update `error-cause` [`6af352d`](https://github.com/inspect-js/object-inspect/commit/6af352d7c3929a4cc4c55768c27bf547a5e900f4) +- [Dev Deps] update `npmignore` [`94e617d`](https://github.com/inspect-js/object-inspect/commit/94e617d38831722562fa73dff4c895746861d267) +- [Dev Deps] update `mock-property` [`2ac24d7`](https://github.com/inspect-js/object-inspect/commit/2ac24d7e58cd388ad093c33249e413e05bbfd6c3) +- [Dev Deps] update `tape` [`46125e5`](https://github.com/inspect-js/object-inspect/commit/46125e58f1d1dcfb170ed3d1ea69da550ea8d77b) + +## [v1.13.1](https://github.com/inspect-js/object-inspect/compare/v1.13.0...v1.13.1) - 2023-10-19 + +### Commits + +- [Fix] in IE 8, global can !== window despite them being prototypes of each other [`30d0859`](https://github.com/inspect-js/object-inspect/commit/30d0859dc4606cf75c2410edcd5d5c6355f8d372) + +## [v1.13.0](https://github.com/inspect-js/object-inspect/compare/v1.12.3...v1.13.0) - 2023-10-14 + +### Commits + +- [New] add special handling for the global object [`431bab2`](https://github.com/inspect-js/object-inspect/commit/431bab21a490ee51d35395966a504501e8c685da) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`fd4f619`](https://github.com/inspect-js/object-inspect/commit/fd4f6193562b4b0e95dcf5c0201b4e8cbbc4f58d) +- [Dev Deps] update `mock-property`, `tape` [`b453f6c`](https://github.com/inspect-js/object-inspect/commit/b453f6ceeebf8a1b738a1029754092e0367a4134) +- [Dev Deps] update `error-cause` [`e8ffc57`](https://github.com/inspect-js/object-inspect/commit/e8ffc577d73b92bb6a4b00c44f14e3319e374888) +- [Dev Deps] update `tape` [`054b8b9`](https://github.com/inspect-js/object-inspect/commit/054b8b9b98633284cf989e582450ebfbbe53503c) +- [Dev Deps] temporarily remove `aud` due to breaking change in transitive deps [`2476845`](https://github.com/inspect-js/object-inspect/commit/2476845e0678dd290c541c81cd3dec8420782c52) +- [Dev Deps] pin `glob`, since v10.3.8+ requires a broken `jackspeak` [`383fa5e`](https://github.com/inspect-js/object-inspect/commit/383fa5eebc0afd705cc778a4b49d8e26452e49a8) +- [Dev Deps] pin `jackspeak` since 2.1.2+ depends on npm aliases, which kill the install process in npm < 6 [`68c244c`](https://github.com/inspect-js/object-inspect/commit/68c244c5174cdd877e5dcb8ee90aa3f44b2f25be) + +## [v1.12.3](https://github.com/inspect-js/object-inspect/compare/v1.12.2...v1.12.3) - 2023-01-12 + +### Commits + +- [Fix] in eg FF 24, collections lack forEach [`75fc226`](https://github.com/inspect-js/object-inspect/commit/75fc22673c82d45f28322b1946bb0eb41b672b7f) +- [actions] update rebase action to use reusable workflow [`250a277`](https://github.com/inspect-js/object-inspect/commit/250a277a095e9dacc029ab8454dcfc15de549dcd) +- [Dev Deps] update `aud`, `es-value-fixtures`, `tape` [`66a19b3`](https://github.com/inspect-js/object-inspect/commit/66a19b3209ccc3c5ef4b34c3cb0160e65d1ce9d5) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `error-cause` [`c43d332`](https://github.com/inspect-js/object-inspect/commit/c43d3324b48384a16fd3dc444e5fc589d785bef3) +- [Tests] add `@pkgjs/support` to `postlint` [`e2618d2`](https://github.com/inspect-js/object-inspect/commit/e2618d22a7a3fa361b6629b53c1752fddc9c4d80) + +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + +## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 + +### Commits + +- [New] add `numericSeparator` boolean option [`2d2d537`](https://github.com/inspect-js/object-inspect/commit/2d2d537f5359a4300ce1c10241369f8024f89e11) +- [Robustness] cache more prototype methods [`191533d`](https://github.com/inspect-js/object-inspect/commit/191533da8aec98a05eadd73a5a6e979c9c8653e8) +- [New] ensure an Error’s `cause` is displayed [`53bc2ce`](https://github.com/inspect-js/object-inspect/commit/53bc2cee4e5a9cc4986f3cafa22c0685f340715e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`bc164b6`](https://github.com/inspect-js/object-inspect/commit/bc164b6e2e7d36b263970f16f54de63048b84a36) +- [Robustness] cache `RegExp.prototype.test` [`a314ab8`](https://github.com/inspect-js/object-inspect/commit/a314ab8271b905cbabc594c82914d2485a8daf12) +- [meta] fix auto-changelog settings [`5ed0983`](https://github.com/inspect-js/object-inspect/commit/5ed0983be72f73e32e2559997517a95525c7e20d) + +## [v1.11.1](https://github.com/inspect-js/object-inspect/compare/v1.11.0...v1.11.1) - 2021-12-05 + +### Commits + +- [meta] add `auto-changelog` [`7dbdd22`](https://github.com/inspect-js/object-inspect/commit/7dbdd228401d6025d8b7391476d88aee9ea9bbdf) +- [actions] reuse common workflows [`c8823bc`](https://github.com/inspect-js/object-inspect/commit/c8823bc0a8790729680709d45fb6e652432e91aa) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`7532b12`](https://github.com/inspect-js/object-inspect/commit/7532b120598307497b712890f75af8056f6d37a6) +- [Refactor] use `has-tostringtag` to behave correctly in the presence of symbol shams [`94abb5d`](https://github.com/inspect-js/object-inspect/commit/94abb5d4e745bf33253942dea86b3e538d2ff6c6) +- [actions] update codecov uploader [`5ed5102`](https://github.com/inspect-js/object-inspect/commit/5ed51025267a00e53b1341357315490ac4eb0874) +- [Dev Deps] update `eslint`, `tape` [`37b2ad2`](https://github.com/inspect-js/object-inspect/commit/37b2ad26c08d94bfd01d5d07069a0b28ef4e2ad7) +- [meta] add `sideEffects` flag [`d341f90`](https://github.com/inspect-js/object-inspect/commit/d341f905ef8bffa6a694cda6ddc5ba343532cd4f) + +## [v1.11.0](https://github.com/inspect-js/object-inspect/compare/v1.10.3...v1.11.0) - 2021-07-12 + +### Commits + +- [New] `customInspect`: add `symbol` option, to mimic modern util.inspect behavior [`e973a6e`](https://github.com/inspect-js/object-inspect/commit/e973a6e21f8140c5837cf25e9d89bdde88dc3120) +- [Dev Deps] update `eslint` [`05f1cb3`](https://github.com/inspect-js/object-inspect/commit/05f1cb3cbcfe1f238e8b51cf9bc294305b7ed793) + +## [v1.10.3](https://github.com/inspect-js/object-inspect/compare/v1.10.2...v1.10.3) - 2021-05-07 + +### Commits + +- [Fix] handle core-js Symbol shams [`4acfc2c`](https://github.com/inspect-js/object-inspect/commit/4acfc2c4b503498759120eb517abad6d51c9c5d6) +- [readme] update badges [`95c323a`](https://github.com/inspect-js/object-inspect/commit/95c323ad909d6cbabb95dd6015c190ba6db9c1f2) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud` [`cb38f48`](https://github.com/inspect-js/object-inspect/commit/cb38f485de6ec7a95109b5a9bbd0a1deba2f6611) + +## [v1.10.2](https://github.com/inspect-js/object-inspect/compare/v1.10.1...v1.10.2) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed Symbol [`87f12d6`](https://github.com/inspect-js/object-inspect/commit/87f12d6e69ce530be04659c81a4cd502943acac5) + +## [v1.10.1](https://github.com/inspect-js/object-inspect/compare/v1.10.0...v1.10.1) - 2021-04-17 + +### Commits + +- [Fix] use a robust check for a boxed bigint [`d5ca829`](https://github.com/inspect-js/object-inspect/commit/d5ca8298b6d2e5c7b9334a5b21b96ed95d225c91) + +## [v1.10.0](https://github.com/inspect-js/object-inspect/compare/v1.9.0...v1.10.0) - 2021-04-17 + +### Commits + +- [Tests] increase coverage [`d8abb8a`](https://github.com/inspect-js/object-inspect/commit/d8abb8a62c2f084919df994a433b346e0d87a227) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`4bfec2e`](https://github.com/inspect-js/object-inspect/commit/4bfec2e30aaef6ddef6cbb1448306f9f8b9520b7) +- [New] respect `Symbol.toStringTag` on objects [`799b58f`](https://github.com/inspect-js/object-inspect/commit/799b58f536a45e4484633a8e9daeb0330835f175) +- [Fix] do not allow Symbol.toStringTag to masquerade as builtins [`d6c5b37`](https://github.com/inspect-js/object-inspect/commit/d6c5b37d7e94427796b82432fb0c8964f033a6ab) +- [New] add `WeakRef` support [`b6d898e`](https://github.com/inspect-js/object-inspect/commit/b6d898ee21868c780a7ee66b28532b5b34ed7f09) +- [meta] do not publish github action workflow files [`918cdfc`](https://github.com/inspect-js/object-inspect/commit/918cdfc4b6fe83f559ff6ef04fe66201e3ff5cbd) +- [meta] create `FUNDING.yml` [`0bb5fc5`](https://github.com/inspect-js/object-inspect/commit/0bb5fc516dbcd2cd728bd89cee0b580acc5ce301) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`22c8dc0`](https://github.com/inspect-js/object-inspect/commit/22c8dc0cac113d70f4781e49a950070923a671be) +- [meta] use `prepublishOnly` script for npm 7+ [`e52ee09`](https://github.com/inspect-js/object-inspect/commit/e52ee09e8050b8dbac94ef57f786675567728223) +- [Dev Deps] update `eslint` [`7c4e6fd`](https://github.com/inspect-js/object-inspect/commit/7c4e6fdedcd27cc980e13c9ad834d05a96f3d40c) + +## [v1.9.0](https://github.com/inspect-js/object-inspect/compare/v1.8.0...v1.9.0) - 2020-11-30 + +### Commits + +- [Tests] migrate tests to Github Actions [`d262251`](https://github.com/inspect-js/object-inspect/commit/d262251e13e16d3490b5473672f6b6d6ff86675d) +- [New] add enumerable own Symbols to plain object output [`ee60c03`](https://github.com/inspect-js/object-inspect/commit/ee60c033088cff9d33baa71e59a362a541b48284) +- [Tests] add passing tests [`01ac3e4`](https://github.com/inspect-js/object-inspect/commit/01ac3e4b5a30f97875a63dc9b1416b3bd626afc9) +- [actions] add "Require Allow Edits" action [`c2d7746`](https://github.com/inspect-js/object-inspect/commit/c2d774680cde4ca4af332d84d4121b26f798ba9e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `core-js` [`70058de`](https://github.com/inspect-js/object-inspect/commit/70058de1579fc54d1d15ed6c2dbe246637ce70ff) +- [Fix] hex characters in strings should be uppercased, to match node `assert` [`6ab8faa`](https://github.com/inspect-js/object-inspect/commit/6ab8faaa0abc08fe7a8e2afd8b39c6f1f0e00113) +- [Tests] run `nyc` on all tests [`4c47372`](https://github.com/inspect-js/object-inspect/commit/4c473727879ddc8e28b599202551ddaaf07b6210) +- [Tests] node 0.8 has an unpredictable property order; fix `groups` test by removing property [`f192069`](https://github.com/inspect-js/object-inspect/commit/f192069a978a3b60e6f0e0d45ac7df260ab9a778) +- [New] add enumerable properties to Function inspect result, per node’s `assert` [`fd38e1b`](https://github.com/inspect-js/object-inspect/commit/fd38e1bc3e2a1dc82091ce3e021917462eee64fc) +- [Tests] fix tests for node < 10, due to regex match `groups` [`2ac6462`](https://github.com/inspect-js/object-inspect/commit/2ac6462cc4f72eaa0b63a8cfee9aabe3008b2330) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`44b59e2`](https://github.com/inspect-js/object-inspect/commit/44b59e2676a7f825ef530dfd19dafb599e3b9456) +- [Robustness] cache `Symbol.prototype.toString` [`f3c2074`](https://github.com/inspect-js/object-inspect/commit/f3c2074d8f32faf8292587c07c9678ea931703dd) +- [Dev Deps] update `eslint` [`9411294`](https://github.com/inspect-js/object-inspect/commit/94112944b9245e3302e25453277876402d207e7f) +- [meta] `require-allow-edits` no longer requires an explicit github token [`36c0220`](https://github.com/inspect-js/object-inspect/commit/36c02205de3c2b0e84d53777c5c9fd54a36c48ab) +- [actions] update rebase checkout action to v2 [`55a39a6`](https://github.com/inspect-js/object-inspect/commit/55a39a64e944f19c6a7d8efddf3df27700f20d14) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`f59fd3c`](https://github.com/inspect-js/object-inspect/commit/f59fd3cf406c3a7c7ece140904a80bbc6bacfcca) +- [Dev Deps] update `eslint` [`a492bec`](https://github.com/inspect-js/object-inspect/commit/a492becec644b0155c9c4bc1caf6f9fac11fb2c7) + +## [v1.8.0](https://github.com/inspect-js/object-inspect/compare/v1.7.0...v1.8.0) - 2020-06-18 + +### Fixed + +- [New] add `indent` option [`#27`](https://github.com/inspect-js/object-inspect/issues/27) + +### Commits + +- [Tests] add codecov [`4324cbb`](https://github.com/inspect-js/object-inspect/commit/4324cbb1a2bd7710822a4151ff373570db22453e) +- [New] add `maxStringLength` option [`b3995cb`](https://github.com/inspect-js/object-inspect/commit/b3995cb71e15b5ee127a3094c43994df9d973502) +- [New] add `customInspect` option, to disable custom inspect methods [`28b9179`](https://github.com/inspect-js/object-inspect/commit/28b9179ee802bb3b90810100c11637db90c2fb6d) +- [Tests] add Date and RegExp tests [`3b28eca`](https://github.com/inspect-js/object-inspect/commit/3b28eca57b0367aeadffac604ea09e8bdae7d97b) +- [actions] add automatic rebasing / merge commit blocking [`0d9c6c0`](https://github.com/inspect-js/object-inspect/commit/0d9c6c044e83475ff0bfffb9d35b149834c83a2e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape`; add `aud` [`7c204f2`](https://github.com/inspect-js/object-inspect/commit/7c204f22b9e41bc97147f4d32d4cb045b17769a6) +- [readme] fix repo URLs, remove testling [`34ca9a0`](https://github.com/inspect-js/object-inspect/commit/34ca9a0dabfe75bd311f806a326fadad029909a3) +- [Fix] when truncating a deep array, note it as `[Array]` instead of just `[Object]` [`f74c82d`](https://github.com/inspect-js/object-inspect/commit/f74c82dd0b35386445510deb250f34c41be3ec0e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`1a8a5ea`](https://github.com/inspect-js/object-inspect/commit/1a8a5ea069ea2bee89d77caedad83ffa23d35711) +- [Fix] do not be fooled by a function’s own `toString` method [`7cb5c65`](https://github.com/inspect-js/object-inspect/commit/7cb5c657a976f94715c19c10556a30f15bb7d5d7) +- [patch] indicate explicitly that anon functions are anonymous, to match node [`81ebdd4`](https://github.com/inspect-js/object-inspect/commit/81ebdd4215005144074bbdff3f6bafa01407910a) +- [Dev Deps] loosen the `core-js` dep [`e7472e8`](https://github.com/inspect-js/object-inspect/commit/e7472e8e242117670560bd995830c2a4d12080f5) +- [Dev Deps] update `tape` [`699827e`](https://github.com/inspect-js/object-inspect/commit/699827e6b37258b5203c33c78c009bf4b0e6a66d) +- [meta] add `safe-publish-latest` [`c5d2868`](https://github.com/inspect-js/object-inspect/commit/c5d2868d6eb33c472f37a20f89ceef2787046088) +- [Dev Deps] update `@ljharb/eslint-config` [`9199501`](https://github.com/inspect-js/object-inspect/commit/919950195d486114ccebacbdf9d74d7f382693b0) + +## [v1.7.0](https://github.com/inspect-js/object-inspect/compare/v1.6.0...v1.7.0) - 2019-11-10 + +### Commits + +- [Tests] use shared travis-ci configs [`19899ed`](https://github.com/inspect-js/object-inspect/commit/19899edbf31f4f8809acf745ce34ad1ce1bfa63b) +- [Tests] add linting [`a00f057`](https://github.com/inspect-js/object-inspect/commit/a00f057d917f66ea26dd37769c6b810ec4af97e8) +- [Tests] lint last file [`2698047`](https://github.com/inspect-js/object-inspect/commit/2698047b58af1e2e88061598ef37a75f228dddf6) +- [Tests] up to `node` `v12.7`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`589e87a`](https://github.com/inspect-js/object-inspect/commit/589e87a99cadcff4b600e6a303418e9d922836e8) +- [New] add support for `WeakMap` and `WeakSet` [`3ddb3e4`](https://github.com/inspect-js/object-inspect/commit/3ddb3e4e0c8287130c61a12e0ed9c104b1549306) +- [meta] clean up license so github can detect it properly [`27527bb`](https://github.com/inspect-js/object-inspect/commit/27527bb801520c9610c68cc3b55d6f20a2bee56d) +- [Tests] cover `util.inspect.custom` [`36d47b9`](https://github.com/inspect-js/object-inspect/commit/36d47b9c59056a57ef2f1491602c726359561800) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `tape` [`b614eaa`](https://github.com/inspect-js/object-inspect/commit/b614eaac901da0e5c69151f534671f990a94cace) +- [Tests] fix coverage thresholds [`7b7b176`](https://github.com/inspect-js/object-inspect/commit/7b7b176e15f8bd6e8b2f261ff5a493c2fe78d9c2) +- [Tests] bigint tests now can run on unflagged node [`063af31`](https://github.com/inspect-js/object-inspect/commit/063af31ce9cd13c202e3b67c07ba06dc9b7c0f81) +- [Refactor] add early bailout to `isMap` and `isSet` checks [`fc51047`](https://github.com/inspect-js/object-inspect/commit/fc5104714a3671d37e225813db79470d6335683b) +- [meta] add `funding` field [`7f9953a`](https://github.com/inspect-js/object-inspect/commit/7f9953a113eec7b064a6393cf9f90ba15f1d131b) +- [Tests] Fix invalid strict-mode syntax with hexadecimal [`a8b5425`](https://github.com/inspect-js/object-inspect/commit/a8b542503b4af1599a275209a1a99f5fdedb1ead) +- [Dev Deps] update `@ljharb/eslint-config` [`98df157`](https://github.com/inspect-js/object-inspect/commit/98df1577314d9188a3fc3f17fdcf2fba697ae1bd) +- add copyright to LICENSE [`bb69fd0`](https://github.com/inspect-js/object-inspect/commit/bb69fd017a062d299e44da1f9b2c7dcd67f621e6) +- [Tests] use `npx aud` in `posttest` [`4838353`](https://github.com/inspect-js/object-inspect/commit/4838353593974cf7f905b9ef04c03c094f0cdbe2) +- [Tests] move `0.6` to allowed failures, because it won‘t build on travis [`1bff32a`](https://github.com/inspect-js/object-inspect/commit/1bff32aa52e8aea687f0856b28ba754b3e43ebf7) + +## [v1.6.0](https://github.com/inspect-js/object-inspect/compare/v1.5.0...v1.6.0) - 2018-05-02 + +### Commits + +- [New] add support for boxed BigInt primitives [`356c66a`](https://github.com/inspect-js/object-inspect/commit/356c66a410e7aece7162c8319880a5ef647beaa9) +- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`c77b65b`](https://github.com/inspect-js/object-inspect/commit/c77b65bba593811b906b9ec57561c5cba92e2db3) +- [New] Add support for upcoming `BigInt` [`1ac548e`](https://github.com/inspect-js/object-inspect/commit/1ac548e4b27e26466c28c9a5e63e5d4e0591c31f) +- [Tests] run bigint tests in CI with --harmony-bigint flag [`d31b738`](https://github.com/inspect-js/object-inspect/commit/d31b73831880254b5c6cf5691cda9a149fbc5f04) +- [Dev Deps] update `core-js`, `tape` [`ff9eff6`](https://github.com/inspect-js/object-inspect/commit/ff9eff67113341ee1aaf80c1c22d683f43bfbccf) +- [Docs] fix example to use `safer-buffer` [`48cae12`](https://github.com/inspect-js/object-inspect/commit/48cae12a73ec6cacc955175bc56bbe6aee6a211f) + +## [v1.5.0](https://github.com/inspect-js/object-inspect/compare/v1.4.1...v1.5.0) - 2017-12-25 + +### Commits + +- [New] add `quoteStyle` option [`f5a72d2`](https://github.com/inspect-js/object-inspect/commit/f5a72d26edb3959b048f74c056ca7100a6b091e4) +- [Tests] add more test coverage [`30ebe4e`](https://github.com/inspect-js/object-inspect/commit/30ebe4e1fa943b99ecbb85be7614256d536e2759) +- [Tests] require 0.6 to pass [`99a008c`](https://github.com/inspect-js/object-inspect/commit/99a008ccace189a60fd7da18bf00e32c9572b980) + +## [v1.4.1](https://github.com/inspect-js/object-inspect/compare/v1.4.0...v1.4.1) - 2017-12-19 + +### Commits + +- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12` [`6674476`](https://github.com/inspect-js/object-inspect/commit/6674476cc56acaac1bde96c84fed5ef631911906) +- [Fix] `inspect(Object(-0))` should be “Object(-0)”, not “Object(0)” [`d0a031f`](https://github.com/inspect-js/object-inspect/commit/d0a031f1cbb3024ee9982bfe364dd18a7e4d1bd3) + +## [v1.4.0](https://github.com/inspect-js/object-inspect/compare/v1.3.0...v1.4.0) - 2017-10-24 + +### Commits + +- [Tests] add `npm run coverage` [`3b48fb2`](https://github.com/inspect-js/object-inspect/commit/3b48fb25db037235eeb808f0b2830aad7aa36f70) +- [Tests] remove commented-out osx builds [`71e24db`](https://github.com/inspect-js/object-inspect/commit/71e24db8ad6ee3b9b381c5300b0475f2ba595a73) +- [New] add support for `util.inspect.custom`, in node only. [`20cca77`](https://github.com/inspect-js/object-inspect/commit/20cca7762d7e17f15b21a90793dff84acce155df) +- [Tests] up to `node` `v8.6`; use `nvm install-latest-npm` to ensure new npm doesn’t break old node [`252952d`](https://github.com/inspect-js/object-inspect/commit/252952d230d8065851dd3d4d5fe8398aae068529) +- [Tests] up to `node` `v8.8` [`4aa868d`](https://github.com/inspect-js/object-inspect/commit/4aa868d3a62914091d489dd6ec6eed194ee67cd3) +- [Dev Deps] update `core-js`, `tape` [`59483d1`](https://github.com/inspect-js/object-inspect/commit/59483d1df418f852f51fa0db7b24aa6b0209a27a) + +## [v1.3.0](https://github.com/inspect-js/object-inspect/compare/v1.2.2...v1.3.0) - 2017-07-31 + +### Fixed + +- [Fix] Map/Set: work around core-js bug < v2.5.0 [`#9`](https://github.com/inspect-js/object-inspect/issues/9) + +### Commits + +- [New] add support for arrays with additional object keys [`0d19937`](https://github.com/inspect-js/object-inspect/commit/0d199374ee37959e51539616666f420ccb29acb9) +- [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`; fix new npm breaking on older nodes [`e24784a`](https://github.com/inspect-js/object-inspect/commit/e24784a90c49117787157a12a63897c49cf89bbb) +- Only apps should have lockfiles [`c6faebc`](https://github.com/inspect-js/object-inspect/commit/c6faebcb2ee486a889a4a1c4d78c0776c7576185) +- [Dev Deps] update `tape` [`7345a0a`](https://github.com/inspect-js/object-inspect/commit/7345a0aeba7e91b888a079c10004d17696a7f586) + +## [v1.2.2](https://github.com/inspect-js/object-inspect/compare/v1.2.1...v1.2.2) - 2017-03-24 + +### Commits + +- [Tests] up to `node` `v7.7`, `v6.10`, `v4.8`; improve test matrix [`a2ddc15`](https://github.com/inspect-js/object-inspect/commit/a2ddc15a1f2c65af18076eea1c0eb9cbceb478a0) +- [Tests] up to `node` `v7.0`, `v6.9`, `v5.12`, `v4.6`, `io.js` `v3.3`; improve test matrix [`a48949f`](https://github.com/inspect-js/object-inspect/commit/a48949f6b574b2d4d2298109d8e8d0eb3e7a83e7) +- [Performance] check for primitive types as early as possible. [`3b8092a`](https://github.com/inspect-js/object-inspect/commit/3b8092a2a4deffd0575f94334f00194e2d48dad3) +- [Refactor] remove unneeded `else`s. [`7255034`](https://github.com/inspect-js/object-inspect/commit/725503402e08de4f96f6bf2d8edef44ac36f26b6) +- [Refactor] avoid recreating `lowbyte` function every time. [`81edd34`](https://github.com/inspect-js/object-inspect/commit/81edd3475bd15bdd18e84de7472033dcf5004aaa) +- [Fix] differentiate -0 from 0 [`521d345`](https://github.com/inspect-js/object-inspect/commit/521d3456b009da7bf1c5785c8a9df5a9f8718264) +- [Refactor] move object key gathering into separate function [`aca6265`](https://github.com/inspect-js/object-inspect/commit/aca626536eaeef697196c6e9db3e90e7e0355b6a) +- [Refactor] consolidate wrapping logic for boxed primitives into a function. [`4e440cd`](https://github.com/inspect-js/object-inspect/commit/4e440cd9065df04802a2a1dead03f48c353ca301) +- [Robustness] use `typeof` instead of comparing to literal `undefined` [`5ca6f60`](https://github.com/inspect-js/object-inspect/commit/5ca6f601937506daff8ed2fcf686363b55807b69) +- [Refactor] consolidate Map/Set notations. [`4e576e5`](https://github.com/inspect-js/object-inspect/commit/4e576e5d7ed2f9ec3fb7f37a0d16732eb10758a9) +- [Tests] ensure that this function remains anonymous, despite ES6 name inference. [`7540ae5`](https://github.com/inspect-js/object-inspect/commit/7540ae591278756db614fa4def55ca413150e1a3) +- [Refactor] explicitly coerce Error objects to strings. [`7f4ca84`](https://github.com/inspect-js/object-inspect/commit/7f4ca8424ee8dc2c0ca5a422d94f7fac40327261) +- [Refactor] split up `var` declarations for debuggability [`6f2c11e`](https://github.com/inspect-js/object-inspect/commit/6f2c11e6a85418586a00292dcec5e97683f89bc3) +- [Robustness] cache `Object.prototype.toString` [`df44a20`](https://github.com/inspect-js/object-inspect/commit/df44a20adfccf31529d60d1df2079bfc3c836e27) +- [Dev Deps] update `tape` [`3ec714e`](https://github.com/inspect-js/object-inspect/commit/3ec714eba57bc3f58a6eb4fca1376f49e70d300a) +- [Dev Deps] update `tape` [`beb72d9`](https://github.com/inspect-js/object-inspect/commit/beb72d969653747d7cde300393c28755375329b0) + +## [v1.2.1](https://github.com/inspect-js/object-inspect/compare/v1.2.0...v1.2.1) - 2016-04-09 + +### Fixed + +- [Fix] fix Boolean `false` object inspection. [`#7`](https://github.com/substack/object-inspect/pull/7) + +## [v1.2.0](https://github.com/inspect-js/object-inspect/compare/v1.1.0...v1.2.0) - 2016-04-09 + +### Fixed + +- [New] add support for inspecting String/Number/Boolean objects. [`#6`](https://github.com/inspect-js/object-inspect/issues/6) + +### Commits + +- [Dev Deps] update `tape` [`742caa2`](https://github.com/inspect-js/object-inspect/commit/742caa262cf7af4c815d4821c8bd0129c1446432) + +## [v1.1.0](https://github.com/inspect-js/object-inspect/compare/1.0.2...v1.1.0) - 2015-12-14 + +### Merged + +- [New] add ES6 Map/Set support. [`#4`](https://github.com/inspect-js/object-inspect/pull/4) + +### Fixed + +- [New] add ES6 Map/Set support. [`#3`](https://github.com/inspect-js/object-inspect/issues/3) + +### Commits + +- Update `travis.yml` to test on bunches of `iojs` and `node` versions. [`4c1fd65`](https://github.com/inspect-js/object-inspect/commit/4c1fd65cc3bd95307e854d114b90478324287fd2) +- [Dev Deps] update `tape` [`88a907e`](https://github.com/inspect-js/object-inspect/commit/88a907e33afbe408e4b5d6e4e42a33143f88848c) + +## [1.0.2](https://github.com/inspect-js/object-inspect/compare/1.0.1...1.0.2) - 2015-08-07 + +### Commits + +- [Fix] Cache `Object.prototype.hasOwnProperty` in case it's deleted later. [`1d0075d`](https://github.com/inspect-js/object-inspect/commit/1d0075d3091dc82246feeb1f9871cb2b8ed227b3) +- [Dev Deps] Update `tape` [`ca8d5d7`](https://github.com/inspect-js/object-inspect/commit/ca8d5d75635ddbf76f944e628267581e04958457) +- gitignore node_modules since this is a reusable modules. [`ed41407`](https://github.com/inspect-js/object-inspect/commit/ed41407811743ca530cdeb28f982beb96026af82) + +## [1.0.1](https://github.com/inspect-js/object-inspect/compare/1.0.0...1.0.1) - 2015-07-19 + +### Commits + +- Make `inspect` work with symbol primitives and objects, including in node 0.11 and 0.12. [`ddf1b94`](https://github.com/inspect-js/object-inspect/commit/ddf1b94475ab951f1e3bccdc0a48e9073cfbfef4) +- bump tape [`103d674`](https://github.com/inspect-js/object-inspect/commit/103d67496b504bdcfdd765d303a773f87ec106e2) +- use newer travis config [`d497276`](https://github.com/inspect-js/object-inspect/commit/d497276c1da14234bb5098a59cf20de75fbc316a) + +## [1.0.0](https://github.com/inspect-js/object-inspect/compare/0.4.0...1.0.0) - 2014-08-05 + +### Commits + +- error inspect works properly [`260a22d`](https://github.com/inspect-js/object-inspect/commit/260a22d134d3a8a482c67d52091c6040c34f4299) +- seen coverage [`57269e8`](https://github.com/inspect-js/object-inspect/commit/57269e8baa992a7439047f47325111fdcbcb8417) +- htmlelement instance coverage [`397ffe1`](https://github.com/inspect-js/object-inspect/commit/397ffe10a1980350868043ef9de65686d438979f) +- more element coverage [`6905cc2`](https://github.com/inspect-js/object-inspect/commit/6905cc2f7df35600177e613b0642b4df5efd3eca) +- failing test for type errors [`385b615`](https://github.com/inspect-js/object-inspect/commit/385b6152e49b51b68449a662f410b084ed7c601a) +- fn name coverage [`edc906d`](https://github.com/inspect-js/object-inspect/commit/edc906d40fca6b9194d304062c037ee8e398c4c2) +- server-side element test [`362d1d3`](https://github.com/inspect-js/object-inspect/commit/362d1d3e86f187651c29feeb8478110afada385b) +- custom inspect fn [`e89b0f6`](https://github.com/inspect-js/object-inspect/commit/e89b0f6fe6d5e03681282af83732a509160435a6) +- fixed browser test [`b530882`](https://github.com/inspect-js/object-inspect/commit/b5308824a1c8471c5617e394766a03a6977102a9) +- depth test, matches node [`1cfd9e0`](https://github.com/inspect-js/object-inspect/commit/1cfd9e0285a4ae1dff44101ad482915d9bf47e48) +- exercise hasOwnProperty path [`8d753fb`](https://github.com/inspect-js/object-inspect/commit/8d753fb362a534fa1106e4d80f2ee9bea06a66d9) +- more cases covered for errors [`c5c46a5`](https://github.com/inspect-js/object-inspect/commit/c5c46a569ec4606583497e8550f0d8c7ad39a4a4) +- \W obj key test case [`b0eceee`](https://github.com/inspect-js/object-inspect/commit/b0eceeea6e0eb94d686c1046e99b9e25e5005f75) +- coverage for explicit depth param [`e12b91c`](https://github.com/inspect-js/object-inspect/commit/e12b91cd59683362f3a0e80f46481a0211e26c15) + +## [0.4.0](https://github.com/inspect-js/object-inspect/compare/0.3.1...0.4.0) - 2014-03-21 + +### Commits + +- passing lowbyte interpolation test [`b847511`](https://github.com/inspect-js/object-inspect/commit/b8475114f5def7e7961c5353d48d3d8d9a520985) +- lowbyte test [`4a2b0e1`](https://github.com/inspect-js/object-inspect/commit/4a2b0e142667fc933f195472759385ac08f3946c) + +## [0.3.1](https://github.com/inspect-js/object-inspect/compare/0.3.0...0.3.1) - 2014-03-04 + +### Commits + +- sort keys [`a07b19c`](https://github.com/inspect-js/object-inspect/commit/a07b19cc3b1521a82d4fafb6368b7a9775428a05) + +## [0.3.0](https://github.com/inspect-js/object-inspect/compare/0.2.0...0.3.0) - 2014-03-04 + +### Commits + +- [] and {} instead of [ ] and { } [`654c44b`](https://github.com/inspect-js/object-inspect/commit/654c44b2865811f3519e57bb8526e0821caf5c6b) + +## [0.2.0](https://github.com/inspect-js/object-inspect/compare/0.1.3...0.2.0) - 2014-03-04 + +### Commits + +- failing holes test [`99cdfad`](https://github.com/inspect-js/object-inspect/commit/99cdfad03c6474740275a75636fe6ca86c77737a) +- regex already work [`e324033`](https://github.com/inspect-js/object-inspect/commit/e324033267025995ec97d32ed0a65737c99477a6) +- failing undef/null test [`1f88a00`](https://github.com/inspect-js/object-inspect/commit/1f88a00265d3209719dda8117b7e6360b4c20943) +- holes in the all example [`7d345f3`](https://github.com/inspect-js/object-inspect/commit/7d345f3676dcbe980cff89a4f6c243269ebbb709) +- check for .inspect(), fixes Buffer use-case [`c3f7546`](https://github.com/inspect-js/object-inspect/commit/c3f75466dbca125347d49847c05262c292f12b79) +- fixes for holes [`ce25f73`](https://github.com/inspect-js/object-inspect/commit/ce25f736683de4b92ff27dc5471218415e2d78d8) +- weird null behavior [`405c1ea`](https://github.com/inspect-js/object-inspect/commit/405c1ea72cd5a8cf3b498c3eaa903d01b9fbcab5) +- tape is actually a devDependency, upgrade [`703b0ce`](https://github.com/inspect-js/object-inspect/commit/703b0ce6c5817b4245a082564bccd877e0bb6990) +- put date in the example [`a342219`](https://github.com/inspect-js/object-inspect/commit/a3422190eeaa013215f46df2d0d37b48595ac058) +- passing the null test [`4ab737e`](https://github.com/inspect-js/object-inspect/commit/4ab737ebf862a75d247ebe51e79307a34d6380d4) + +## [0.1.3](https://github.com/inspect-js/object-inspect/compare/0.1.1...0.1.3) - 2013-07-26 + +### Commits + +- special isElement() check [`882768a`](https://github.com/inspect-js/object-inspect/commit/882768a54035d30747be9de1baf14e5aa0daa128) +- oh right old IEs don't have indexOf either [`36d1275`](https://github.com/inspect-js/object-inspect/commit/36d12756c38b08a74370b0bb696c809e529913a5) + +## [0.1.1](https://github.com/inspect-js/object-inspect/compare/0.1.0...0.1.1) - 2013-07-26 + +### Commits + +- tests! [`4422fd9`](https://github.com/inspect-js/object-inspect/commit/4422fd95532c2745aa6c4f786f35f1090be29998) +- fix for ie<9, doesn't have hasOwnProperty [`6b7d611`](https://github.com/inspect-js/object-inspect/commit/6b7d61183050f6da801ea04473211da226482613) +- fix for all IEs: no f.name [`4e0c2f6`](https://github.com/inspect-js/object-inspect/commit/4e0c2f6dfd01c306d067d7163319acc97c94ee50) +- badges [`5ed0d88`](https://github.com/inspect-js/object-inspect/commit/5ed0d88e4e407f9cb327fa4a146c17921f9680f3) + +## [0.1.0](https://github.com/inspect-js/object-inspect/compare/0.0.0...0.1.0) - 2013-07-26 + +### Commits + +- [Function] for functions [`ad5c485`](https://github.com/inspect-js/object-inspect/commit/ad5c485098fc83352cb540a60b2548ca56820e0b) + +## 0.0.0 - 2013-07-26 + +### Commits + +- working browser example [`34be6b6`](https://github.com/inspect-js/object-inspect/commit/34be6b6548f9ce92bdc3c27572857ba0c4a1218d) +- package.json etc [`cad51f2`](https://github.com/inspect-js/object-inspect/commit/cad51f23fc6bcf1a456ed6abe16088256c2f632f) +- docs complete [`b80cce2`](https://github.com/inspect-js/object-inspect/commit/b80cce2490c4e7183a9ee11ea89071f0abec4446) +- circular example [`4b4a7b9`](https://github.com/inspect-js/object-inspect/commit/4b4a7b92209e4e6b4630976cb6bcd17d14165a59) +- string rep [`7afb479`](https://github.com/inspect-js/object-inspect/commit/7afb479baa798d27f09e0a178b72ea327f60f5c8) diff --git a/tools/ui/node_modules/object-inspect/LICENSE b/tools/ui/node_modules/object-inspect/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ca64cc1e605205438cc1b04b215f6fc12ab3f039 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 James Halliday + +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. diff --git a/tools/ui/node_modules/object-inspect/example/all.js b/tools/ui/node_modules/object-inspect/example/all.js new file mode 100644 index 0000000000000000000000000000000000000000..2f3355c509acd1a0e9d409f9e655939d6d18c2ec --- /dev/null +++ b/tools/ui/node_modules/object-inspect/example/all.js @@ -0,0 +1,23 @@ +'use strict'; + +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = ['a', 'b']; +holes[4] = 'e'; +holes[6] = 'g'; + +var obj = { + a: 1, + b: [3, 4, undefined, null], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date() +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/tools/ui/node_modules/object-inspect/example/circular.js b/tools/ui/node_modules/object-inspect/example/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..487a7c169d0df8c4acb6ad02b26ce76175ecfc0f --- /dev/null +++ b/tools/ui/node_modules/object-inspect/example/circular.js @@ -0,0 +1,6 @@ +'use strict'; + +var inspect = require('../'); +var obj = { a: 1, b: [3, 4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/tools/ui/node_modules/object-inspect/example/fn.js b/tools/ui/node_modules/object-inspect/example/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..9b5db8de036ffc6718969bee9193de36409235aa --- /dev/null +++ b/tools/ui/node_modules/object-inspect/example/fn.js @@ -0,0 +1,5 @@ +'use strict'; + +var inspect = require('../'); +var obj = [1, 2, function f(n) { return n + 5; }, 4]; +console.log(inspect(obj)); diff --git a/tools/ui/node_modules/object-inspect/example/inspect.js b/tools/ui/node_modules/object-inspect/example/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..e2df7c9f471356c48f14e7af2813119ffb6854bb --- /dev/null +++ b/tools/ui/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,10 @@ +'use strict'; + +/* eslint-env browser */ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }])); diff --git a/tools/ui/node_modules/object-inspect/index.js b/tools/ui/node_modules/object-inspect/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4b2d4cd850adb5cda64eb9e5692457a73c0947e --- /dev/null +++ b/tools/ui/node_modules/object-inspect/index.js @@ -0,0 +1,544 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +var quotes = { + __proto__: null, + 'double': '"', + single: "'" +}; +var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g +}; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof global !== 'undefined' && obj === global) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function canTrustToString(obj) { + return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); +} +function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } +function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } +function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } +function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} diff --git a/tools/ui/node_modules/object-inspect/package-support.json b/tools/ui/node_modules/object-inspect/package-support.json new file mode 100644 index 0000000000000000000000000000000000000000..5cc12d0585a386018d3c486be5a841d8377d15db --- /dev/null +++ b/tools/ui/node_modules/object-inspect/package-support.json @@ -0,0 +1,20 @@ +{ + "versions": [ + { + "version": "*", + "target": { + "node": "all" + }, + "response": { + "type": "time-permitting" + }, + "backing": { + "npm-funding": true, + "donations": [ + "https://github.com/ljharb", + "https://tidelift.com/funding/github/npm/object-inspect" + ] + } + } + ] +} diff --git a/tools/ui/node_modules/object-inspect/package.json b/tools/ui/node_modules/object-inspect/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9fd97ff7523f106de04c47adf74aa3a36db8dbbd --- /dev/null +++ b/tools/ui/node_modules/object-inspect/package.json @@ -0,0 +1,105 @@ +{ + "name": "object-inspect", + "version": "1.13.4", + "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, + "devDependencies": { + "@ljharb/eslint-config": "^21.1.1", + "@pkgjs/support": "^0.0.6", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "error-cause": "^1.0.8", + "es-value-fixtures": "^1.7.1", + "eslint": "=8.8.0", + "for-each": "^0.3.4", + "functions-have-names": "^1.2.3", + "glob": "=10.3.7", + "globalthis": "^1.0.4", + "has-symbols": "^1.1.0", + "has-tostringtag": "^1.0.2", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "make-arrow-function": "^1.2.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "semver": "^6.3.1", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.9.0" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "lint": "eslint --ext=js,mjs .", + "postlint": "npx @pkgjs/support validate", + "test": "npm run tests-only && npm run test:corejs", + "tests-only": "nyc tape 'test/*.js'", + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true, + "engines": { + "node": ">= 0.4" + } +} diff --git a/tools/ui/node_modules/object-inspect/readme.markdown b/tools/ui/node_modules/object-inspect/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..f91617df32a3c8b9ffa23300ad26ca918bca13aa --- /dev/null +++ b/tools/ui/node_modules/object-inspect/readme.markdown @@ -0,0 +1,84 @@ +# object-inspect [![Version Badge][npm-version-svg]][package-url] + +string representations of objects in node and the browser + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present. Default `'single'` for strings, `'double'` for HTML elements. + - `maxStringLength`: must be `0`, a positive integer, `Infinity`, or `null`, if present. Default `Infinity`. + - `customInspect`: When `true`, a custom inspect method function will be invoked (either undere the `util.inspect.custom` symbol, or the `inspect` property). When the string `'symbol'`, only the symbol method will be invoked. Default `true`. + - `indent`: must be "\t", `null`, or a positive integer. Default `null`. + - `numericSeparator`: must be a boolean, if present. Default `false`. If `true`, all numbers will be printed with numeric separators (eg, `1234.5678` will be printed as `'1_234.567_8'`) + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/object-inspect +[npm-version-svg]: https://versionbadg.es/inspect-js/object-inspect.svg +[deps-svg]: https://david-dm.org/inspect-js/object-inspect.svg +[deps-url]: https://david-dm.org/inspect-js/object-inspect +[dev-deps-svg]: https://david-dm.org/inspect-js/object-inspect/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/object-inspect#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object-inspect.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/object-inspect.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/object-inspect.svg +[downloads-url]: https://npm-stat.com/charts.html?package=object-inspect +[codecov-image]: https://codecov.io/gh/inspect-js/object-inspect/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/object-inspect/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/object-inspect +[actions-url]: https://github.com/inspect-js/object-inspect/actions diff --git a/tools/ui/node_modules/object-inspect/test-core-js.js b/tools/ui/node_modules/object-inspect/test-core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..e53c40022533f691fd17d623cd24a8ecb5a82669 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,26 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('WeakMaps', function (t) { + t.equal(inspect(new WeakMap([[{}, 2]])), 'WeakMap { ? }'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); + +test('WeakSets', function (t) { + t.equal(inspect(new WeakSet([[1, 2]])), 'WeakSet { ? }'); + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/bigint.js b/tools/ui/node_modules/object-inspect/test/bigint.js new file mode 100644 index 0000000000000000000000000000000000000000..4ecc31df8ab3fd311570d866b418514d159abfde --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,58 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + /* eslint-disable no-new-func */ + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'BigInt'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'BigInt\' }', + 'object lying about being a BigInt inspects as an object' + ); + }); + + t.test('numericSeparator', function (st) { + st.equal(inspect(BigInt(0), { numericSeparator: false }), '0n', '0n, numericSeparator false'); + st.equal(inspect(BigInt(0), { numericSeparator: true }), '0n', '0n, numericSeparator true'); + + st.equal(inspect(BigInt(1234), { numericSeparator: false }), '1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(1234), { numericSeparator: true }), '1_234n', '1234n, numericSeparator true'); + st.equal(inspect(BigInt(-1234), { numericSeparator: false }), '-1234n', '1234n, numericSeparator false'); + st.equal(inspect(BigInt(-1234), { numericSeparator: true }), '-1_234n', '1234n, numericSeparator true'); + + st.end(); + }); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/browser/dom.js b/tools/ui/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 0000000000000000000000000000000000000000..210c0b233e9f72c5733ef80fa38a3e8a315e5c29 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([d, { a: 3, b: 4, c: [5, 6, [7, [8, [9]]]] }]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/tools/ui/node_modules/object-inspect/test/circular.js b/tools/ui/node_modules/object-inspect/test/circular.js new file mode 100644 index 0000000000000000000000000000000000000000..5df4233cb202efc92a8e874ef74f0c69d6ac29d1 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/circular.js @@ -0,0 +1,16 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(2); + var obj = { a: 1, b: [3, 4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); + + var double = {}; + double.a = [double]; + double.b = {}; + double.b.inner = double.b; + double.b.obj = double; + t.equal(inspect(double), '{ a: [ [Circular] ], b: { inner: [Circular], obj: [Circular] } }'); +}); diff --git a/tools/ui/node_modules/object-inspect/test/deep.js b/tools/ui/node_modules/object-inspect/test/deep.js new file mode 100644 index 0000000000000000000000000000000000000000..99ce32a088f90f217c1e4b001f4e41d3ddd4f3ec --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/deep.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(4); + var obj = [[[[[[500]]]]]]; + t.equal(inspect(obj), '[ [ [ [ [ [Array] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 4 }), '[ [ [ [ [Array] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Array] ] ]'); + + t.equal(inspect([[[{ a: 1 }]]], { depth: 3 }), '[ [ [ [Object] ] ] ]'); +}); diff --git a/tools/ui/node_modules/object-inspect/test/element.js b/tools/ui/node_modules/object-inspect/test/element.js new file mode 100644 index 0000000000000000000000000000000000000000..47fa9e240029eb6fa2906727e20ec843fc3b6308 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [{ name: 'class', value: 'row' }], + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) { return key; }, + childNodes: [{ nodeName: 'b' }] + }; + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new global.HTMLElement('div', []); + var obj = [1, elem, 3]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/tools/ui/node_modules/object-inspect/test/err.js b/tools/ui/node_modules/object-inspect/test/err.js new file mode 100644 index 0000000000000000000000000000000000000000..cc1d884abdc52c8b5443b6212ab1d0d886ce9c33 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/err.js @@ -0,0 +1,48 @@ +var test = require('tape'); +var ErrorWithCause = require('error-cause/Error'); + +var inspect = require('../'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError(); + aerr.foo = 555; + aerr.bar = [1, 2, 3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError(); + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var withCause = new ErrorWithCause('foo', { cause: 'bar' }); + var withCausePlus = new ErrorWithCause('foo', { cause: 'bar' }); + withCausePlus.foo = 'bar'; + var withUndefinedCause = new ErrorWithCause('foo', { cause: undefined }); + var withEnumerableCause = new Error('foo'); + withEnumerableCause.cause = 'bar'; + + var obj = [ + new TypeError(), + new TypeError('xxx'), + aerr, + berr, + cerr, + withCause, + withCausePlus, + withUndefinedCause, + withEnumerableCause + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', + '{ [Error: foo] cause: \'bar\' }' + ].join(', ') + ' ]'); +}); diff --git a/tools/ui/node_modules/object-inspect/test/fakes.js b/tools/ui/node_modules/object-inspect/test/fakes.js new file mode 100644 index 0000000000000000000000000000000000000000..a65c08c15a6e4c9c5500cbbb7a2b01327a5a8c4b --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/fakes.js @@ -0,0 +1,29 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); + +test('fakes', { skip: !hasToStringTag }, function (t) { + forEach([ + 'Array', + 'Boolean', + 'Date', + 'Error', + 'Number', + 'RegExp', + 'String' + ], function (expected) { + var faker = {}; + faker[Symbol.toStringTag] = expected; + + t.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'' + expected + '\' }', + 'faker masquerading as ' + expected + ' is not shown as one' + ); + }); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/fn.js b/tools/ui/node_modules/object-inspect/test/fn.js new file mode 100644 index 0000000000000000000000000000000000000000..de3ca625e73adcabc8570a11318504d8d6aa6806 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/fn.js @@ -0,0 +1,76 @@ +var inspect = require('../'); +var test = require('tape'); +var arrow = require('make-arrow-function')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +test('function', function (t) { + t.plan(1); + var obj = [1, 2, function f(n) { return n; }, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function toStr() { return 'function xxx () {}'; }; + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)] { toString: [Function: toStr] }, 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [1, 2, f, 4]; + t.equal(inspect(obj), '[ 1, 2, [Function (anonymous)], 4 ]'); + + t.end(); +}); + +test('arrow function', { skip: !arrow }, function (t) { + t.equal(inspect(arrow), '[Function (anonymous)]'); + + t.end(); +}); + +test('truly nameless function', { skip: !arrow || !functionsHaveConfigurableNames }, function (t) { + function f() {} + Object.defineProperty(f, 'name', { value: false }); + t.equal(f.name, false); + t.equal( + inspect(f), + '[Function: f]', + 'named function with falsy `.name` does not hide its original name' + ); + + function g() {} + Object.defineProperty(g, 'name', { value: true }); + t.equal(g.name, true); + t.equal( + inspect(g), + '[Function: true]', + 'named function with truthy `.name` hides its original name' + ); + + var anon = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon, 'name', { value: null }); + t.equal(anon.name, null); + t.equal( + inspect(anon), + '[Function (anonymous)]', + 'anon function with falsy `.name` does not hide its anonymity' + ); + + var anon2 = function () {}; // eslint-disable-line func-style + Object.defineProperty(anon2, 'name', { value: 1 }); + t.equal(anon2.name, 1); + t.equal( + inspect(anon2), + '[Function: 1]', + 'anon function with truthy `.name` hides its anonymity' + ); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/global.js b/tools/ui/node_modules/object-inspect/test/global.js new file mode 100644 index 0000000000000000000000000000000000000000..c57216aebd518555d0ba6e6677238b6cf4aee59d --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/global.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); + +var test = require('tape'); +var globalThis = require('globalthis')(); + +test('global object', function (t) { + /* eslint-env browser */ + var expected = typeof window === 'undefined' ? 'globalThis' : 'Window'; + t.equal( + inspect([globalThis]), + '[ { [object ' + expected + '] } ]' + ); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/has.js b/tools/ui/node_modules/object-inspect/test/has.js new file mode 100644 index 0000000000000000000000000000000000000000..01800dee6b07894536485e9a23ca6cda472984a2 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/has.js @@ -0,0 +1,15 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays + + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect(arr), '[ 1, , 3 ]'); +}); diff --git a/tools/ui/node_modules/object-inspect/test/holes.js b/tools/ui/node_modules/object-inspect/test/holes.js new file mode 100644 index 0000000000000000000000000000000000000000..87fc8c84aedf765a2c908f451564e54ac27dcb85 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = ['a', 'b']; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/tools/ui/node_modules/object-inspect/test/indent-option.js b/tools/ui/node_modules/object-inspect/test/indent-option.js new file mode 100644 index 0000000000000000000000000000000000000000..89d8fcedfa318ca67c9ba8fe694ba06fd2b47044 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/indent-option.js @@ -0,0 +1,271 @@ +var test = require('tape'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('bad indent options', function (t) { + forEach([ + undefined, + true, + false, + -1, + 1.2, + Infinity, + -Infinity, + NaN + ], function (indent) { + t['throws']( + function () { inspect('', { indent: indent }); }, + TypeError, + inspect(indent) + ' is invalid' + ); + }); + + t.end(); +}); + +test('simple object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: 2 }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: 2', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('two deep object with indent', function (t) { + t.plan(2); + + var obj = { a: 1, b: { c: 3, d: 4 } }; + + var expectedSpaces = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + var expectedTabs = [ + '{', + ' a: 1,', + ' b: {', + ' c: 3,', + ' d: 4', + ' }', + '}' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('simple array with all single line elements', function (t) { + t.plan(2); + + var obj = [1, 2, 3, 'asdf\nsdf']; + + var expected = '[ 1, 2, 3, \'asdf\\nsdf\' ]'; + + t.equal(inspect(obj, { indent: 2 }), expected, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expected, 'tabs'); +}); + +test('array with complex elements', function (t) { + t.plan(2); + + var obj = [1, { a: 1, b: { c: 1 } }, 'asdf\nsdf']; + + var expectedSpaces = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' 1,', + ' {', + ' a: 1,', + ' b: {', + ' c: 1', + ' }', + ' },', + ' \'asdf\\nsdf\'', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('values', function (t) { + t.plan(2); + var obj = [{}, [], { 'a-b': 5 }]; + + var expectedSpaces = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + var expectedTabs = [ + '[', + ' {},', + ' [],', + ' {', + ' \'a-b\': 5', + ' }', + ']' + ].join('\n'); + + t.equal(inspect(obj, { indent: 2 }), expectedSpaces, 'two'); + t.equal(inspect(obj, { indent: '\t' }), expectedTabs, 'tabs'); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + + var expectedStringSpaces = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + '}' + ].join('\n'); + var expectedStringTabsDoubleQuotes = [ + 'Map (2) {', + ' { a: 1 } => [ "b" ],', + ' 3 => NaN', + '}' + ].join('\n'); + + t.equal( + inspect(map, { indent: 2 }), + expectedStringSpaces, + 'Map keys are not indented (two)' + ); + t.equal( + inspect(map, { indent: '\t' }), + expectedStringTabs, + 'Map keys are not indented (tabs)' + ); + t.equal( + inspect(map, { indent: '\t', quoteStyle: 'double' }), + expectedStringTabsDoubleQuotes, + 'Map keys are not indented (tabs + double quotes)' + ); + + t.equal(inspect(new Map(), { indent: 2 }), 'Map (0) {}', 'empty Map should show as empty (two)'); + t.equal(inspect(new Map(), { indent: '\t' }), 'Map (0) {}', 'empty Map should show as empty (tabs)'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + var expectedNestedSpaces = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Map (1) {', + ' [Circular] => Map (2) {', + ' { a: 1 } => [ \'b\' ],', + ' 3 => NaN', + ' }', + '}' + ].join('\n'); + t.equal(inspect(nestedMap, { indent: 2 }), expectedNestedSpaces, 'Map containing a Map should work (two)'); + t.equal(inspect(nestedMap, { indent: '\t' }), expectedNestedTabs, 'Map containing a Map should work (tabs)'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedStringSpaces = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + var expectedStringTabs = [ + 'Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + '}' + ].join('\n'); + t.equal(inspect(set, { indent: 2 }), expectedStringSpaces, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (two)'); + t.equal(inspect(set, { indent: '\t' }), expectedStringTabs, 'new Set([{ a: 1 }, ["b"]]) should show size and contents (tabs)'); + + t.equal(inspect(new Set(), { indent: 2 }), 'Set (0) {}', 'empty Set should show as empty (two)'); + t.equal(inspect(new Set(), { indent: '\t' }), 'Set (0) {}', 'empty Set should show as empty (tabs)'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + var expectedNestedSpaces = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + var expectedNestedTabs = [ + 'Set (2) {', + ' Set (2) {', + ' {', + ' a: 1', + ' },', + ' [ \'b\' ]', + ' },', + ' [Circular]', + '}' + ].join('\n'); + t.equal(inspect(nestedSet, { indent: 2 }), expectedNestedSpaces, 'Set containing a Set should work (two)'); + t.equal(inspect(nestedSet, { indent: '\t' }), expectedNestedTabs, 'Set containing a Set should work (tabs)'); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/inspect.js b/tools/ui/node_modules/object-inspect/test/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..1abf81b1f00b305519e52fe74477b2c5b71803c7 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,139 @@ +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var utilInspect = require('../util.inspect'); +var repeat = require('string.prototype.repeat'); + +var inspect = require('..'); + +test('inspect', function (t) { + t.plan(5); + + var obj = [{ inspect: function xyzInspect() { return '!XYZ¡'; } }, []]; + var stringResult = '[ !XYZ¡, [] ]'; + var falseResult = '[ { inspect: [Function: xyzInspect] }, [] ]'; + + t.equal(inspect(obj), stringResult); + t.equal(inspect(obj, { customInspect: true }), stringResult); + t.equal(inspect(obj, { customInspect: 'symbol' }), falseResult); + t.equal(inspect(obj, { customInspect: false }), falseResult); + t['throws']( + function () { inspect(obj, { customInspect: 'not a boolean or "symbol"' }); }, + TypeError, + '`customInspect` must be a boolean or the string "symbol"' + ); +}); + +test('inspect custom symbol', { skip: !hasSymbols || !utilInspect || !utilInspect.custom }, function (t) { + t.plan(4); + + var obj = { inspect: function stringInspect() { return 'string'; } }; + obj[utilInspect.custom] = function custom() { return 'symbol'; }; + + var symbolResult = '[ symbol, [] ]'; + var stringResult = '[ string, [] ]'; + var falseResult = '[ { inspect: [Function: stringInspect]' + (utilInspect.custom ? ', [' + inspect(utilInspect.custom) + ']: [Function: custom]' : '') + ' }, [] ]'; + + var symbolStringFallback = utilInspect.custom ? symbolResult : stringResult; + var symbolFalseFallback = utilInspect.custom ? symbolResult : falseResult; + + t.equal(inspect([obj, []]), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: true }), symbolStringFallback); + t.equal(inspect([obj, []], { customInspect: 'symbol' }), symbolFalseFallback); + t.equal(inspect([obj, []], { customInspect: false }), falseResult); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + t.plan(2); + + var obj = { a: 1 }; + obj[Symbol('test')] = 2; + obj[Symbol.iterator] = 3; + Object.defineProperty(obj, Symbol('non-enum'), { + enumerable: false, + value: 4 + }); + + if (typeof Symbol.iterator === 'symbol') { + t.equal(inspect(obj), '{ a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }', 'object with symbols'); + t.equal(inspect([obj, []]), '[ { a: 1, [Symbol(test)]: 2, [Symbol(Symbol.iterator)]: 3 }, [] ]', 'object with symbols in array'); + } else { + // symbol sham key ordering is unreliable + t.match( + inspect(obj), + /^(?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 })$/, + 'object with symbols (nondeterministic symbol sham key ordering)' + ); + t.match( + inspect([obj, []]), + /^\[ (?:{ a: 1, \[Symbol\(test\)\]: 2, \[Symbol\(Symbol.iterator\)\]: 3 }|{ a: 1, \[Symbol\(Symbol.iterator\)\]: 3, \[Symbol\(test\)\]: 2 }), \[\] \]$/, + 'object with symbols in array (nondeterministic symbol sham key ordering)' + ); + } +}); + +test('maxStringLength', function (t) { + t['throws']( + function () { inspect('', { maxStringLength: -1 }); }, + TypeError, + 'maxStringLength must be >= 0, or Infinity, not negative' + ); + + var str = repeat('a', 1e8); + + t.equal( + inspect([str], { maxStringLength: 10 }), + '[ \'aaaaaaaaaa\'... 99999990 more characters ]', + 'maxStringLength option limits output' + ); + + t.equal( + inspect(['f'], { maxStringLength: null }), + '[ \'\'... 1 more character ]', + 'maxStringLength option accepts `null`' + ); + + t.equal( + inspect([str], { maxStringLength: Infinity }), + '[ \'' + str + '\' ]', + 'maxStringLength option accepts ∞' + ); + + t.end(); +}); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/lowbyte.js b/tools/ui/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 0000000000000000000000000000000000000000..68a345d8578004506a45296d6de9e091b7811272 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\x05! \x1f \x12' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1F \\x12' }" + ); +}); diff --git a/tools/ui/node_modules/object-inspect/test/number.js b/tools/ui/node_modules/object-inspect/test/number.js new file mode 100644 index 0000000000000000000000000000000000000000..8f287e8e2ab93785108de2e82e5b359ffb524f02 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/number.js @@ -0,0 +1,58 @@ +var test = require('tape'); +var v = require('es-value-fixtures'); +var forEach = require('for-each'); + +var inspect = require('../'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); + +test('numericSeparator', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { inspect(true, { numericSeparator: nonBoolean }); }, + TypeError, + inspect(nonBoolean) + ' is not a boolean' + ); + }); + + t.test('3 digit numbers', function (st) { + var failed = false; + for (var i = -999; i < 1000; i += 1) { + var actual = inspect(i); + var actualSepNo = inspect(i, { numericSeparator: false }); + var actualSepYes = inspect(i, { numericSeparator: true }); + var expected = String(i); + if (actual !== expected || actualSepNo !== expected || actualSepYes !== expected) { + failed = true; + t.equal(actual, expected); + t.equal(actualSepNo, expected); + t.equal(actualSepYes, expected); + } + } + + st.notOk(failed, 'all 3 digit numbers passed'); + + st.end(); + }); + + t.equal(inspect(1e3), '1000', '1000'); + t.equal(inspect(1e3, { numericSeparator: false }), '1000', '1000, numericSeparator false'); + t.equal(inspect(1e3, { numericSeparator: true }), '1_000', '1000, numericSeparator true'); + t.equal(inspect(-1e3), '-1000', '-1000'); + t.equal(inspect(-1e3, { numericSeparator: false }), '-1000', '-1000, numericSeparator false'); + t.equal(inspect(-1e3, { numericSeparator: true }), '-1_000', '-1000, numericSeparator true'); + + t.equal(inspect(1234.5678, { numericSeparator: true }), '1_234.567_8', 'fractional numbers get separators'); + t.equal(inspect(1234.56789, { numericSeparator: true }), '1_234.567_89', 'fractional numbers get separators'); + t.equal(inspect(1234.567891, { numericSeparator: true }), '1_234.567_891', 'fractional numbers get separators'); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/quoteStyle.js b/tools/ui/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 0000000000000000000000000000000000000000..da23e630cfcf0b2bcd6d5e90becc09d714f46d7b --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,26 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.equal(inspect('"', { quoteStyle: 'single' }), '\'"\'', 'double quote, quoteStyle: "single"'); + t.equal(inspect('"', { quoteStyle: 'double' }), '"\\""', 'double quote, quoteStyle: "double"'); + + t.equal(inspect('\'', { quoteStyle: 'single' }), '\'\\\'\'', 'single quote, quoteStyle: "single"'); + t.equal(inspect('\'', { quoteStyle: 'double' }), '"\'"', 'single quote, quoteStyle: "double"'); + + t.equal(inspect('`', { quoteStyle: 'single' }), '\'`\'', 'backtick, quoteStyle: "single"'); + t.equal(inspect('`', { quoteStyle: 'double' }), '"`"', 'backtick, quoteStyle: "double"'); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/test/toStringTag.js b/tools/ui/node_modules/object-inspect/test/toStringTag.js new file mode 100644 index 0000000000000000000000000000000000000000..95f82703d08f358b00f180c7b479b9f33dff3dac --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/toStringTag.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); +var hasToStringTag = require('has-tostringtag/shams')(); + +var inspect = require('../'); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + t.plan(4); + + var obj = { a: 1 }; + t.equal(inspect(obj), '{ a: 1 }', 'object, no Symbol.toStringTag'); + + obj[Symbol.toStringTag] = 'foo'; + t.equal(inspect(obj), '{ a: 1, [Symbol(Symbol.toStringTag)]: \'foo\' }', 'object with Symbol.toStringTag'); + + t.test('null objects', { skip: 'toString' in { __proto__: null } }, function (st) { + st.plan(2); + + var dict = { __proto__: null, a: 1 }; + st.equal(inspect(dict), '[Object: null prototype] { a: 1 }', 'null object with Symbol.toStringTag'); + + dict[Symbol.toStringTag] = 'Dict'; + st.equal(inspect(dict), '[Dict: null prototype] { a: 1, [Symbol(Symbol.toStringTag)]: \'Dict\' }', 'null object with Symbol.toStringTag'); + }); + + t.test('instances', function (st) { + st.plan(4); + + function C() { + this.a = 1; + } + st.equal(Object.prototype.toString.call(new C()), '[object Object]', 'instance, no toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C { a: 1 }', 'instance, no toStringTag'); + + C.prototype[Symbol.toStringTag] = 'Class!'; + st.equal(Object.prototype.toString.call(new C()), '[object Class!]', 'instance, with toStringTag, Object.prototype.toString'); + st.equal(inspect(new C()), 'C [Class!] { a: 1 }', 'instance, with toStringTag'); + }); +}); diff --git a/tools/ui/node_modules/object-inspect/test/undef.js b/tools/ui/node_modules/object-inspect/test/undef.js new file mode 100644 index 0000000000000000000000000000000000000000..e3f4961229c249a1d4f242d415b5193fc0ad5056 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [3, 4, undefined, null], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/tools/ui/node_modules/object-inspect/test/values.js b/tools/ui/node_modules/object-inspect/test/values.js new file mode 100644 index 0000000000000000000000000000000000000000..15986cd0edbb8218fdd4fe8f414b4e27b5767b1e --- /dev/null +++ b/tools/ui/node_modules/object-inspect/test/values.js @@ -0,0 +1,261 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); +var mockProperty = require('mock-property'); +var hasSymbols = require('has-symbols/shams')(); +var hasToStringTag = require('has-tostringtag/shams')(); +var forEach = require('for-each'); +var semver = require('semver'); + +test('values', function (t) { + t.plan(1); + var obj = [{}, [], { 'a-b': 5 }]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [1, 2, 3, {}]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [1, 2, 3]; + + var seen = [5, xs]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + if (typeof sym === 'symbol') { + // Symbol shams are incapable of differentiating boxed from unboxed symbols + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + } + + t.test('toStringTag', { skip: !hasToStringTag }, function (st) { + st.plan(1); + + var faker = {}; + faker[Symbol.toStringTag] = 'Symbol'; + st.equal( + inspect(faker), + '{ [Symbol(Symbol.toStringTag)]: \'Symbol\' }', + 'object lying about being a Symbol inspects as an object' + ); + }); + + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('WeakMap', { skip: typeof WeakMap !== 'function' }, function (t) { + var map = new WeakMap(); + map.set({ a: 1 }, ['b']); + var expectedString = 'WeakMap { ? }'; + t.equal(inspect(map), expectedString, 'new WeakMap([[{ a: 1 }, ["b"]]]) should not show size or contents'); + t.equal(inspect(new WeakMap()), 'WeakMap { ? }', 'empty WeakMap should not show as empty'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('WeakSet', { skip: typeof WeakSet !== 'function' }, function (t) { + var map = new WeakSet(); + map.add({ a: 1 }); + var expectedString = 'WeakSet { ? }'; + t.equal(inspect(map), expectedString, 'new WeakSet([{ a: 1 }]) should not show size or contents'); + t.equal(inspect(new WeakSet()), 'WeakSet { ? }', 'empty WeakSet should not show as empty'); + + t.end(); +}); + +test('WeakRef', { skip: typeof WeakRef !== 'function' }, function (t) { + var ref = new WeakRef({ a: 1 }); + var expectedString = 'WeakRef { ? }'; + t.equal(inspect(ref), expectedString, 'new WeakRef({ a: 1 }) should not show contents'); + + t.end(); +}); + +test('FinalizationRegistry', { skip: typeof FinalizationRegistry !== 'function' }, function (t) { + var registry = new FinalizationRegistry(function () {}); + var expectedString = 'FinalizationRegistry [FinalizationRegistry] {}'; + t.equal(inspect(registry), expectedString, 'new FinalizationRegistry(function () {}) should work normallys'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); + +test('Date', function (t) { + var now = new Date(); + t.equal(inspect(now), String(now), 'Date shows properly'); + t.equal(inspect(new Date(NaN)), 'Invalid Date', 'Invalid Date shows properly'); + + t.end(); +}); + +test('RegExps', function (t) { + t.equal(inspect(/a/g), '/a/g', 'regex shows properly'); + t.equal(inspect(new RegExp('abc', 'i')), '/abc/i', 'new RegExp shows properly'); + + var match = 'abc abc'.match(/[ab]+/); + delete match.groups; // for node < 10 + t.equal(inspect(match), '[ \'ab\', index: 0, input: \'abc abc\' ]', 'RegExp match object shows properly'); + + t.end(); +}); + +test('Proxies', { skip: typeof Proxy !== 'function' || !hasToStringTag }, function (t) { + var target = { proxy: true }; + var fake = new Proxy(target, { has: function () { return false; } }); + + // needed to work around a weird difference in node v6.0 - v6.4 where non-present properties are not logged + var isNode60 = semver.satisfies(process.version, '6.0 - 6.4'); + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(fake), + '{ ' + (isNode60 ? '' : 'proxy: true, ') + '[Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Proxy for + ' + tag + ' shows as the target, which has no slots' + ); + }); + + t.end(); +}); + +test('fakers', { skip: !hasToStringTag }, function (t) { + var target = { proxy: false }; + + forEach([ + 'Boolean', + 'Number', + 'String', + 'Symbol', + 'Date' + ], function (tag) { + target[Symbol.toStringTag] = tag; + + t.equal( + inspect(target), + '{ proxy: false, [Symbol(Symbol.toStringTag)]: \'' + tag + '\' }', + 'Object pretending to be ' + tag + ' does not trick us' + ); + }); + + t.end(); +}); diff --git a/tools/ui/node_modules/object-inspect/util.inspect.js b/tools/ui/node_modules/object-inspect/util.inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..7784fab55d08875a01b24636f3a541c3d0bd39b2 --- /dev/null +++ b/tools/ui/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/tools/ui/node_modules/object-keys/.editorconfig b/tools/ui/node_modules/object-keys/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..eaa214161f5cdb409c32465fd822624c633a6bd8 --- /dev/null +++ b/tools/ui/node_modules/object-keys/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/tools/ui/node_modules/object-keys/.eslintrc b/tools/ui/node_modules/object-keys/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9a8d5b0e95e3615753a24220256ddc671ac2cedc --- /dev/null +++ b/tools/ui/node_modules/object-keys/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 23], + "id-length": [2, { "min": 1, "max": 40 }], + "max-params": [2, 3], + "max-statements": [2, 23], + "max-statements-per-line": [2, { "max": 2 }], + "no-extra-parens": [1], + "no-invalid-this": [1], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "LabeledStatement", "WithStatement"], + "operator-linebreak": [2, "after"] + } +} diff --git a/tools/ui/node_modules/object-keys/.travis.yml b/tools/ui/node_modules/object-keys/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..94a6ce42df6f7716665798fab033108ab07f97b1 --- /dev/null +++ b/tools/ui/node_modules/object-keys/.travis.yml @@ -0,0 +1,277 @@ +language: node_js +os: + - linux +node_js: + - "11.8" + - "10.15" + - "9.11" + - "8.15" + - "7.10" + - "6.16" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true + - env: POSTTEST=true diff --git a/tools/ui/node_modules/object-keys/CHANGELOG.md b/tools/ui/node_modules/object-keys/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b7d92df248e7c9c53413397b4e4dd50780f7cde8 --- /dev/null +++ b/tools/ui/node_modules/object-keys/CHANGELOG.md @@ -0,0 +1,232 @@ +1.1.1 / 2019-04-06 +================= + * [Fix] exclude deprecated Firefox keys (#53) + +1.1.0 / 2019-02-10 +================= + * [New] [Refactor] move full implementation to `implementation` entry point + * [Refactor] only evaluate the implementation if `Object.keys` is not present + * [Tests] up to `node` `v11.8`, `v10.15`, `v8.15`, `v6.16` + * [Tests] remove jscs + * [Tests] switch to `npm audit` from `nsp` + +1.0.12 / 2018-06-18 +================= + * [Fix] avoid accessing `window.applicationCache`, to avoid issues with latest Chrome on HTTP (#46) + +1.0.11 / 2016-07-05 +================= + * [Fix] exclude keys regarding the style (eg. `pageYOffset`) on `window` to avoid reflow (#32) + +1.0.10 / 2016-07-04 +================= + * [Fix] exclude `height` and `width` keys on `window` to avoid reflow (#31) + * [Fix] In IE 6, `window.external` makes `Object.keys` throw + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] use pretest/posttest for linting/security + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Dev Deps] remove unused eccheck script + dep + +1.0.9 / 2015-10-19 +================= + * [Fix] Blacklist 'frame' property on window (#16, #17) + * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` + +1.0.8 / 2015-10-14 +================= + * [Fix] wrap automation equality bug checking in try/catch, per [es5-shim#327](https://github.com/es-shims/es5-shim/issues/327) + * [Fix] Blacklist 'window.frameElement' per [es5-shim#322](https://github.com/es-shims/es5-shim/issues/322) + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + * [Dev Deps] update `eslint`, `tape`, `@ljharb/eslint-config`, `jscs` + +1.0.7 / 2015-07-18 +================= + * [Fix] A proper fix for 176f03335e90d5c8d0d8125a99f27819c9b9cdad / https://github.com/es-shims/es5-shim/issues/275 that doesn't break dontEnum/constructor fixes in IE 8. + * [Fix] Remove deprecation message in Chrome by touching deprecated window properties (#15) + * [Tests] Improve test output for automation equality bugfix + * [Tests] Test on `io.js` `v2.4` + +1.0.6 / 2015-07-09 +================= + * [Fix] Use an object lookup rather than ES5's `indexOf` (#14) + * [Tests] ES3 browsers don't have `Array.isArray` + * [Tests] Fix `no-shadow` rule, as well as an IE 8 bug caused by engine NFE shadowing bugs. + +1.0.5 / 2015-07-03 +================= + * [Fix] Fix a flabbergasting IE 8 bug where `localStorage.constructor.prototype === localStorage` throws + * [Tests] Test up to `io.js` `v2.3` + * [Dev Deps] Update `nsp`, `eslint` + +1.0.4 / 2015-05-23 +================= + * Fix a Safari 5.0 bug with `Object.keys` not working with `arguments` + * Test on latest `node` and `io.js` + * Update `jscs`, `tape`, `eslint`, `nsp`, `is`, `editorconfig-tools`, `covert` + +1.0.3 / 2015-01-06 +================= + * Revert "Make `object-keys` more robust against later environment tampering" to maintain ES3 compliance + +1.0.2 / 2014-12-28 +================= + * Update lots of dev dependencies + * Tweaks to README + * Make `object-keys` more robust against later environment tampering + +1.0.1 / 2014-09-03 +================= + * Update URLs and badges in README + +1.0.0 / 2014-08-26 +================= + * v1.0.0 + +0.6.1 / 2014-08-25 +================= + * v0.6.1 + * Updating dependencies (tape, covert, is) + * Update badges in readme + * Use separate var statements + +0.6.0 / 2014-04-23 +================= + * v0.6.0 + * Updating dependencies (tape, covert) + * Make sure boxed primitives, and arguments objects, work properly in ES3 browsers + * Improve test matrix: test all node versions, but only latest two stables are a failure + * Remove internal foreach shim. + +0.5.1 / 2014-03-09 +================= + * 0.5.1 + * Updating dependencies (tape, covert, is) + * Removing forEach from the module (but keeping it in tests) + +0.5.0 / 2014-01-30 +================= + * 0.5.0 + * Explicitly returning the shim, instead of returning native Object.keys when present + * Adding a changelog. + * Cleaning up IIFE wrapping + * Testing on node 0.4 through 0.11 + +0.4.0 / 2013-08-14 +================== + + * v0.4.0 + * In Chrome 4-10 and Safari 4, typeof (new RegExp) === 'function' + * If it's a string, make sure to use charAt instead of brackets. + * Only use Function#call if necessary. + * Making sure the context tests actually run. + * Better function detection + * Adding the android browser + * Fixing testling files + * Updating tape + * Removing the "is" dependency. + * Making an isArguments shim. + * Adding a local forEach shim and tests. + * Updating paths. + * Moving the shim test. + * v0.3.0 + +0.3.0 / 2013-05-18 +================== + + * README tweak. + * Fixing constructor enum issue. Fixes [#5](https://github.com/ljharb/object-keys/issues/5). + * Adding a test for [#5](https://github.com/ljharb/object-keys/issues/5) + * Updating readme. + * Updating dependencies. + * Giving credit to lodash. + * Make sure that a prototype's constructor property is not enumerable. Fixes [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding additional tests to handle arguments objects, and to skip "prototype" in functions. Fixes [#2](https://github.com/ljharb/object-keys/issues/2). + * Fixing a typo on this test for [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding node 0.10 to travis. + * Adding an IE < 9 test per [#3](https://github.com/ljharb/object-keys/issues/3) + * Adding an iOS 5 mobile Safari test per [#2](https://github.com/ljharb/object-keys/issues/2) + * Moving "indexof" and "is" to be dev dependencies. + * Making sure the shim works with functions. + * Flattening the tests. + +0.2.0 / 2013-05-10 +================== + + * v0.2.0 + * Object.keys should work with arrays. + +0.1.8 / 2013-05-10 +================== + + * v0.1.8 + * Upgrading dependencies. + * Using a simpler check. + * Fixing a bug in hasDontEnumBug browsers. + * Using the newest tape! + * Fixing this error test. + * "undefined" is probably a reserved word in ES3. + * Better test message. + +0.1.7 / 2013-04-17 +================== + + * Upgrading "is" once more. + * The key "null" is breaking some browsers. + +0.1.6 / 2013-04-17 +================== + + * v0.1.6 + * Upgrading "is" + +0.1.5 / 2013-04-14 +================== + + * Bumping version. + * Adding more testling browsers. + * Updating "is" + +0.1.4 / 2013-04-08 +================== + + * Using "is" instead of "is-extended". + +0.1.3 / 2013-04-07 +================== + + * Using "foreach" instead of my own shim. + * Removing "tap"; I'll just wait for "tape" to fix its node 0.10 bug. + +0.1.2 / 2013-04-03 +================== + + * Adding dependency status; moving links to an index at the bottom. + * Upgrading is-extended; version 0.1.2 + * Adding an npm version badge. + +0.1.1 / 2013-04-01 +================== + + * Adding Travis CI. + * Bumping the version. + * Adding indexOf since IE sucks. + * Adding a forEach shim since older browsers don't have Array#forEach. + * Upgrading tape - 0.3.2 uses Array#map + * Using explicit end instead of plan. + * Can't test with Array.isArray in older browsers. + * Using is-extended. + * Fixing testling files. + * JSHint/JSLint-ing. + * Removing an unused object. + * Using strict mode. + +0.1.0 / 2013-03-30 +================== + + * Changing the exports should have meant a higher version bump. + * Oops, fixing the repo URL. + * Adding more tests. + * 0.0.2 + * Merge branch 'export_one_thing'; closes [#1](https://github.com/ljharb/object-keys/issues/1) + * Move shim export to a separate file. diff --git a/tools/ui/node_modules/object-keys/LICENSE b/tools/ui/node_modules/object-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28553fdd06841b14fea43a5093bea3a5773fe1e0 --- /dev/null +++ b/tools/ui/node_modules/object-keys/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2013 Jordan Harband + +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. \ No newline at end of file diff --git a/tools/ui/node_modules/object-keys/README.md b/tools/ui/node_modules/object-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed4c277023a8a48522ec922f35ed27dda62a0ea8 --- /dev/null +++ b/tools/ui/node_modules/object-keys/README.md @@ -0,0 +1,76 @@ +#object-keys [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable. + +Most common usage: +```js +var keys = Object.keys || require('object-keys'); +``` + +## Example + +```js +var keys = require('object-keys'); +var assert = require('assert'); +var obj = { + a: true, + b: true, + c: true +}; + +assert.deepEqual(keys(obj), ['a', 'b', 'c']); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is not present */ +delete Object.keys; +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is present */ +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, Object.keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +## Source +Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url]. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/object-keys +[npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg +[travis-svg]: https://travis-ci.org/ljharb/object-keys.svg +[travis-url]: https://travis-ci.org/ljharb/object-keys +[deps-svg]: https://david-dm.org/ljharb/object-keys.svg +[deps-url]: https://david-dm.org/ljharb/object-keys +[dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/object-keys.png +[testling-url]: https://ci.testling.com/ljharb/object-keys +[es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589 +[lodash-url]: https://github.com/lodash/lodash +[npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object-keys.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object-keys.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object-keys + diff --git a/tools/ui/node_modules/object-keys/implementation.js b/tools/ui/node_modules/object-keys/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..5b329861954977f86c06e1efaf4d30a3f9629a0d --- /dev/null +++ b/tools/ui/node_modules/object-keys/implementation.js @@ -0,0 +1,122 @@ +'use strict'; + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; diff --git a/tools/ui/node_modules/object-keys/index.js b/tools/ui/node_modules/object-keys/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a43807d2f695c7b101bf95a24620227ab00947de --- /dev/null +++ b/tools/ui/node_modules/object-keys/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; diff --git a/tools/ui/node_modules/object-keys/isArguments.js b/tools/ui/node_modules/object-keys/isArguments.js new file mode 100644 index 0000000000000000000000000000000000000000..f2a2a9014d925e99b46c9f776525b02442fb6005 --- /dev/null +++ b/tools/ui/node_modules/object-keys/isArguments.js @@ -0,0 +1,17 @@ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; diff --git a/tools/ui/node_modules/object-keys/package.json b/tools/ui/node_modules/object-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..99ea923870ceb9e896828018d22a083dc4e70545 --- /dev/null +++ b/tools/ui/node_modules/object-keys/package.json @@ -0,0 +1,88 @@ +{ + "name": "object-keys", + "version": "1.1.1", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net" + }, + { + "name": "Ivan Starkov", + "email": "istarkov@gmail.com" + }, + { + "name": "Gary Katsevman", + "email": "git@gkatsev.com" + } + ], + "description": "An Object.keys replacement, in case Object.keys is not available. From https://github.com/es-shims/es5-shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "posttest": "npm run --silent audit", + "tests-only": "node test/index.js", + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "lint": "eslint .", + "preaudit": "npm install --package-lock --package-lock-only", + "audit": "npm audit", + "postaudit": "rm package-lock.json" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object-keys.git" + }, + "keywords": [ + "Object.keys", + "keys", + "ES5", + "shim" + ], + "dependencies": {}, + "devDependencies": { + "@ljharb/eslint-config": "^13.1.1", + "covert": "^1.1.1", + "eslint": "^5.13.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "tape": "^4.9.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/tools/ui/node_modules/object-keys/test/index.js b/tools/ui/node_modules/object-keys/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5402465a19b5b697128197df09d014c791542c51 --- /dev/null +++ b/tools/ui/node_modules/object-keys/test/index.js @@ -0,0 +1,5 @@ +'use strict'; + +require('./isArguments'); + +require('./shim'); diff --git a/tools/ui/node_modules/object.assign/.editorconfig b/tools/ui/node_modules/object.assign/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/tools/ui/node_modules/object.assign/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/tools/ui/node_modules/object.assign/.eslintrc b/tools/ui/node_modules/object.assign/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..131851698feacc552ca62b379186430f0257b2b0 --- /dev/null +++ b/tools/ui/node_modules/object.assign/.eslintrc @@ -0,0 +1,28 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": ["dist/"], + + "rules": { + "eqeqeq": [2, "allow-null"], + "id-length": [2, { "min": 1, "max": 30 }], + "max-statements": [2, 33], + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": [1, { "ignore": [0] }], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "no-invalid-this": 1, + "max-lines-per-function": 0, + "max-statements-per-line": [2, { "max": 3 }], + "no-magic-numbers": 0, + }, + }, + ], +} diff --git a/tools/ui/node_modules/object.assign/.github/FUNDING.yml b/tools/ui/node_modules/object.assign/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..ef7fdbfa08a090928219b6ae36796c5d73b4a952 --- /dev/null +++ b/tools/ui/node_modules/object.assign/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/object.assign +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tools/ui/node_modules/object.assign/.nycrc b/tools/ui/node_modules/object.assign/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/tools/ui/node_modules/object.assign/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tools/ui/node_modules/object.assign/CHANGELOG.md b/tools/ui/node_modules/object.assign/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..509f766dc90e71776ab3af19b422915f887b4c0f --- /dev/null +++ b/tools/ui/node_modules/object.assign/CHANGELOG.md @@ -0,0 +1,246 @@ +4.1.7 / 2024-12-18 +================== + * [Deps] add missing `es-object-atoms` (#86) + +4.1.6 / 2024-12-18 +================== + * [Refactor] use `call-bound` directly; use `es-object-atoms` + * [Deps] update `call-bind`, `has-symbols` + * [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `hasown`, `mock-property`, `ses`, `tape` + * [actions] split out node 10-20, and 20+ + * [actions] remove redundant finisher + * [Tests] replace `aud` with `npm audit` + +4.1.5 / 2023-11-30 +================== + * [meta] republish without testing HTML file (#85) + * [Deps] update `call-bind`, `define-properties` + * [Dev Deps] use `hasown` instead of `has` + * [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `npmignore`, `mock-property`, `tape` + * [actions] update rebase action + +4.1.4 / 2022-08-16 +================== + * [meta] fix `npmignore` integration (#83) + +4.1.3 / 2022-08-05 +================== + * [Refactor] make steps closer to actual spec + * [Refactor] simplify object coercible check + * [readme] remove defunct badges, add coverage and actions badges + * [eslint] ignore coverage output + * [meta] use `npmignore` to autogenerate an npmignore file + * [meta] remove audit-level + * [Deps] update `call-bind`, `define-properties`, `has-symbols` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `functions-have-names`, `safe-publish-latest`, `ses`, `tape` + * [actions] use `node/install` instead of `node/run`; use `codecov` action + * [actions] reuse common workflows + * [actions] update codecov uploader + * [Tests] add implementation tests + * [Tests] use `mock-property` + * [Tests] disable posttest pending `aud` handling `file:` deps + * [Tests] migrate remaining tests to Github Actions (#81) + * [Tests] gitignore coverage output + * [Tests] test node v1-v9 on Github Actions instead of travis; resume testing all minors (#80) + +4.1.2 / 2020-10-30 +================== + * [Refactor] use extracted `call-bind` instead of full `es-abstract` + * [Dev Deps] update `eslint`, `ses`, `browserify` + * [Tests] run tests in SES + * [Tests] ses-compat: show error stacks + +4.1.1 / 2020-09-11 +================== + * [Fix] avoid mutating `Object.assign` in modern engines + * [Refactor] use `callBind` from `es-abstract` instead of `function-bind` + * [Deps] update `has-symbols`, `object-keys`, `define-properties` + * [meta] add `funding` field, FUNDING.yml + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `browserify`, `covert`, `for-each`, `is`, `tape`, `functions-have-names`; add `aud`, `safe-publish-latest`; remove `jscs` + * [actions] add Require Allow Edits workflow + * [actions] add automatic rebasing / merge commit blocking + * [Tests] ses-compat - add test to ensure package initializes correctly after ses lockdown (#77) + * [Tests] Add passing test for a source of `window.location` (#68) + * [Tests] use shared travis-ci config + * [Tests] use `npx aud` instead of `npm audit` with hoops or `nsp` + * [Tests] use `functions-have-names` + +4.1.0 / 2017-12-21 +================== + * [New] add `auto` entry point (#52) + * [Refactor] Use `has-symbols` module + * [Deps] update `function-bind`, `object-keys` + * [Dev Deps] update `@es-shims/api`, `browserify`, `nsp`, `eslint`, `@ljharb/eslint-config`, `is` + * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS + +4.0.4 / 2016-07-04 +================== + * [Fix] Cache original `getOwnPropertySymbols`, and use that when `Object.getOwnPropertySymbols` is unavailable + * [Deps] update `object-keys` + * [Dev Deps] update `eslint`, `get-own-property-symbols`, `core-js`, `jscs`, `nsp`, `browserify`, `@ljharb/eslint-config`, `tape`, `@es-shims/api` + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] run sham tests on node 0.10 + * [Tests] use pretest/posttest for linting/security + +4.0.3 / 2015-10-21 +================== + * [Fix] Support core-js's Symbol sham (#17) + * [Fix] Ensure that properties removed or made non-enumerable during enumeration are not assigned (#16) + * [Fix] Avoid looking up keys and values more than once + * [Tests] Avoid using `reduce` so `npm run test:shams:corejs` passes in `node` `v0.8` ([core-js#122](https://github.com/zloirock/core-js/issues/122)) + * [Tests] Refactor to use my conventional structure that separates shimmed, implementation, and common tests + * [Tests] Create `npm run test:shams` and better organize tests for symbol shams + * [Tests] Remove `nsp` in favor of `requiresafe` + +4.0.2 / 2015-10-20 +================== + * [Fix] Ensure correct property enumeration order, particularly in v8 (#15) + * [Deps] update `object-keys`, `define-properties` + * [Dev Deps] update `browserify`, `is`, `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + +4.0.1 / 2015-08-16 +================== + * [Docs] Add `Symbol` note to readme + +4.0.0 / 2015-08-15 +================== + * [Breaking] Implement the [es-shim API](es-shims/api). + * [Robustness] Make implementation robust against later modification of environment methods. + * [Refactor] Move implementation to `implementation.js` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Deps] update `object-keys`, `define-properties` + * [Dev Deps] update `browserify`, `tape`, `eslint`, `jscs`, `browserify` + * [Tests] Add `npm run tests-only` + * [Tests] use my personal shared `eslint` config. + * [Tests] up to `io.js` `v3.0` + +3.0.1 / 2015-06-28 +================== + * Cache `Object` and `Array#push` to make the shim more robust. + * [Fix] Remove use of `Array#filter`, which isn't in ES3. + * [Deps] Update `object-keys`, `define-properties` + * [Dev Deps] Update `get-own-property-symbols`, `browserify`, `eslint`, `nsp` + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Adding `Object.assign` tests for non-object targets, per https://github.com/paulmillr/es6-shim/issues/348 + +3.0.0 / 2015-05-20 +================== + * Attempt to feature-detect Symbols, even if `typeof Symbol() !== 'symbol'` (#12) + * Make a separate `hasSymbols` internal module + * Update `browserify`, `eslint` + +2.0.3 / 2015-06-28 +================== + * Cache `Object` and `Array#push` to make the shim more robust. + * [Fix] Remove use of `Array#filter`, which isn't in ES3 + * [Deps] Update `object-keys`, `define-properties` + * [Dev Deps] Update `browserify`, `nsp`, `eslint` + * [Tests] Test up to `io.js` `v2.3` + +2.0.2 / 2015-05-20 +================== + * Make sure `.shim` is non-enumerable. + * Refactor `.shim` implementation to use `define-properties` predicates, rather than `delete`ing the original. + * Update docs to match spec/implementation. (#11) + * Add `npm run eslint` + * Test up to `io.js` `v2.0` + * Update `jscs`, `browserify`, `covert` + +2.0.1 / 2015-04-12 +================== + * Make sure non-enumerable Symbols are excluded. + +2.0.0 / 2015-04-12 +================== + * Make sure the shim function overwrites a broken implementation with pending exceptions. + * Ensure shim is not enumerable using `define-properties` + * Ensure `Object.assign` includes symbols. + * All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. + * Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. + * Add `npm run security` via `nsp` + * Update `browserify`, `jscs`, `tape`, `object-keys`, `is` + +1.1.1 / 2014-12-14 +================== + * Actually include the browser build in `npm` + +1.1.0 / 2014-12-14 +================== + * Add `npm run build`, and build an automatic-shimming browser distribution as part of the npm publish process. + * Update `is`, `jscs` + +1.0.3 / 2014-11-29 +================== + * Revert "optimize --production installs" + +1.0.2 / 2014-11-27 +================== + * Update `jscs`, `is`, `object-keys`, `tape` + * Add badges to README + * Name URLs in README + * Lock `covert` to `v1.0.0` + * Optimize --production installs + +1.0.1 / 2014-08-26 +================== + * Update `is`, `covert` + +1.0.0 / 2014-08-07 +================== + * Update `object-keys`, `tape` + +0.5.0 / 2014-07-31 +================== + * Object.assign no longer throws on null or undefined sources, per https://bugs.ecmascript.org/show_bug.cgi?id=3096 + +0.4.3 / 2014-07-30 +================== + * Don’t modify vars in the function signature, since it deoptimizes v8 + +0.4.2 / 2014-07-30 +================== + * Fixing the version number: v0.4.2 + +0.4.1 / 2014-07-19 +================== + * Revert "Use the native Object.keys if it’s available." + +0.4.0 / 2014-07-19 +================== + * Use the native Object.keys if it’s available. + * Fixes [#2](https://github.com/ljharb/object.assign/issues/2). + * Adding failing tests for [#2](https://github.com/ljharb/object.assign/issues/2). + * Fix indentation. + * Adding `npm run lint` + * Update `tape`, `covert` + * README: Use SVG badge for Travis [#1](https://github.com/ljharb/object.assign/issues/1) from mathiasbynens/patch-1 + +0.3.1 / 2014-04-10 +================== + * Object.assign does partially modify objects if it throws, per https://twitter.com/awbjs/status/454320863093862400 + +0.3.0 / 2014-04-10 +================== + * Update with newest ES6 behavior - Object.assign now takes a variable number of source objects. + * Update `tape` + * Make sure old and unstable nodes don’t fail Travis + +0.2.1 / 2014-03-16 +================== + * Let object-keys handle the fallback + * Update dependency badges + * Adding bower.json + +0.2.0 / 2014-03-16 +================== + * Use a for loop, because ES3 browsers don’t have "reduce" + +0.1.1 / 2014-03-14 +================== + * Updating readme + +0.1.0 / 2014-03-14 +================== + * Initial release. + diff --git a/tools/ui/node_modules/object.assign/LICENSE b/tools/ui/node_modules/object.assign/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ab29cbd63b72d5d30b0cc92162db190f2e4b9a36 --- /dev/null +++ b/tools/ui/node_modules/object.assign/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +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. \ No newline at end of file diff --git a/tools/ui/node_modules/object.assign/README.md b/tools/ui/node_modules/object.assign/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8e933fee6260157922ea8ebd8f46795e030d6df4 --- /dev/null +++ b/tools/ui/node_modules/object.assign/README.md @@ -0,0 +1,136 @@ +# object.assign [![Version Badge][npm-version-svg]][npm-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][npm-url] + +An Object.assign shim. Invoke its "shim" method to shim Object.assign if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Takes a minimum of 2 arguments: `target` and `source`. +Takes a variable sized list of source arguments - at least 1, as many as you want. +Throws a TypeError if the `target` argument is `null` or `undefined`. + +Most common usage: +```js +var assign = require('object.assign').getPolyfill(); // returns native method if compliant + /* or */ +var assign = require('object.assign/polyfill')(); // returns native method if compliant +``` + +## Example + +```js +var assert = require('assert'); + +// Multiple sources! +var target = { a: true }; +var source1 = { b: true }; +var source2 = { c: true }; +var sourceN = { n: true }; + +var expected = { + a: true, + b: true, + c: true, + n: true +}; + +assign(target, source1, source2, sourceN); +assert.deepEqual(target, expected); // AWESOME! +``` + +```js +var target = { + a: true, + b: true, + c: true +}; +var source1 = { + c: false, + d: false +}; +var sourceN = { + e: false +}; + +var assigned = assign(target, source1, sourceN); +assert.equal(target, assigned); // returns the target object +assert.deepEqual(assigned, { + a: true, + b: true, + c: false, + d: false, + e: false +}); +``` + +```js +/* when Object.assign is not present */ +delete Object.assign; +var shimmedAssign = require('object.assign').shim(); + /* or */ +var shimmedAssign = require('object.assign/shim')(); + +assert.equal(shimmedAssign, assign); + +var target = { + a: true, + b: true, + c: true +}; +var source = { + c: false, + d: false, + e: false +}; + +var assigned = assign(target, source); +assert.deepEqual(Object.assign(target, source), assign(target, source)); +``` + +```js +/* when Object.assign is present */ +var shimmedAssign = require('object.assign').shim(); +assert.equal(shimmedAssign, Object.assign); + +var target = { + a: true, + b: true, + c: true +}; +var source = { + c: false, + d: false, + e: false +}; + +assert.deepEqual(Object.assign(target, source), assign(target, source)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[npm-url]: https://npmjs.org/package/object.assign +[npm-version-svg]: http://versionbadg.es/ljharb/object.assign.svg +[travis-svg]: https://travis-ci.org/ljharb/object.assign.svg +[travis-url]: https://travis-ci.org/ljharb/object.assign +[deps-svg]: https://david-dm.org/ljharb/object.assign.svg?theme=shields.io +[deps-url]: https://david-dm.org/ljharb/object.assign +[dev-deps-svg]: https://david-dm.org/ljharb/object.assign/dev-status.svg?theme=shields.io +[dev-deps-url]: https://david-dm.org/ljharb/object.assign#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/object.assign.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object.assign.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object.assign.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object.assign +[codecov-image]: https://codecov.io/gh/ljharb/object.assign/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/object.assign/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/object.assign +[actions-url]: https://github.com/ljharb/object.assign/actions diff --git a/tools/ui/node_modules/object.assign/auto.js b/tools/ui/node_modules/object.assign/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/tools/ui/node_modules/object.assign/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/tools/ui/node_modules/object.assign/dist/browser.js b/tools/ui/node_modules/object.assign/dist/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..a644f9bc91dd9f247921e199e1e9ff39f9700197 --- /dev/null +++ b/tools/ui/node_modules/object.assign/dist/browser.js @@ -0,0 +1,1304 @@ +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0 ? adjustedLength : 0), + true + ); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + +},{"call-bind-apply-helpers":8,"call-bind-apply-helpers/applyBind":5,"es-define-property":15,"set-function-length":41}],11:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBindBasic = require('call-bind-apply-helpers'); + +/** @type {(thisArg: string, searchString: string, position?: number) => number} */ +var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + +/** @type {import('.')} */ +module.exports = function callBoundIntrinsic(name, allowMissing) { + // eslint-disable-next-line no-extra-parens + var intrinsic = /** @type {Parameters[0][0]} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic([intrinsic]); + } + return intrinsic; +}; + +},{"call-bind-apply-helpers":8,"get-intrinsic":26}],12:[function(require,module,exports){ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); + +var gopd = require('gopd'); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + +},{"es-define-property":15,"es-errors/syntax":20,"es-errors/type":21,"gopd":28}],13:[function(require,module,exports){ +'use strict'; + +var keys = require('object-keys'); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +var toStr = Object.prototype.toString; +var concat = Array.prototype.concat; +var defineDataProperty = require('define-data-property'); + +var isFunction = function (fn) { + return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; +}; + +var supportsDescriptors = require('has-property-descriptors')(); + +var defineProperty = function (object, name, value, predicate) { + if (name in object) { + if (predicate === true) { + if (object[name] === value) { + return; + } + } else if (!isFunction(predicate) || !predicate()) { + return; + } + } + + if (supportsDescriptors) { + defineDataProperty(object, name, value, true); + } else { + defineDataProperty(object, name, value); + } +}; + +var defineProperties = function (object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } +}; + +defineProperties.supportsDescriptors = !!supportsDescriptors; + +module.exports = defineProperties; + +},{"define-data-property":12,"has-property-descriptors":29,"object-keys":39}],14:[function(require,module,exports){ +'use strict'; + +var callBind = require('call-bind-apply-helpers'); +var gOPD = require('gopd'); + +var hasProtoAccessor; +try { + // eslint-disable-next-line no-extra-parens, no-proto + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; +} catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } +} + +// eslint-disable-next-line no-extra-parens +var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + +var $Object = Object; +var $getPrototypeOf = $Object.getPrototypeOf; + +/** @type {import('./get')} */ +module.exports = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; + +},{"call-bind-apply-helpers":8,"gopd":28}],15:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +var $defineProperty = Object.defineProperty || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + +},{}],16:[function(require,module,exports){ +'use strict'; + +/** @type {import('./eval')} */ +module.exports = EvalError; + +},{}],17:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +module.exports = Error; + +},{}],18:[function(require,module,exports){ +'use strict'; + +/** @type {import('./range')} */ +module.exports = RangeError; + +},{}],19:[function(require,module,exports){ +'use strict'; + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + +},{}],20:[function(require,module,exports){ +'use strict'; + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + +},{}],21:[function(require,module,exports){ +'use strict'; + +/** @type {import('./type')} */ +module.exports = TypeError; + +},{}],22:[function(require,module,exports){ +'use strict'; + +/** @type {import('./uri')} */ +module.exports = URIError; + +},{}],23:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +module.exports = Object; + +},{}],24:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],25:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":24}],26:[function(require,module,exports){ +'use strict'; + +var undefined; + +var $Object = require('es-object-atoms'); + +var $Error = require('es-errors'); +var $EvalError = require('es-errors/eval'); +var $RangeError = require('es-errors/range'); +var $ReferenceError = require('es-errors/ref'); +var $SyntaxError = require('es-errors/syntax'); +var $TypeError = require('es-errors/type'); +var $URIError = require('es-errors/uri'); + +var abs = require('math-intrinsics/abs'); +var floor = require('math-intrinsics/floor'); +var max = require('math-intrinsics/max'); +var min = require('math-intrinsics/min'); +var pow = require('math-intrinsics/pow'); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = require('gopd'); +var $defineProperty = require('es-define-property'); + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); +var getDunderProto = require('dunder-proto/get'); + +var getProto = (typeof Reflect === 'function' && Reflect.getPrototypeOf) + || $Object.getPrototypeOf + || getDunderProto; + +var $apply = require('call-bind-apply-helpers/functionApply'); +var $call = require('call-bind-apply-helpers/functionCall'); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('hasown'); +var $concat = bind.call($call, Array.prototype.concat); +var $spliceApply = bind.call($apply, Array.prototype.splice); +var $replace = bind.call($call, String.prototype.replace); +var $strSlice = bind.call($call, String.prototype.slice); +var $exec = bind.call($call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +},{"call-bind-apply-helpers/functionApply":6,"call-bind-apply-helpers/functionCall":7,"dunder-proto/get":14,"es-define-property":15,"es-errors":17,"es-errors/eval":16,"es-errors/range":18,"es-errors/ref":19,"es-errors/syntax":20,"es-errors/type":21,"es-errors/uri":22,"es-object-atoms":23,"function-bind":25,"gopd":28,"has-symbols":30,"hasown":32,"math-intrinsics/abs":33,"math-intrinsics/floor":34,"math-intrinsics/max":35,"math-intrinsics/min":36,"math-intrinsics/pow":37}],27:[function(require,module,exports){ +'use strict'; + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; + +},{}],28:[function(require,module,exports){ +'use strict'; + +/** @type {import('.')} */ +var $gOPD = require('./gOPD'); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + +},{"./gOPD":27}],29:[function(require,module,exports){ +'use strict'; + +var $defineProperty = require('es-define-property'); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + +},{"es-define-property":15}],30:[function(require,module,exports){ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +},{"./shams":31}],31:[function(require,module,exports){ +'use strict'; + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],32:[function(require,module,exports){ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + +},{"function-bind":25}],33:[function(require,module,exports){ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.abs; + +},{}],34:[function(require,module,exports){ +'use strict'; + +/** @type {import('./abs')} */ +module.exports = Math.floor; + +},{}],35:[function(require,module,exports){ +'use strict'; + +/** @type {import('./max')} */ +module.exports = Math.max; + +},{}],36:[function(require,module,exports){ +'use strict'; + +/** @type {import('./min')} */ +module.exports = Math.min; + +},{}],37:[function(require,module,exports){ +'use strict'; + +/** @type {import('./pow')} */ +module.exports = Math.pow; + +},{}],38:[function(require,module,exports){ +'use strict'; + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; + +},{"./isArguments":40}],39:[function(require,module,exports){ +'use strict'; + +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; + +},{"./implementation":38,"./isArguments":40}],40:[function(require,module,exports){ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; + +},{}],41:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = require('es-errors/type'); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; + +},{"define-data-property":12,"es-errors/type":21,"get-intrinsic":26,"gopd":28,"has-property-descriptors":29}],42:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; + +},{"./implementation":2}],43:[function(require,module,exports){ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimAssign() { + var polyfill = getPolyfill(); + define( + Object, + { assign: polyfill }, + { assign: function () { return Object.assign !== polyfill; } } + ); + return polyfill; +}; + +},{"./polyfill":42,"define-properties":13}]},{},[1]); diff --git a/tools/ui/node_modules/object.assign/hasSymbols.js b/tools/ui/node_modules/object.assign/hasSymbols.js new file mode 100644 index 0000000000000000000000000000000000000000..34841e01199eb2cc5e607665b22679da2eeb6a43 --- /dev/null +++ b/tools/ui/node_modules/object.assign/hasSymbols.js @@ -0,0 +1,43 @@ +'use strict'; + +var keys = require('object-keys'); + +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + /* + * temp disabled per https://github.com/ljharb/object.assign/issues/17 + * if (sym instanceof Symbol) { return false; } + * temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + * if (!(symObj instanceof Symbol)) { return false; } + */ + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-unreachable-loop + if (keys(obj).length !== 0) { return false; } + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/tools/ui/node_modules/object.assign/implementation.js b/tools/ui/node_modules/object.assign/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..4f4b4256f57ecb9478548853ad4cb61ec98cbbe8 --- /dev/null +++ b/tools/ui/node_modules/object.assign/implementation.js @@ -0,0 +1,46 @@ +'use strict'; + +// modified from https://github.com/es-shims/es6-shim +var objectKeys = require('object-keys'); +var hasSymbols = require('has-symbols/shams')(); +var callBound = require('call-bound'); +var $Object = require('es-object-atoms'); +var $push = callBound('Array.prototype.push'); +var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var originalGetSymbols = hasSymbols ? $Object.getOwnPropertySymbols : null; + +// eslint-disable-next-line no-unused-vars +module.exports = function assign(target, source1) { + if (target == null) { throw new TypeError('target must be an object'); } + var to = $Object(target); // step 1 + if (arguments.length === 1) { + return to; // step 2 + } + for (var s = 1; s < arguments.length; ++s) { + var from = $Object(arguments[s]); // step 3.a.i + + // step 3.a.ii: + var keys = objectKeys(from); + var getSymbols = hasSymbols && ($Object.getOwnPropertySymbols || originalGetSymbols); + if (getSymbols) { + var syms = getSymbols(from); + for (var j = 0; j < syms.length; ++j) { + var key = syms[j]; + if ($propIsEnumerable(from, key)) { + $push(keys, key); + } + } + } + + // step 3.a.iii: + for (var i = 0; i < keys.length; ++i) { + var nextKey = keys[i]; + if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 + var propValue = from[nextKey]; // step 3.a.iii.2.a + to[nextKey] = propValue; // step 3.a.iii.2.b + } + } + } + + return to; // step 4 +}; diff --git a/tools/ui/node_modules/object.assign/index.js b/tools/ui/node_modules/object.assign/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b50603769174865159dd05b178f9f18d890d63a --- /dev/null +++ b/tools/ui/node_modules/object.assign/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var polyfill = callBind.apply(getPolyfill()); +// eslint-disable-next-line no-unused-vars +var bound = function assign(target, source1) { + return polyfill(Object, arguments); +}; + +defineProperties(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/tools/ui/node_modules/object.assign/package.json b/tools/ui/node_modules/object.assign/package.json new file mode 100644 index 0000000000000000000000000000000000000000..996fee0cd4b5ab41d7c1da5812adacdaadecb8e4 --- /dev/null +++ b/tools/ui/node_modules/object.assign/package.json @@ -0,0 +1,96 @@ +{ + "name": "object.assign", + "version": "4.1.7", + "author": "Jordan Harband", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES6 spec-compliant Object.assign shim. From https://github.com/es-shims/es6-shim", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint && es-shim-api --bound", + "test": "npm run tests-only && npm run test:ses", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "npm run test:implementation && npm run test:shim", + "test:native": "nyc node test/native", + "test:shim": "nyc node test/shimmed", + "test:implementation": "nyc node test", + "test:ses": "node test/ses-compat", + "lint": "eslint .", + "build": "mkdir -p dist && browserify browserShim.js > dist/browser.js", + "prepublishOnly": "safe-publish-latest && npm run build", + "prepublish": "not-in-publish || npm run prepublishOnly" + }, + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object.assign.git" + }, + "keywords": [ + "Object.assign", + "assign", + "ES6", + "extend", + "$.extend", + "jQuery", + "_.extend", + "Underscore", + "es-shim API", + "polyfill", + "shim" + ], + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^21.1.1", + "browserify": "^16.5.2", + "eslint": "=8.8.0", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.0.1", + "hasown": "^2.0.2", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "ses": "^1.10.0", + "tape": "^5.9.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "bower.json", + "browserShim.js", + "!dist/" + ] + } +} diff --git a/tools/ui/node_modules/object.assign/polyfill.js b/tools/ui/node_modules/object.assign/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..ca94aea9ba30d7435bb481b8f8bfb098a9f007c0 --- /dev/null +++ b/tools/ui/node_modules/object.assign/polyfill.js @@ -0,0 +1,55 @@ +'use strict'; + +var implementation = require('./implementation'); + +var lacksProperEnumerationOrder = function () { + if (!Object.assign) { + return false; + } + /* + * v8, specifically in node 4.x, has a bug with incorrect property enumeration order + * note: this does not detect the bug unless there's 20 characters + */ + var str = 'abcdefghijklmnopqrst'; + var letters = str.split(''); + var map = {}; + for (var i = 0; i < letters.length; ++i) { + map[letters[i]] = letters[i]; + } + var obj = Object.assign({}, map); + var actual = ''; + for (var k in obj) { + actual += k; + } + return str !== actual; +}; + +var assignHasPendingExceptions = function () { + if (!Object.assign || !Object.preventExtensions) { + return false; + } + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: 2 }); + try { + Object.assign(thrower, 'xy'); + } catch (e) { + return thrower[1] === 'y'; + } + return false; +}; + +module.exports = function getPolyfill() { + if (!Object.assign) { + return implementation; + } + if (lacksProperEnumerationOrder()) { + return implementation; + } + if (assignHasPendingExceptions()) { + return implementation; + } + return Object.assign; +}; diff --git a/tools/ui/node_modules/object.assign/shim.js b/tools/ui/node_modules/object.assign/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..9f896ae3cf90a39f574d789020c40cda3eb4e9bf --- /dev/null +++ b/tools/ui/node_modules/object.assign/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimAssign() { + var polyfill = getPolyfill(); + define( + Object, + { assign: polyfill }, + { assign: function () { return Object.assign !== polyfill; } } + ); + return polyfill; +}; diff --git a/tools/ui/node_modules/object.assign/test/implementation.js b/tools/ui/node_modules/object.assign/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..05d7d7ada705b5518cf0827899513f46e1e8751e --- /dev/null +++ b/tools/ui/node_modules/object.assign/test/implementation.js @@ -0,0 +1,19 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad first arg/receiver', { skip: !hasStrictMode }, function (st) { + st['throws'](function () { implementation(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { implementation(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(implementation, Object), t); + + t.end(); +}); diff --git a/tools/ui/node_modules/object.assign/test/index.js b/tools/ui/node_modules/object.assign/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..776b2b3342e636b0c172d9192111cf7c37888454 --- /dev/null +++ b/tools/ui/node_modules/object.assign/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var assign = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(assign, t); + + t.end(); +}); diff --git a/tools/ui/node_modules/object.assign/test/native.js b/tools/ui/node_modules/object.assign/test/native.js new file mode 100644 index 0000000000000000000000000000000000000000..49a70f7987691ee4b0f6193b434b83d4c97699b5 --- /dev/null +++ b/tools/ui/node_modules/object.assign/test/native.js @@ -0,0 +1,49 @@ +'use strict'; + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('native', function (t) { + t.equal(Object.assign.length, 2, 'Object.assign has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.assign.name, 'assign', 'Object.assign has name "assign"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'assign'), 'Object.assign is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + // v8 in node 0.8 and 0.10 have non-enumerable string properties + var stringCharsAreEnumerable = isEnumerable.call('xy', 0); + t.test('when Object.assign is present and has pending exceptions', { skip: !stringCharsAreEnumerable || !Object.preventExtensions }, function (st) { + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: '2' }); + var error; + try { Object.assign(thrower, 'xy'); } catch (e) { error = e; } + st.equal(error instanceof TypeError, true, 'error is TypeError'); + st.equal(thrower[1], '2', 'thrower[1] === "2"'); + + st.end(); + }); + + runTests(Object.assign, t); + + t.end(); +}); diff --git a/tools/ui/node_modules/object.assign/test/ses-compat.js b/tools/ui/node_modules/object.assign/test/ses-compat.js new file mode 100644 index 0000000000000000000000000000000000000000..9669eb9a98e3931ad02a22b6a834e28f7234489e --- /dev/null +++ b/tools/ui/node_modules/object.assign/test/ses-compat.js @@ -0,0 +1,12 @@ +'use strict'; + +/* globals lockdown */ + +// requiring ses exposes "lockdown" on the global +require('ses'); + +// lockdown freezes the primordials +lockdown({ errorTaming: 'unsafe' }); + +// initialize the module +require('./'); diff --git a/tools/ui/node_modules/object.assign/test/shimmed.js b/tools/ui/node_modules/object.assign/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..ee577587a8961307b30651c9bfe56559eccc5c54 --- /dev/null +++ b/tools/ui/node_modules/object.assign/test/shimmed.js @@ -0,0 +1,52 @@ +'use strict'; + +var assign = require('../'); +assign.shim(); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(Object.assign.length, 2, 'Object.assign has a length of 2'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.assign.name, 'assign', 'Object.assign has name "assign"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'assign'), 'Object.assign is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.assign(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.assign(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + // v8 in node 0.8 and 0.10 have non-enumerable string properties + var stringCharsAreEnumerable = isEnumerable.call('xy', 0); + t.test('when Object.assign is present and has pending exceptions', { skip: !stringCharsAreEnumerable || !Object.preventExtensions }, function (st) { + /* + * Firefox 37 still has "pending exception" logic in its Object.assign implementation, + * which is 72% slower than our shim, and Firefox 40's native implementation. + */ + var thrower = Object.preventExtensions({ 1: '2' }); + var error; + try { Object.assign(thrower, 'xy'); } catch (e) { error = e; } + st.equal(error instanceof TypeError, true, 'error is TypeError'); + st.equal(thrower[1], '2', 'thrower[1] === "2"'); + + st.end(); + }); + + runTests(Object.assign, t); + + t.end(); +}); diff --git a/tools/ui/node_modules/object.assign/test/tests.js b/tools/ui/node_modules/object.assign/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..eff2793d3000ccfd92f3a8f18ec0f85518369f90 --- /dev/null +++ b/tools/ui/node_modules/object.assign/test/tests.js @@ -0,0 +1,232 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams')(); +var forEach = require('for-each'); +var hasOwn = require('hasown'); +var mockProperty = require('mock-property'); + +module.exports = function (assign, t) { + t.test('error cases', function (st) { + st['throws'](function () { assign(null); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(undefined); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(null, {}); }, TypeError, 'target must be an object'); + st['throws'](function () { assign(undefined, {}); }, TypeError, 'target must be an object'); + st.end(); + }); + + t.test('non-object target, no sources', function (st) { + var bool = assign(true); + st.equal(typeof bool, 'object', 'bool is object'); + st.equal(Boolean.prototype.valueOf.call(bool), true, 'bool coerces to `true`'); + + var number = assign(1); + st.equal(typeof number, 'object', 'number is object'); + st.equal(Number.prototype.valueOf.call(number), 1, 'number coerces to `1`'); + + var string = assign('1'); + st.equal(typeof string, 'object', 'number is object'); + st.equal(String.prototype.valueOf.call(string), '1', 'number coerces to `"1"`'); + + st.end(); + }); + + t.test('non-object target, with sources', function (st) { + var signal = {}; + + st.test('boolean', function (st2) { + var bool = assign(true, { a: signal }); + st2.equal(typeof bool, 'object', 'bool is object'); + st2.equal(Boolean.prototype.valueOf.call(bool), true, 'bool coerces to `true`'); + st2.equal(bool.a, signal, 'source properties copied'); + st2.end(); + }); + + st.test('number', function (st2) { + var number = assign(1, { a: signal }); + st2.equal(typeof number, 'object', 'number is object'); + st2.equal(Number.prototype.valueOf.call(number), 1, 'number coerces to `1`'); + st2.equal(number.a, signal, 'source properties copied'); + st2.end(); + }); + + st.test('string', function (st2) { + var string = assign('1', { a: signal }); + st2.equal(typeof string, 'object', 'number is object'); + st2.equal(String.prototype.valueOf.call(string), '1', 'number coerces to `"1"`'); + st2.equal(string.a, signal, 'source properties copied'); + st2.end(); + }); + + st.end(); + }); + + t.test('non-object sources', function (st) { + st.deepEqual(assign({ a: 1 }, null, { b: 2 }), { a: 1, b: 2 }, 'ignores null source'); + st.deepEqual(assign({ a: 1 }, { b: 2 }, undefined), { a: 1, b: 2 }, 'ignores undefined source'); + st.end(); + }); + + t.test('returns the modified target object', function (st) { + var target = {}; + var returned = assign(target, { a: 1 }); + st.equal(returned, target, 'returned object is the same reference as the target object'); + st.end(); + }); + + t.test('has the right length', function (st) { + st.equal(assign.length, 2, 'length is 2 => 2 required arguments'); + st.end(); + }); + + t.test('merge two objects', function (st) { + var target = { a: 1 }; + var returned = assign(target, { b: 2 }); + st.deepEqual(returned, { a: 1, b: 2 }, 'returned object has properties from both'); + st.end(); + }); + + t.test('works with functions', function (st) { + var target = function () {}; + target.a = 1; + var returned = assign(target, { b: 2 }); + st.equal(target, returned, 'returned object is target'); + st.equal(returned.a, 1); + st.equal(returned.b, 2); + st.end(); + }); + + t.test('works with primitives', function (st) { + var target = 2; + var source = { b: 42 }; + var returned = assign(target, source); + st.equal(Object.prototype.toString.call(returned), '[object Number]', 'returned is object form of number primitive'); + st.equal(Number(returned), target, 'returned and target have same valueOf'); + st.equal(returned.b, source.b); + st.end(); + }); + + /* globals window */ + t.test('works with window.location', { skip: typeof window === 'undefined' }, function (st) { + var target = {}; + assign(target, window.location); + for (var prop in window.location) { + if (hasOwn(window.location, prop)) { + st.deepEqual(target[prop], window.location[prop], prop + ' is copied'); + } + } + st.end(); + }); + + t.test('merge N objects', function (st) { + var target = { a: 1 }; + var source1 = { b: 2 }; + var source2 = { c: 3 }; + var returned = assign(target, source1, source2); + st.deepEqual(returned, { a: 1, b: 2, c: 3 }, 'returned object has properties from all sources'); + st.end(); + }); + + t.test('only iterates over own keys', function (st) { + var Foo = function () {}; + Foo.prototype.bar = true; + var foo = new Foo(); + foo.baz = true; + var target = { a: 1 }; + var returned = assign(target, foo); + st.equal(returned, target, 'returned object is the same reference as the target object'); + st.deepEqual(target, { a: 1, baz: true }, 'returned object has only own properties from both'); + st.end(); + }); + + t.test('includes enumerable symbols, after keys', { skip: !hasSymbols }, function (st) { + var visited = []; + var obj = {}; + Object.defineProperty(obj, 'a', { enumerable: true, get: function () { visited.push('a'); return 42; } }); + var symbol = Symbol('enumerable'); + Object.defineProperty(obj, symbol, { + enumerable: true, + get: function () { visited.push(symbol); return Infinity; } + }); + var nonEnumSymbol = Symbol('non-enumerable'); + Object.defineProperty(obj, nonEnumSymbol, { + enumerable: false, + get: function () { visited.push(nonEnumSymbol); return -Infinity; } + }); + var target = assign({}, obj); + st.deepEqual(visited, ['a', symbol], 'key is visited first, then symbol'); + st.equal(target.a, 42, 'target.a is 42'); + st.equal(target[symbol], Infinity, 'target[symbol] is Infinity'); + st.notEqual(target[nonEnumSymbol], -Infinity, 'target[nonEnumSymbol] is not -Infinity'); + st.end(); + }); + + t.test('does not fail when symbols are not present', { skip: !Object.isFrozen || Object.isFrozen(Object) }, function (st) { + st.teardown(mockProperty(Object, 'getOwnPropertySymbols', { 'delete': true })); + + var visited = []; + var obj = {}; + Object.defineProperty(obj, 'a', { enumerable: true, get: function () { visited.push('a'); return 42; } }); + var keys = ['a']; + if (hasSymbols) { + var symbol = Symbol('sym'); + Object.defineProperty(obj, symbol, { + enumerable: true, + get: function () { visited.push(symbol); return Infinity; } + }); + keys.push(symbol); + } + var target = assign({}, obj); + st.deepEqual(visited, keys, 'assign visits expected keys'); + st.equal(target.a, 42, 'target.a is 42'); + + if (hasSymbols) { + st.equal(target[symbol], Infinity); + } + st.end(); + }); + + t.test('preserves correct property enumeration order', function (st) { + var str = 'abcdefghijklmnopqrst'; + var letters = {}; + forEach(str.split(''), function (letter) { + letters[letter] = letter; + }); + + var n = 5; + st.comment('run the next test ' + n + ' times'); + var object = assign({}, letters); + var actual = ''; + for (var k in object) { + actual += k; + } + for (var i = 0; i < n; ++i) { + st.equal(actual, str, 'property enumeration order should be followed'); + } + st.end(); + }); + + t.test('checks enumerability and existence, in case of modification during [[Get]]', { skip: !Object.defineProperty }, function (st) { + var targetBvalue = {}; + var targetCvalue = {}; + var target = { b: targetBvalue, c: targetCvalue }; + var source = {}; + Object.defineProperty(source, 'a', { + enumerable: true, + get: function () { + delete this.b; + Object.defineProperty(this, 'c', { enumerable: false }); + return 'a'; + } + }); + var sourceBvalue = {}; + var sourceCvalue = {}; + source.b = sourceBvalue; + source.c = sourceCvalue; + var result = assign(target, source); + st.equal(result, target, 'sanity check: result is === target'); + st.equal(result.b, targetBvalue, 'target key not overwritten by deleted source key'); + st.equal(result.c, targetCvalue, 'target key not overwritten by non-enumerable source key'); + + st.end(); + }); +}; diff --git a/tools/ui/node_modules/obug/LICENSE b/tools/ui/node_modules/obug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..12eb1480b950f145a3ef976671da3337d621e5b8 --- /dev/null +++ b/tools/ui/node_modules/obug/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright © 2025-PRESENT Kevin Deng (https://github.com/sxzz) +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon + +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. diff --git a/tools/ui/node_modules/obug/README.md b/tools/ui/node_modules/obug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ae9d9fc3f4d137fa95c1c791ed1975716b4daec3 --- /dev/null +++ b/tools/ui/node_modules/obug/README.md @@ -0,0 +1,251 @@ +# obug + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![JSR][jsr-badge-src]][jsr-badge-href] +[![Unit Test][unit-test-src]][unit-test-href] + +A lightweight JavaScript debugging utility, forked from [debug](https://www.npmjs.com/package/debug), featuring TypeScript and ESM support. + +> [!NOTE] +> obug v1 retains most of the compatibility with [debug](https://github.com/debug-js/debug), but drops support for older browsers and Node.js, making it a drop-in replacement. +> +> obug v2 refactors some API imports and usage for better support of ESM and TypeScript, easier customization, and an even smaller package size. + +## Key Differences from `debug` + +- ✨ Minimal footprint + - 7.7 kB package size + - 1.4 KB minified + gzipped for browsers +- 📦 Zero dependencies +- 📝 Full TypeScript support +- 🚀 Native ESM compatibility +- 🌐 Optimized for modern runtimes + - ES2015+ browsers + - Modern Node.js versions +- 🎨 Customizable formatting + +## Installation + +```bash +npm install obug +``` + +## Usage + +```ts +import { createDebug, disable, enable, enabled, namespaces } from 'obug' + +// Get the currently enabled namespaces +console.log(namespaces()) + +const debug = createDebug('my-namespace', { + // All options are optional + + useColors: true, // false, true, undefined for auto-detect + color: 2, // custom color + // custom formatArgs + formatArgs(args) {}, + formatters: {}, + // Node.js only + inspectOpts: {}, + + // custom log + log: console.log, +}) + +debug('This is a debug message') +console.log( + debug.namespace, // 'my-namespace' + debug.enabled, // Check if enabled + debug.useColors, // true + debug.color, // 2 + debug.formatArgs, // custom formatArgs + debug.formatters, // {} + debug.inspectOpts, // {} + debug.log, // implemented log function +) + +// Create a sub-namespace, and it will inherit options from the parent debugger +const sub = debug.extend('sub-namespace') +sub('This is a sub-namespace debug message') +console.log(sub.namespace) // 'my-namespace:sub-namespace' +``` + +## How to use + +### Enabling debug output + +obug picks up enabled namespaces from the `DEBUG` environment variable in Node.js, or from `localStorage.debug` in browsers. + +In Node.js: + +```bash +DEBUG=app:* node app.js +``` + +On Windows (CMD): + +```cmd +set DEBUG=app:* & node app.js +``` + +On Windows (PowerShell): + +```powershell +$env:DEBUG='app:*'; node app.js +``` + +In the browser, set the value in DevTools and refresh the page: + +```js +localStorage.debug = 'app:*' +``` + +### Wildcards and exclusion + +The `*` character is a wildcard. Suppose your library has debuggers named `connect:bodyParser`, `connect:compress`, and `connect:session` — instead of listing each one, use `DEBUG=connect:*`. Use `DEBUG=*` to enable everything. + +Exclude namespaces by prefixing them with `-`: + +```bash +DEBUG=*,-connect:* node app.js +``` + +### Namespace conventions + +If you're using obug in a library, prefix your namespaces with the library name and use `:` to separate features (e.g. `connect:bodyParser`). This lets users opt into the parts they care about without guessing names. + +### Extending a namespace + +Use `.extend()` to create a sub-namespace that inherits options from its parent: + +```ts +const log = createDebug('auth') +const logSign = log.extend('sign') // 'auth:sign' +const logLogin = log.extend('login') // 'auth:login' + +log('hello') // auth hello +logSign('hello') // auth:sign hello +logLogin('hello') // auth:login hello +``` + +### Formatters + +obug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Built-in formatters: + +| Formatter | Representation | +| --------- | -------------------------------------------------- | +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%%` | Single percent sign. Does not consume an argument. | + +Other format specifiers supported by Node's `util.format` (`%s`, `%d`, `%j`, …) and the browser console pass through to the underlying logger. + +#### Custom formatters + +Register custom formatters via the `formatters` option. For example, to render a `Buffer` as hex with `%h`: + +```ts +const debug = createDebug('foo', { + formatters: { + h: (v) => v.toString('hex'), + }, +}) + +debug('this is hex: %h', Buffer.from('hello world')) +// foo this is hex: 68656c6c6f20776f726c64 +0ms +``` + +### Dynamic enable / disable + +You can toggle namespaces at runtime: + +```ts +import { disable, enable, enabled, namespaces } from 'obug' + +enable('app:*') +console.log(enabled('app:server')) // true + +const previous = disable() +console.log(enabled('app:server')) // false + +// Restore later +enable(previous) +``` + +`namespaces()` returns the string of currently enabled namespaces. Note that calling `enable()` overrides the value initially read from `DEBUG`. + +### Checking whether a debugger is enabled + +Guard expensive work behind the `enabled` property: + +```ts +const debug = createDebug('http') + +if (debug.enabled) { + // expensive computation only when enabled +} +``` + +You can also force the state by assigning to `debug.enabled` directly. + +### Custom output + +By default, obug writes to `stderr` in Node.js and to the console in browsers. Override the `log` option to redirect output per-namespace: + +```ts +const log = createDebug('app:log', { + log: console.log, +}) + +const error = createDebug('app:error') // still goes to stderr +``` + +### Environment variables (Node.js) + +| Name | Purpose | +| ------------------- | ----------------------------------------------- | +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS` | Whether to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + +Variables prefixed with `DEBUG_` are converted to camelCase keys on the options object passed to Node's [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the `%o` / `%O` formatters. + +## Original Authors + +As obug is a fork of debug with significant modifications, we would like to acknowledge the original authors: + +- TJ Holowaychuk +- Nathan Rajlich +- Andrew Rhyne +- Josh Junon + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2025-PRESENT [Kevin Deng](https://github.com/sxzz) + +[The MIT License](./LICENSE) Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +[The MIT License](./LICENSE) Copyright (c) 2018-2021 Josh Junon + + + +[npm-version-src]: https://img.shields.io/npm/v/obug.svg +[npm-version-href]: https://npmjs.com/package/obug +[npm-downloads-src]: https://img.shields.io/npm/dm/obug +[npm-downloads-href]: https://www.npmcharts.com/compare/obug?interval=30 +[unit-test-src]: https://github.com/sxzz/obug/actions/workflows/unit-test.yml/badge.svg +[unit-test-href]: https://github.com/sxzz/obug/actions/workflows/unit-test.yml +[jsr-badge-src]: https://jsr.io/badges/@sxzz/obug +[jsr-badge-href]: https://jsr.io/@sxzz/obug diff --git a/tools/ui/node_modules/obug/dist/browser.d.ts b/tools/ui/node_modules/obug/dist/browser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95b22fbf5342fde6b25d73e6c74ec3b2fbd8356c --- /dev/null +++ b/tools/ui/node_modules/obug/dist/browser.d.ts @@ -0,0 +1,11 @@ +import { a as Debugger, i as DebugOptions, n as enabled, o as Formatters, r as namespaces, s as InspectOptions, t as disable } from "./core.js"; + +//#region src/browser.d.ts +declare function createDebug(namespace: string, options?: DebugOptions): Debugger; +/** +* Enables a debug mode by namespaces. This can include modes +* separated by a colon and wildcards. +*/ +declare function enable(namespaces: string): void; +//#endregion +export { type DebugOptions, type Debugger, type Formatters, type InspectOptions, createDebug, disable, enable, enabled, namespaces }; \ No newline at end of file diff --git a/tools/ui/node_modules/obug/dist/browser.js b/tools/ui/node_modules/obug/dist/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..582feaaab1137047946c4eb23f4943abb31765e8 --- /dev/null +++ b/tools/ui/node_modules/obug/dist/browser.js @@ -0,0 +1,166 @@ +import { a as namespaces, i as enabled, n as disable, o as humanize, r as enable$1, s as selectColor, t as createDebug$1 } from "./core.js"; +//#region src/browser.ts +const colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" +]; +/** +* Colorize log arguments if enabled. +*/ +function formatArgs(diff, args) { + const { useColors } = this; + args[0] = `${(useColors ? "%c" : "") + this.namespace + (useColors ? " %c" : " ") + args[0] + (useColors ? "%c " : " ")}+${this.humanize(diff)}`; + if (!useColors) return; + const c = `color: ${this.color}`; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-z%]/gi, (match) => { + if (match === "%%") return; + index++; + if (match === "%c") lastC = index; + }); + args.splice(lastC, 0, c); +} +/** +* Invokes `console.debug()` when available. +* No-op when `console.debug` is not a "function". +* If `console.debug` is not available, falls back +* to `console.log`. +*/ +const log = console.debug || console.log || (() => {}); +const storage = localstorage(); +const defaultOptions = { + useColors: true, + formatArgs, + formatters: { + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ +j(v) { + try { + return JSON.stringify(v); + } catch (error) { + return `[UnexpectedJSONParseError]: ${error.message}`; + } + } }, + inspectOpts: {}, + humanize, + log +}; +function createDebug(namespace, options) { + var _ref; + const color = (_ref = options && options.color) !== null && _ref !== void 0 ? _ref : selectColor(colors, namespace); + return createDebug$1(namespace, Object.assign(defaultOptions, { color }, options)); +} +/** +* Localstorage attempts to return the localstorage. +* +* This is necessary because safari throws +* when a user disables cookies/localstorage +* and you attempt to access it. +*/ +function localstorage() { + try { + return localStorage; + } catch (_unused) {} +} +function load() { + let r; + try { + r = storage.getItem("debug") || storage.getItem("DEBUG"); + } catch (_unused2) {} + if (!r && typeof process !== "undefined" && "env" in process) r = process.env.DEBUG; + return r || ""; +} +function save(namespaces) { + try { + if (namespaces) storage.setItem("debug", namespaces); + else storage.removeItem("debug"); + } catch (_unused3) {} +} +/** +* Enables a debug mode by namespaces. This can include modes +* separated by a colon and wildcards. +*/ +function enable(namespaces) { + save(namespaces); + enable$1(namespaces); +} +enable$1(load()); +//#endregion +export { createDebug, disable, enable, enabled, namespaces }; diff --git a/tools/ui/node_modules/obug/dist/browser.min.js b/tools/ui/node_modules/obug/dist/browser.min.js new file mode 100644 index 0000000000000000000000000000000000000000..b93cb3a02f30e24e0bcd2c3d8ad529e7781e677b --- /dev/null +++ b/tools/ui/node_modules/obug/dist/browser.min.js @@ -0,0 +1 @@ +function e(e){return e instanceof Error?e.stack||e.message:e}function t(e,t){let n=0;for(let e=0;e=1e3?`${(e/1e3).toFixed(1)}s`:`${e}ms`}let i=``;function a(){return i}function o(t,n){let r,a,s,c,l=(...t)=>{if(!l.enabled)return;let i=Date.now(),a=i-(r||i);r=i,t[0]=e(t[0]),typeof t[0]!=`string`&&t.unshift(`%O`);let o=0;t[0]=t[0].replace(/%([a-z%])/gi,(e,r)=>{if(e===`%%`)return`%`;o++;let i=n.formatters[r];if(typeof i==`function`){let n=t[o];e=i.call(l,n),t.splice(o,1),o--}return e}),n.formatArgs.call(l,a,t),l.log(...t)};return l.extend=function(e,t=`:`){return o(this.namespace+t+e,{useColors:this.useColors,color:this.color,formatArgs:this.formatArgs,formatters:this.formatters,inspectOpts:this.inspectOpts,log:this.log,humanize:this.humanize})},Object.assign(l,n),l.namespace=t,Object.defineProperty(l,"enabled",{enumerable:!0,configurable:!1,get:()=>a==null?(s!==i&&(s=i,c=d(t)),c):a,set:e=>{a=e}}),l}let s=[],c=[];function l(e){i=e,s=[],c=[];let t=i.trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?c.push(e.slice(1)):s.push(e)}function u(){let e=[...s,...c.map(e=>`-${e}`)].join(`,`);return l(``),e}function d(e){for(let t of c)if(n(e,t))return!1;for(let t of s)if(n(e,t))return!0;return!1}const f=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function p(e,t){let{useColors:n}=this;if(t[0]=`${(n?`%c`:``)+this.namespace+(n?` %c`:` `)+t[0]+(n?`%c `:` `)}+${this.humanize(e)}`,!n)return;let r=`color: ${this.color}`;t.splice(1,0,r,`color: inherit`);let i=0,a=0;t[0].replace(/%[a-z%]/gi,e=>{e!==`%%`&&(i++,e===`%c`&&(a=i))}),t.splice(a,0,r)}const m=console.debug||console.log||(()=>{}),h=v(),g={useColors:!0,formatArgs:p,formatters:{j(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: ${e.message}`}}},inspectOpts:{},humanize:r,log:m};function _(e,n){var r;let i=(r=n&&n.color)==null?t(f,e):r;return o(e,Object.assign(g,{color:i},n))}function v(){try{return localStorage}catch(e){}}function y(){let e;try{e=h.getItem(`debug`)||h.getItem(`DEBUG`)}catch(e){}return!e&&typeof process<`u`&&`env`in process&&(e=process.env.DEBUG),e||``}function b(e){try{e?h.setItem(`debug`,e):h.removeItem(`debug`)}catch(e){}}function x(e){b(e),l(e)}l(y());export{_ as createDebug,u as disable,x as enable,d as enabled,a as namespaces}; \ No newline at end of file diff --git a/tools/ui/node_modules/obug/dist/core.d.ts b/tools/ui/node_modules/obug/dist/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..61f80ae399783af419de1c3c08cc5eb64e503f38 --- /dev/null +++ b/tools/ui/node_modules/obug/dist/core.d.ts @@ -0,0 +1,47 @@ +import { InspectOptions } from "node:util"; + +//#region src/types.d.ts +interface InspectOptions$1 extends InspectOptions { + hideDate?: boolean; +} +/** +* Map of special "%n" handling functions, for the debug "format" argument. +* +* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". +*/ +interface Formatters { + [formatter: string]: (this: Debugger, v: any) => string; +} +interface Debugger extends Required { + (formatter: any, ...args: any[]): void; + namespace: string; + enabled: boolean; + extend: (namespace: string, delimiter?: string) => Debugger; +} +interface DebugOptions { + useColors?: boolean; + color?: string | number; + formatArgs?: (this: Debugger, diff: number, args: [string, ...any[]]) => void; + formatters?: Formatters; + /** Node.js only */ + inspectOpts?: InspectOptions$1; + /** Humanize a duration in milliseconds */ + humanize?: (value: number) => string; + log?: (this: Debugger, ...args: any[]) => void; +} +//#endregion +//#region src/core.d.ts +/** +* Returns a string of the currently enabled debug namespaces. +*/ +declare function namespaces(): string; +/** +* Disable debug output. +*/ +declare function disable(): string; +/** +* Returns true if the given mode name is enabled, false otherwise. +*/ +declare function enabled(name: string): boolean; +//#endregion +export { Debugger as a, DebugOptions as i, enabled as n, Formatters as o, namespaces as r, InspectOptions$1 as s, disable as t }; \ No newline at end of file diff --git a/tools/ui/node_modules/obug/dist/core.js b/tools/ui/node_modules/obug/dist/core.js new file mode 100644 index 0000000000000000000000000000000000000000..cb1343560cc26fa82f8bee1ea33ddae3f015747d --- /dev/null +++ b/tools/ui/node_modules/obug/dist/core.js @@ -0,0 +1,144 @@ +//#region src/utils.ts +/** +* Coerce `value`. +*/ +function coerce(value) { + if (value instanceof Error) return value.stack || value.message; + return value; +} +/** +* Selects a color for a debug namespace +* @return An ANSI color code for the given namespace +*/ +function selectColor(colors, namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return colors[Math.abs(hash) % colors.length]; +} +/** +* Checks if the given string matches a namespace template, honoring +* asterisks as wildcards. +*/ +function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else return false; + while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++; + return templateIndex === template.length; +} +function humanize(value) { + if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`; + return `${value}ms`; +} +//#endregion +//#region src/core.ts +let globalNamespaces = ""; +/** +* Returns a string of the currently enabled debug namespaces. +*/ +function namespaces() { + return globalNamespaces; +} +function createDebug(namespace, options) { + let prevTime; + let enableOverride; + let namespacesCache; + let enabledCache; + const debug = (...args) => { + if (!debug.enabled) return; + const curr = Date.now(); + const diff = curr - (prevTime || curr); + prevTime = curr; + args[0] = coerce(args[0]); + if (typeof args[0] !== "string") args.unshift("%O"); + let index = 0; + args[0] = args[0].replace(/%([a-z%])/gi, (match, format) => { + if (match === "%%") return "%"; + index++; + const formatter = options.formatters[format]; + if (typeof formatter === "function") { + const value = args[index]; + match = formatter.call(debug, value); + args.splice(index, 1); + index--; + } + return match; + }); + options.formatArgs.call(debug, diff, args); + debug.log(...args); + }; + debug.extend = function(namespace, delimiter = ":") { + return createDebug(this.namespace + delimiter + namespace, { + useColors: this.useColors, + color: this.color, + formatArgs: this.formatArgs, + formatters: this.formatters, + inspectOpts: this.inspectOpts, + log: this.log, + humanize: this.humanize + }); + }; + Object.assign(debug, options); + debug.namespace = namespace; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride != null) return enableOverride; + if (namespacesCache !== globalNamespaces) { + namespacesCache = globalNamespaces; + enabledCache = enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + return debug; +} +let names = []; +let skips = []; +function enable(namespaces) { + globalNamespaces = namespaces; + names = []; + skips = []; + const split = globalNamespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) if (ns[0] === "-") skips.push(ns.slice(1)); + else names.push(ns); +} +/** +* Disable debug output. +*/ +function disable() { + const namespaces = [...names, ...skips.map((namespace) => `-${namespace}`)].join(","); + enable(""); + return namespaces; +} +/** +* Returns true if the given mode name is enabled, false otherwise. +*/ +function enabled(name) { + for (const skip of skips) if (matchesTemplate(name, skip)) return false; + for (const ns of names) if (matchesTemplate(name, ns)) return true; + return false; +} +//#endregion +export { namespaces as a, enabled as i, disable as n, humanize as o, enable as r, selectColor as s, createDebug as t }; diff --git a/tools/ui/node_modules/obug/dist/node.d.ts b/tools/ui/node_modules/obug/dist/node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa3b8495973fc093db62be5a80afff16db08c30b --- /dev/null +++ b/tools/ui/node_modules/obug/dist/node.d.ts @@ -0,0 +1,11 @@ +import { a as Debugger, i as DebugOptions, n as enabled, o as Formatters, r as namespaces, s as InspectOptions, t as disable } from "./core.js"; + +//#region src/node.d.ts +declare function createDebug(namespace: string, options?: DebugOptions): Debugger; +/** +* Enables a debug mode by namespaces. This can include modes +* separated by a colon and wildcards. +*/ +declare function enable(namespaces: string): void; +//#endregion +export { type DebugOptions, type Debugger, type Formatters, type InspectOptions, createDebug, disable, enable, enabled, namespaces }; \ No newline at end of file diff --git a/tools/ui/node_modules/obug/dist/node.js b/tools/ui/node_modules/obug/dist/node.js new file mode 100644 index 0000000000000000000000000000000000000000..d04958661116ef8568463904fd6a39d6b14a6486 --- /dev/null +++ b/tools/ui/node_modules/obug/dist/node.js @@ -0,0 +1,169 @@ +import { a as namespaces, i as enabled, n as disable, o as humanize, r as enable$1, s as selectColor, t as createDebug$1 } from "./core.js"; +import { isatty } from "node:tty"; +import { formatWithOptions, inspect } from "node:util"; +//#region src/node.ts +const colors = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 +] : [ + 6, + 2, + 3, + 4, + 5, + 1 +]; +const inspectOpts = Object.keys(process.env).filter((key) => /^debug_/i.test(key)).reduce((obj, key) => { + const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase()); + let value = process.env[key]; + const lowerCase = typeof value === "string" && value.toLowerCase(); + if (value === "null") value = null; + else if (lowerCase === "yes" || lowerCase === "on" || lowerCase === "true" || lowerCase === "enabled") value = true; + else if (lowerCase === "no" || lowerCase === "off" || lowerCase === "false" || lowerCase === "disabled") value = false; + else value = Number(value); + obj[prop] = value; + return obj; +}, Object.create(null)); +/** +* Is stdout a TTY? Colored output is enabled when `true`. +*/ +function useColors() { + return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd); +} +function getDate() { + if (inspectOpts.hideDate) return ""; + return `${(/* @__PURE__ */ new Date()).toISOString()} `; +} +/** +* Adds ANSI color escape codes if enabled. +*/ +function formatArgs(diff, args) { + const { namespace: name, useColors } = this; + if (useColors) { + const c = this.color; + const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`; + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + args[0] = prefix + args[0].split("\n").join(`\n${prefix}`); + args.push(`${colorCode}m+${this.humanize(diff)}\u001B[0m`); + } else args[0] = `${getDate()}${name} ${args[0]}`; +} +function log(...args) { + process.stderr.write(`${formatWithOptions(this.inspectOpts, ...args)}\n`); +} +const defaultOptions = { + useColors: useColors(), + formatArgs, + formatters: { + /** + * Map %o to `util.inspect()`, all on a single line. + */ + o(v) { + this.inspectOpts.colors = this.useColors; + return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }, + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + O(v) { + this.inspectOpts.colors = this.useColors; + return inspect(v, this.inspectOpts); + } + }, + inspectOpts, + log, + humanize +}; +function createDebug(namespace, options) { + var _ref; + const color = (_ref = options && options.color) !== null && _ref !== void 0 ? _ref : selectColor(colors, namespace); + return createDebug$1(namespace, Object.assign(defaultOptions, { color }, options)); +} +function save(namespaces) { + if (namespaces) process.env.DEBUG = namespaces; + else delete process.env.DEBUG; +} +/** +* Enables a debug mode by namespaces. This can include modes +* separated by a colon and wildcards. +*/ +function enable(namespaces) { + save(namespaces); + enable$1(namespaces); +} +enable$1(process.env.DEBUG || ""); +//#endregion +export { createDebug, disable, enable, enabled, namespaces }; diff --git a/tools/ui/node_modules/obug/package.json b/tools/ui/node_modules/obug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..716f816637b2153a446a42004cfecbde47c729a0 --- /dev/null +++ b/tools/ui/node_modules/obug/package.json @@ -0,0 +1,72 @@ +{ + "name": "obug", + "type": "module", + "version": "2.1.2", + "description": "A lightweight JavaScript debugging utility, forked from debug, featuring TypeScript and ESM support.", + "author": "Kevin Deng ", + "license": "MIT", + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "homepage": "https://github.com/sxzz/obug#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/sxzz/obug.git" + }, + "bugs": { + "url": "https://github.com/sxzz/obug/issues" + }, + "exports": { + ".": { + "browser": "./dist/browser.js", + "default": "./dist/node.js" + }, + "./package.json": "./package.json" + }, + "main": "./dist/node.js", + "module": "./dist/node.js", + "unpkg": "./dist/browser.min.js", + "jsdelivr": "./dist/browser.min.js", + "types": "./dist/browser.d.ts", + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "engines": { + "node": ">=12.20.0" + }, + "devDependencies": { + "@sxzz/eslint-config": "^8.1.0", + "@sxzz/prettier-config": "^2.3.1", + "@types/debug": "^4.1.13", + "@types/node": "^25.9.1", + "@typescript/native-preview": "7.0.0-dev.20260603.1", + "@vitest/browser-playwright": "^4.1.8", + "@vitest/coverage-v8": "^4.1.8", + "bumpp": "^11.1.0", + "debug": "^4.4.3", + "eslint": "^10.4.1", + "playwright": "^1.60.0", + "prettier": "^3.8.3", + "tsdown": "^0.22.1", + "typescript": "^6.0.3", + "vite": "^8.0.16", + "vitest": "^4.1.8" + }, + "prettier": "@sxzz/prettier-config", + "scripts": { + "lint": "eslint --cache .", + "lint:fix": "pnpm run lint --fix", + "build": "tsdown", + "dev": "tsdown --watch", + "test": "vitest", + "test:coverage": "vitest --project node --coverage", + "play": "vite playground", + "typecheck": "tsgo --noEmit", + "format": "prettier --cache --write .", + "release": "bumpp" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/on-finished/HISTORY.md b/tools/ui/node_modules/on-finished/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..1917595a714e11049ec9402d87aa625c68caa080 --- /dev/null +++ b/tools/ui/node_modules/on-finished/HISTORY.md @@ -0,0 +1,98 @@ +2.4.1 / 2022-02-22 +================== + + * Fix error on early async hooks implementations + +2.4.0 / 2022-02-21 +================== + + * Prevent loss of async hooks context + +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/tools/ui/node_modules/on-finished/LICENSE b/tools/ui/node_modules/on-finished/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5931fd23eab9dd3be559cd4bd81253df87a5297c --- /dev/null +++ b/tools/ui/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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. diff --git a/tools/ui/node_modules/on-finished/README.md b/tools/ui/node_modules/on-finished/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8973cded6589a6cc5a9e1718e3fb0d709fe6e8d8 --- /dev/null +++ b/tools/ui/node_modules/on-finished/README.md @@ -0,0 +1,162 @@ +# on-finished + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + + + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error if request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + + + +```js +var data = '' + +req.setEncoding('utf8') +req.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var fs = require('fs') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest (req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function () { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/on-finished/master?label=ci +[ci-url]: https://github.com/jshttp/on-finished/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-finished/master +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[node-image]: https://badgen.net/npm/node/on-finished +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/on-finished +[npm-url]: https://npmjs.org/package/on-finished +[npm-version-image]: https://badgen.net/npm/v/on-finished diff --git a/tools/ui/node_modules/on-finished/index.js b/tools/ui/node_modules/on-finished/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e68df7bde39bb47aa1fd7eff4b317b3969de75bd --- /dev/null +++ b/tools/ui/node_modules/on-finished/index.js @@ -0,0 +1,234 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var asyncHooks = tryRequireAsyncHooks() +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished (msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, wrap(listener)) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished (msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener (msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish (error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket (socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // istanbul ignore next: node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener (msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener (msg) { + function listener (err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +// istanbul ignore next: node.js 0.8 patch +function patchAssignSocket (res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket (socket) { + assignSocket.call(this, socket) + callback(socket) + } +} + +/** + * Try to require async_hooks + * @private + */ + +function tryRequireAsyncHooks () { + try { + return require('async_hooks') + } catch (e) { + return {} + } +} + +/** + * Wrap function with async resource, if possible. + * AsyncResource.bind static method backported. + * @private + */ + +function wrap (fn) { + var res + + // create anonymous resource + if (asyncHooks.AsyncResource) { + res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + } + + // incompatible node.js + if (!res || !res.runInAsyncScope) { + return fn + } + + // return bound function + return res.runInAsyncScope.bind(res, fn, null) +} diff --git a/tools/ui/node_modules/on-finished/package.json b/tools/ui/node_modules/on-finished/package.json new file mode 100644 index 0000000000000000000000000000000000000000..644cd814b9d745714e4d16753de8bc8856e201e4 --- /dev/null +++ b/tools/ui/node_modules/on-finished/package.json @@ -0,0 +1,39 @@ +{ + "name": "on-finished", + "description": "Execute a callback when a request closes, finishes, or errors", + "version": "2.4.1", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/on-finished", + "dependencies": { + "ee-first": "1.1.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/tools/ui/node_modules/once/LICENSE b/tools/ui/node_modules/once/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19129e315fe593965a2fdd50ec0d1253bcbd2ece --- /dev/null +++ b/tools/ui/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/tools/ui/node_modules/once/README.md b/tools/ui/node_modules/once/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1f1ffca9330e3ceddd54106e1ba63322fc9751f8 --- /dev/null +++ b/tools/ui/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/tools/ui/node_modules/once/once.js b/tools/ui/node_modules/once/once.js new file mode 100644 index 0000000000000000000000000000000000000000..235406736d9d9485bbc0dd0820dd661110da7a4d --- /dev/null +++ b/tools/ui/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/tools/ui/node_modules/once/package.json b/tools/ui/node_modules/once/package.json new file mode 100644 index 0000000000000000000000000000000000000000..16815b2fa111936c9681a1b76c5fce98421c1631 --- /dev/null +++ b/tools/ui/node_modules/once/package.json @@ -0,0 +1,33 @@ +{ + "name": "once", + "version": "1.4.0", + "description": "Run a function exactly one time", + "main": "once.js", + "directories": { + "test": "test" + }, + "dependencies": { + "wrappy": "1" + }, + "devDependencies": { + "tap": "^7.0.1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "files": [ + "once.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once" + }, + "keywords": [ + "once", + "function", + "one", + "single" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC" +} diff --git a/tools/ui/node_modules/open/index.d.ts b/tools/ui/node_modules/open/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b754b2af41ca9a3dc179b3b6467793d55d6689bf --- /dev/null +++ b/tools/ui/node_modules/open/index.d.ts @@ -0,0 +1,158 @@ +import {type ChildProcess} from 'node:child_process'; + +export type Options = { + /** + Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app. + + Note that it waits for the app to exit, not just for the window to close. + + On Windows, you have to explicitly specify an app for it to be able to wait. + + @default false + */ + readonly wait?: boolean; + + /** + __macOS only__ + + Do not bring the app to the foreground. + + @default false + */ + readonly background?: boolean; + + /** + __macOS only__ + + Open a new instance of the app even it's already running. + + A new instance is always opened on other platforms. + + @default false + */ + readonly newInstance?: boolean; + + /** + Specify the `name` of the app to open the `target` with, and optionally, app `arguments`. `app` can be an array of apps to try to open and `name` can be an array of app names to try. If each app fails, the last error will be thrown. + + The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows. If possible, use `apps` which auto-detects the correct binary to use. + + You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome. + + The app `arguments` are app dependent. Check the app's documentation for what arguments it accepts. + */ + readonly app?: App | readonly App[]; + + /** + Allow the opened app to exit with nonzero exit code when the `wait` option is `true`. + + We do not recommend setting this option. The convention for success is exit code zero. + + @default false + */ + readonly allowNonzeroExitCode?: boolean; +}; + +export type OpenAppOptions = { + /** + Arguments passed to the app. + + These arguments are app dependent. Check the app's documentation for what arguments it accepts. + */ + readonly arguments?: readonly string[]; +} & Omit; + +export type AppName = + | 'chrome' + | 'brave' + | 'firefox' + | 'edge' + | 'browser' + | 'browserPrivate'; + +export type App = { + name: string | readonly string[]; + arguments?: readonly string[]; +}; + +/** +An object containing auto-detected binary names for common apps. Useful to work around cross-platform differences. + +@example +``` +import open, {apps} from 'open'; + +await open('https://google.com', { + app: { + name: apps.chrome + } +}); +``` +*/ +export const apps: Record; + +/** +Open stuff like URLs, files, executables. Cross-platform. + +Uses the command `open` on macOS, `start` on Windows and `xdg-open` on other platforms. + +There is a caveat for [double-quotes on Windows](https://github.com/sindresorhus/open#double-quotes-on-windows) where all double-quotes are stripped from the `target`. + +@param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. For example, URLs open in your default browser. +@returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process. + +@example +``` +import open, {apps} from 'open'; + +// Opens the image in the default image viewer. +await open('unicorn.png', {wait: true}); +console.log('The image viewer app quit'); + +// Opens the URL in the default browser. +await open('https://sindresorhus.com'); + +// Opens the URL in a specified browser. +await open('https://sindresorhus.com', {app: {name: 'firefox'}}); + +// Specify app arguments. +await open('https://sindresorhus.com', {app: {name: 'google chrome', arguments: ['--incognito']}}); + +// Opens the URL in the default browser in incognito mode. +await open('https://sindresorhus.com', {app: {name: apps.browserPrivate}}); +``` +*/ +export default function open( + target: string, + options?: Options +): Promise; + +/** +Open an app. Cross-platform. + +Uses the command `open` on macOS, `start` on Windows and `xdg-open` on other platforms. + +@param name - The app you want to open. Can be either builtin supported `apps` names or other name supported in platform. +@returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process. + +@example +``` +import open, {openApp, apps} from 'open'; + +// Open Firefox. +await openApp(apps.firefox); + +// Open Chrome in incognito mode. +await openApp(apps.chrome, {arguments: ['--incognito']}); + +// Open default browser. +await openApp(apps.browser); + +// Open default browser in incognito mode. +await openApp(apps.browserPrivate); + +// Open Xcode. +await openApp('xcode'); +``` +*/ +export function openApp(name: App['name'], options?: OpenAppOptions): Promise; diff --git a/tools/ui/node_modules/open/index.js b/tools/ui/node_modules/open/index.js new file mode 100644 index 0000000000000000000000000000000000000000..43c060a0002c4b1cd6c5e5185ee7fdbab53b0d8d --- /dev/null +++ b/tools/ui/node_modules/open/index.js @@ -0,0 +1,366 @@ +import process from 'node:process'; +import {Buffer} from 'node:buffer'; +import path from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {promisify} from 'node:util'; +import childProcess from 'node:child_process'; +import fs, {constants as fsConstants} from 'node:fs/promises'; +import {isWsl, powerShellPath} from 'wsl-utils'; +import defineLazyProperty from 'define-lazy-prop'; +import defaultBrowser from 'default-browser'; +import isInsideContainer from 'is-inside-container'; + +const execFile = promisify(childProcess.execFile); + +// Path to included `xdg-open`. +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const localXdgOpenPath = path.join(__dirname, 'xdg-open'); + +const {platform, arch} = process; + +/** +Get the default browser name in Windows from WSL. + +@returns {Promise} Browser name. +*/ +async function getWindowsDefaultBrowserFromWsl() { + const powershellPath = await powerShellPath(); + const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`; + const encodedCommand = Buffer.from(rawCommand, 'utf16le').toString('base64'); + + const {stdout} = await execFile( + powershellPath, + [ + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-EncodedCommand', + encodedCommand, + ], + {encoding: 'utf8'}, + ); + + const progId = stdout.trim(); + + // Map ProgId to browser IDs + const browserMap = { + ChromeHTML: 'com.google.chrome', + BraveHTML: 'com.brave.Browser', + MSEdgeHTM: 'com.microsoft.edge', + FirefoxURL: 'org.mozilla.firefox', + }; + + return browserMap[progId] ? {id: browserMap[progId]} : {}; +} + +const pTryEach = async (array, mapper) => { + let latestError; + + for (const item of array) { + try { + return await mapper(item); // eslint-disable-line no-await-in-loop + } catch (error) { + latestError = error; + } + } + + throw latestError; +}; + +// eslint-disable-next-line complexity +const baseOpen = async options => { + options = { + wait: false, + background: false, + newInstance: false, + allowNonzeroExitCode: false, + ...options, + }; + + if (Array.isArray(options.app)) { + return pTryEach(options.app, singleApp => baseOpen({ + ...options, + app: singleApp, + })); + } + + let {name: app, arguments: appArguments = []} = options.app ?? {}; + appArguments = [...appArguments]; + + if (Array.isArray(app)) { + return pTryEach(app, appName => baseOpen({ + ...options, + app: { + name: appName, + arguments: appArguments, + }, + })); + } + + if (app === 'browser' || app === 'browserPrivate') { + // IDs from default-browser for macOS and windows are the same + const ids = { + 'com.google.chrome': 'chrome', + 'google-chrome.desktop': 'chrome', + 'com.brave.Browser': 'brave', + 'org.mozilla.firefox': 'firefox', + 'firefox.desktop': 'firefox', + 'com.microsoft.msedge': 'edge', + 'com.microsoft.edge': 'edge', + 'com.microsoft.edgemac': 'edge', + 'microsoft-edge.desktop': 'edge', + }; + + // Incognito flags for each browser in `apps`. + const flags = { + chrome: '--incognito', + brave: '--incognito', + firefox: '--private-window', + edge: '--inPrivate', + }; + + const browser = isWsl ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser(); + if (browser.id in ids) { + const browserName = ids[browser.id]; + + if (app === 'browserPrivate') { + appArguments.push(flags[browserName]); + } + + return baseOpen({ + ...options, + app: { + name: apps[browserName], + arguments: appArguments, + }, + }); + } + + throw new Error(`${browser.name} is not supported as a default browser`); + } + + let command; + const cliArguments = []; + const childProcessOptions = {}; + + if (platform === 'darwin') { + command = 'open'; + + if (options.wait) { + cliArguments.push('--wait-apps'); + } + + if (options.background) { + cliArguments.push('--background'); + } + + if (options.newInstance) { + cliArguments.push('--new'); + } + + if (app) { + cliArguments.push('-a', app); + } + } else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) { + command = await powerShellPath(); + + cliArguments.push( + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-EncodedCommand', + ); + + if (!isWsl) { + childProcessOptions.windowsVerbatimArguments = true; + } + + const encodedArguments = ['Start']; + + if (options.wait) { + encodedArguments.push('-Wait'); + } + + if (app) { + // Double quote with double quotes to ensure the inner quotes are passed through. + // Inner quotes are delimited for PowerShell interpretation with backticks. + encodedArguments.push(`"\`"${app}\`""`); + if (options.target) { + appArguments.push(options.target); + } + } else if (options.target) { + encodedArguments.push(`"${options.target}"`); + } + + if (appArguments.length > 0) { + appArguments = appArguments.map(argument => `"\`"${argument}\`""`); + encodedArguments.push('-ArgumentList', appArguments.join(',')); + } + + // Using Base64-encoded command, accepted by PowerShell, to allow special characters. + options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); + } else { + if (app) { + command = app; + } else { + // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. + const isBundled = !__dirname || __dirname === '/'; + + // Check if local `xdg-open` exists and is executable. + let exeLocalXdgOpen = false; + try { + await fs.access(localXdgOpenPath, fsConstants.X_OK); + exeLocalXdgOpen = true; + } catch {} + + const useSystemXdgOpen = process.versions.electron + ?? (platform === 'android' || isBundled || !exeLocalXdgOpen); + command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; + } + + if (appArguments.length > 0) { + cliArguments.push(...appArguments); + } + + if (!options.wait) { + // `xdg-open` will block the process unless stdio is ignored + // and it's detached from the parent even if it's unref'd. + childProcessOptions.stdio = 'ignore'; + childProcessOptions.detached = true; + } + } + + if (platform === 'darwin' && appArguments.length > 0) { + cliArguments.push('--args', ...appArguments); + } + + // This has to come after `--args`. + if (options.target) { + cliArguments.push(options.target); + } + + const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); + + if (options.wait) { + return new Promise((resolve, reject) => { + subprocess.once('error', reject); + + subprocess.once('close', exitCode => { + if (!options.allowNonzeroExitCode && exitCode > 0) { + reject(new Error(`Exited with code ${exitCode}`)); + return; + } + + resolve(subprocess); + }); + }); + } + + subprocess.unref(); + + return subprocess; +}; + +const open = (target, options) => { + if (typeof target !== 'string') { + throw new TypeError('Expected a `target`'); + } + + return baseOpen({ + ...options, + target, + }); +}; + +export const openApp = (name, options) => { + if (typeof name !== 'string' && !Array.isArray(name)) { + throw new TypeError('Expected a valid `name`'); + } + + const {arguments: appArguments = []} = options ?? {}; + if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) { + throw new TypeError('Expected `appArguments` as Array type'); + } + + return baseOpen({ + ...options, + app: { + name, + arguments: appArguments, + }, + }); +}; + +function detectArchBinary(binary) { + if (typeof binary === 'string' || Array.isArray(binary)) { + return binary; + } + + const {[arch]: archBinary} = binary; + + if (!archBinary) { + throw new Error(`${arch} is not supported`); + } + + return archBinary; +} + +function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { + if (wsl && isWsl) { + return detectArchBinary(wsl); + } + + if (!platformBinary) { + throw new Error(`${platform} is not supported`); + } + + return detectArchBinary(platformBinary); +} + +export const apps = {}; + +defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ + darwin: 'google chrome', + win32: 'chrome', + linux: ['google-chrome', 'google-chrome-stable', 'chromium'], +}, { + wsl: { + ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', + x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'], + }, +})); + +defineLazyProperty(apps, 'brave', () => detectPlatformBinary({ + darwin: 'brave browser', + win32: 'brave', + linux: ['brave-browser', 'brave'], +}, { + wsl: { + ia32: '/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe', + x64: ['/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe', '/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe'], + }, +})); + +defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ + darwin: 'firefox', + win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`, + linux: 'firefox', +}, { + wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe', +})); + +defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ + darwin: 'microsoft edge', + win32: 'msedge', + linux: ['microsoft-edge', 'microsoft-edge-dev'], +}, { + wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', +})); + +defineLazyProperty(apps, 'browser', () => 'browser'); + +defineLazyProperty(apps, 'browserPrivate', () => 'browserPrivate'); + +export default open; diff --git a/tools/ui/node_modules/open/license b/tools/ui/node_modules/open/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/tools/ui/node_modules/open/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/tools/ui/node_modules/open/package.json b/tools/ui/node_modules/open/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b80a4901f1d25497d95b3f05ef1cae66023f74e5 --- /dev/null +++ b/tools/ui/node_modules/open/package.json @@ -0,0 +1,68 @@ +{ + "name": "open", + "version": "10.2.0", + "description": "Open stuff like URLs, files, executables. Cross-platform.", + "license": "MIT", + "repository": "sindresorhus/open", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && tsd" + }, + "files": [ + "index.js", + "index.d.ts", + "xdg-open" + ], + "keywords": [ + "app", + "open", + "opener", + "opens", + "launch", + "start", + "xdg-open", + "xdg", + "default", + "cmd", + "browser", + "editor", + "executable", + "exe", + "url", + "urls", + "arguments", + "args", + "spawn", + "exec", + "child", + "process", + "website", + "file" + ], + "dependencies": { + "default-browser": "^5.2.1", + "define-lazy-prop": "^3.0.0", + "is-inside-container": "^1.0.0", + "wsl-utils": "^0.1.0" + }, + "devDependencies": { + "@types/node": "^20.10.5", + "ava": "^6.4.0", + "tsd": "^0.32.0", + "xo": "^1.1.1" + } +} diff --git a/tools/ui/node_modules/open/readme.md b/tools/ui/node_modules/open/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..e3bd3138b6c69ec5f74f0e6b7623139cc5ee303c --- /dev/null +++ b/tools/ui/node_modules/open/readme.md @@ -0,0 +1,183 @@ +# open + +> Open stuff like URLs, files, executables. Cross-platform. + +This is meant to be used in command-line tools and scripts, not in the browser. + +If you need this for Electron, use [`shell.openPath()`](https://www.electronjs.org/docs/api/shell#shellopenpathpath) instead. + +This package does not make any security guarantees. If you pass in untrusted input, it's up to you to properly sanitize it. + +#### Why? + +- Actively maintained. +- Supports app arguments. +- Safer as it uses `spawn` instead of `exec`. +- Fixes most of the original `node-open` issues. +- Includes the latest [`xdg-open` script](https://gitlab.freedesktop.org/xdg/xdg-utils/-/blob/master/scripts/xdg-open.in) for Linux. +- Supports WSL paths to Windows apps. + +## Install + +```sh +npm install open +``` + +**Warning:** This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) or use the [dynamic `import()`](https://v8.dev/features/dynamic-import) function. Please don't open issues for questions regarding CommonJS / ESM. + +## Usage + +```js +import open, {openApp, apps} from 'open'; + +// Opens the image in the default image viewer and waits for the opened app to quit. +await open('unicorn.png', {wait: true}); +console.log('The image viewer app quit'); + +// Opens the URL in the default browser. +await open('https://sindresorhus.com'); + +// Opens the URL in a specified browser. +await open('https://sindresorhus.com', {app: {name: 'firefox'}}); + +// Specify app arguments. +await open('https://sindresorhus.com', {app: {name: 'google chrome', arguments: ['--incognito']}}); + +// Opens the URL in the default browser in incognito mode. +await open('https://sindresorhus.com', {app: {name: apps.browserPrivate}}); + +// Open an app. +await openApp('xcode'); + +// Open an app with arguments. +await openApp(apps.chrome, {arguments: ['--incognito']}); +``` + +## API + +It uses the command `open` on macOS, `start` on Windows and `xdg-open` on other platforms. + +### open(target, options?) + +Returns a promise for the [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process. + +#### target + +Type: `string` + +The thing you want to open. Can be a URL, file, or executable. + +Opens in the default app for the file type. For example, URLs opens in your default browser. + +#### options + +Type: `object` + +##### wait + +Type: `boolean`\ +Default: `false` + +Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app. + +Note that it waits for the app to exit, not just for the window to close. + +On Windows, you have to explicitly specify an app for it to be able to wait. + +##### background (macOS only) + +Type: `boolean`\ +Default: `false` + +Do not bring the app to the foreground. + +##### newInstance (macOS only) + +Type: `boolean`\ +Default: `false` + +Open a new instance of the app even it's already running. + +A new instance is always opened on other platforms. + +##### app + +Type: `{name: string | string[], arguments?: string[]} | Array<{name: string | string[], arguments: string[]}>` + +Specify the `name` of the app to open the `target` with, and optionally, app `arguments`. `app` can be an array of apps to try to open and `name` can be an array of app names to try. If each app fails, the last error will be thrown. + +The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows. If possible, use [`apps`](#apps) which auto-detects the correct binary to use. + +You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome. + +The app `arguments` are app dependent. Check the app's documentation for what arguments it accepts. + +##### allowNonzeroExitCode + +Type: `boolean`\ +Default: `false` + +Allow the opened app to exit with nonzero exit code when the `wait` option is `true`. + +We do not recommend setting this option. The convention for success is exit code zero. + +### openApp(name, options?) + +Open an app. + +Returns a promise for the [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process. + +#### name + +Type: `string` + +The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows. If possible, use [`apps`](#apps) which auto-detects the correct binary to use. + +You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome. + +#### options + +Type: `object` + +Same options as [`open`](#options) except `app` and with the following additions: + +##### arguments + +Type: `string[]`\ +Default: `[]` + +Arguments passed to the app. + +These arguments are app dependent. Check the app's documentation for what arguments it accepts. + +### apps + +An object containing auto-detected binary names for common apps. Useful to work around [cross-platform differences](#app). + +```js +import open, {apps} from 'open'; + +await open('https://google.com', { + app: { + name: apps.chrome + } +}); +``` + +`browser` and `browserPrivate` can also be used to access the user's default browser through [`default-browser`](https://github.com/sindresorhus/default-browser). + +#### Supported apps + +- [`chrome`](https://www.google.com/chrome) - Web browser +- [`firefox`](https://www.mozilla.org/firefox) - Web browser +- [`edge`](https://www.microsoft.com/edge) - Web browser +- [`brave`](https://brave.com/) - Web browser +- `browser` - Default web browser +- `browserPrivate` - Default web browser in incognito mode + +`browser` and `browserPrivate` only supports `chrome`, `firefox`, `edge`, and `brave`. + +## Related + +- [open-cli](https://github.com/sindresorhus/open-cli) - CLI for this module +- [open-editor](https://github.com/sindresorhus/open-editor) - Open files in your editor at a specific line and column diff --git a/tools/ui/node_modules/open/xdg-open b/tools/ui/node_modules/open/xdg-open new file mode 100644 index 0000000000000000000000000000000000000000..e57e48634676450886f9840cc543fa8035a6cde9 --- /dev/null +++ b/tools/ui/node_modules/open/xdg-open @@ -0,0 +1,1267 @@ +#!/bin/sh +#--------------------------------------------- +# xdg-open +# +# Utility script to open a URL in the registered default application. +# +# Refer to the usage() function below for usage. +# +# Copyright 2009-2010, Fathi Boudra +# Copyright 2009-2016, Rex Dieter +# Copyright 2006, Kevin Krammer +# Copyright 2006, Jeremy White +# +# LICENSE: +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. +# +#--------------------------------------------- + +manualpage() +{ +cat << '_MANUALPAGE' +Name + + xdg-open -- opens a file or URL in the user's preferred + application + +Synopsis + + xdg-open { file | URL } + + xdg-open { --help | --manual | --version } + +Description + + xdg-open opens a file or URL in the user's preferred + application. If a URL is provided the URL will be opened in the + user's preferred web browser. If a file is provided the file + will be opened in the preferred application for files of that + type. xdg-open supports file, ftp, http and https URLs. + + xdg-open is for use inside a desktop session only. It is not + recommended to use xdg-open as root. + + As xdg-open can not handle arguments that begin with a "-" it + is recommended to pass filepaths in one of the following ways: + * Pass absolute paths, i.e. by using realpath as a + preprocessor. + * Prefix known relative filepaths with a "./". For example + using sed -E 's|^[^/]|./\0|'. + * Pass a file URL. + +Options + + --help + Show command synopsis. + + --manual + Show this manual page. + + --version + Show the xdg-utils version information. + +Exit Codes + + An exit code of 0 indicates success while a non-zero exit code + indicates failure. The following failure codes can be returned: + + 1 + Error in command line syntax. + + 2 + One of the files passed on the command line did not + exist. + + 3 + A required tool could not be found. + + 4 + The action failed. + + In case of success the process launched from the .desktop file + will not be forked off and therefore may result in xdg-open + running for a very long time. This behaviour intentionally + differs from most desktop specific openers to allow terminal + based applications to run using the same terminal xdg-open was + called from. + +Reporting Issues + + Please keep in mind xdg-open inherits most of the flaws of its + configuration and the underlying opener. + + In case the command xdg-mime query default "$(xdg-mime query + filetype path/to/troublesome_file)" names the program + responsible for any unexpected behaviour you can fix that by + setting a different handler. (If the program is broken let the + developers know) + + Also see the security note on xdg-mime(1) for the default + subcommand. + + If a flaw is reproducible using the desktop specific opener + (and isn't a configuration issue): Please report to whoever is + responsible for that first (reporting to xdg-utils is better + than not reporting at all, but since the xdg-utils are + maintained in very little spare time a fix will take much + longer) + + In case an issue specific to xdg-open please report it to + https://gitlab.freedesktop.org/xdg/xdg-utils/-/issues . + +See Also + + xdg-mime(1), xdg-settings(1), MIME applications associations + specification + +Examples + +xdg-open 'http://www.freedesktop.org/' + + Opens the freedesktop.org website in the user's default + browser. + +xdg-open /tmp/foobar.png + + Opens the PNG image file /tmp/foobar.png in the user's default + image viewing application. +_MANUALPAGE +} + +usage() +{ +cat << '_USAGE' + xdg-open -- opens a file or URL in the user's preferred + application + +Synopsis + + xdg-open { file | URL } + + xdg-open { --help | --manual | --version } + +_USAGE +} + +#@xdg-utils-common@ +#---------------------------------------------------------------------------- +# Common utility functions included in all XDG wrapper scripts +#---------------------------------------------------------------------------- + +#shellcheck shell=sh + +DEBUG() +{ + [ -z "${XDG_UTILS_DEBUG_LEVEL}" ] && return 0; + [ "${XDG_UTILS_DEBUG_LEVEL}" -lt "$1" ] && return 0; + shift + echo "$@" >&2 +} + +# This handles backslashes but not quote marks. +first_word() +{ + # shellcheck disable=SC2162 # No -r is intended here + read first rest + echo "$first" +} + +#------------------------------------------------------------- +# map a binary to a .desktop file +binary_to_desktop_file() +{ + search="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}" + binary="$(command -v "$1")" + binary="$(xdg_realpath "$binary")" + base="$(basename "$binary")" + IFS=: + for dir in $search; do + unset IFS + [ "$dir" ] || continue + [ -d "$dir/applications" ] || [ -d "$dir/applnk" ] || continue + for file in "$dir"/applications/*.desktop "$dir"/applications/*/*.desktop "$dir"/applnk/*.desktop "$dir"/applnk/*/*.desktop; do + [ -r "$file" ] || continue + # Check to make sure it's worth the processing. + grep -q "^Exec.*$base" "$file" || continue + # Make sure it's a visible desktop file (e.g. not "preferred-web-browser.desktop"). + grep -Eq "^(NoDisplay|Hidden)=true" "$file" && continue + command="$(grep -E "^Exec(\[[^]=]*])?=" "$file" | cut -d= -f 2- | first_word)" + command="$(command -v "$command")" + if [ x"$(xdg_realpath "$command")" = x"$binary" ]; then + # Fix any double slashes that got added path composition + echo "$file" | tr -s / + return + fi + done + done +} + +#------------------------------------------------------------- +# map a .desktop file to a binary +desktop_file_to_binary() +{ + search="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}" + desktop="$(basename "$1")" + IFS=: + for dir in $search; do + unset IFS + [ "$dir" ] && [ -d "$dir/applications" ] || [ -d "$dir/applnk" ] || continue + # Check if desktop file contains - + if [ "${desktop#*-}" != "$desktop" ]; then + vendor=${desktop%-*} + app=${desktop#*-} + if [ -r "$dir/applications/$vendor/$app" ]; then + file_path="$dir/applications/$vendor/$app" + elif [ -r "$dir/applnk/$vendor/$app" ]; then + file_path="$dir/applnk/$vendor/$app" + fi + fi + if test -z "$file_path" ; then + for indir in "$dir"/applications/ "$dir"/applications/*/ "$dir"/applnk/ "$dir"/applnk/*/; do + file="$indir/$desktop" + if [ -r "$file" ]; then + file_path=$file + break + fi + done + fi + if [ -r "$file_path" ]; then + # Remove any arguments (%F, %f, %U, %u, etc.). + command="$(grep -E "^Exec(\[[^]=]*])?=" "$file_path" | cut -d= -f 2- | first_word)" + command="$(command -v "$command")" + xdg_realpath "$command" + return + fi + done +} + +#------------------------------------------------------------- +# Exit script on successfully completing the desired operation + +# shellcheck disable=SC2120 # It is okay to call this without arguments +exit_success() +{ + if [ $# -gt 0 ]; then + echo "$*" + echo + fi + + exit 0 +} + + +#----------------------------------------- +# Exit script on malformed arguments, not enough arguments +# or missing required option. +# prints usage information + +exit_failure_syntax() +{ + if [ $# -gt 0 ]; then + echo "xdg-open: $*" >&2 + echo "Try 'xdg-open --help' for more information." >&2 + else + usage + echo "Use 'man xdg-open' or 'xdg-open --manual' for additional info." + fi + + exit 1 +} + +#------------------------------------------------------------- +# Exit script on missing file specified on command line + +exit_failure_file_missing() +{ + if [ $# -gt 0 ]; then + echo "xdg-open: $*" >&2 + fi + + exit 2 +} + +#------------------------------------------------------------- +# Exit script on failure to locate necessary tool applications + +exit_failure_operation_impossible() +{ + if [ $# -gt 0 ]; then + echo "xdg-open: $*" >&2 + fi + + exit 3 +} + +#------------------------------------------------------------- +# Exit script on failure returned by a tool application + +exit_failure_operation_failed() +{ + if [ $# -gt 0 ]; then + echo "xdg-open: $*" >&2 + fi + + exit 4 +} + +#------------------------------------------------------------ +# Exit script on insufficient permission to read a specified file + +exit_failure_file_permission_read() +{ + if [ $# -gt 0 ]; then + echo "xdg-open: $*" >&2 + fi + + exit 5 +} + +#------------------------------------------------------------ +# Exit script on insufficient permission to write a specified file + +exit_failure_file_permission_write() +{ + if [ $# -gt 0 ]; then + echo "xdg-open: $*" >&2 + fi + + exit 6 +} + +check_input_file() +{ + if [ ! -e "$1" ]; then + exit_failure_file_missing "file '$1' does not exist" + fi + if [ ! -r "$1" ]; then + exit_failure_file_permission_read "no permission to read file '$1'" + fi +} + +check_vendor_prefix() +{ + file_label="$2" + [ -n "$file_label" ] || file_label="filename" + file="$(basename "$1")" + case "$file" in + [[:alpha:]]*-*) + return + ;; + esac + + echo "xdg-open: $file_label '$file' does not have a proper vendor prefix" >&2 + echo 'A vendor prefix consists of alpha characters ([a-zA-Z]) and is terminated' >&2 + echo 'with a dash ("-"). An example '"$file_label"' is '"'example-$file'" >&2 + echo "Use --novendor to override or 'xdg-open --manual' for additional info." >&2 + exit 1 +} + +check_output_file() +{ + # if the file exists, check if it is writeable + # if it does not exists, check if we are allowed to write on the directory + if [ -e "$1" ]; then + if [ ! -w "$1" ]; then + exit_failure_file_permission_write "no permission to write to file '$1'" + fi + else + DIR="$(dirname "$1")" + if [ ! -w "$DIR" ] || [ ! -x "$DIR" ]; then + exit_failure_file_permission_write "no permission to create file '$1'" + fi + fi +} + +#---------------------------------------- +# Checks for shared commands, e.g. --help + +check_common_commands() +{ + while [ $# -gt 0 ] ; do + parm="$1" + shift + + case "$parm" in + --help) + usage + echo "Use 'man xdg-open' or 'xdg-open --manual' for additional info." + exit_success + ;; + + --manual) + manualpage + exit_success + ;; + + --version) + echo "xdg-open 1.2.1" + exit_success + ;; + + --) + [ -z "$XDG_UTILS_ENABLE_DOUBLE_HYPEN" ] || break + ;; + esac + done +} + +check_common_commands "$@" + +[ -z "${XDG_UTILS_DEBUG_LEVEL}" ] && unset XDG_UTILS_DEBUG_LEVEL; +# shellcheck disable=SC2034 +if [ "${XDG_UTILS_DEBUG_LEVEL-0}" -lt 1 ]; then + # Be silent + xdg_redirect_output=" > /dev/null 2> /dev/null" +else + # All output to stderr + xdg_redirect_output=" >&2" +fi + +#-------------------------------------- +# Checks for known desktop environments +# set variable DE to the desktop environments name, lowercase + +detectDE() +{ + # see https://bugs.freedesktop.org/show_bug.cgi?id=34164 + unset GREP_OPTIONS + + if [ -n "${XDG_CURRENT_DESKTOP}" ]; then + case "${XDG_CURRENT_DESKTOP}" in + # only recently added to menu-spec, pre-spec X- still in use + Cinnamon|X-Cinnamon) + DE=cinnamon; + ;; + ENLIGHTENMENT) + DE=enlightenment; + ;; + # GNOME, GNOME-Classic:GNOME, or GNOME-Flashback:GNOME + GNOME*) + DE=gnome; + ;; + KDE) + DE=kde; + ;; + DEEPIN|Deepin|deepin) + DE=deepin; + ;; + LXDE) + DE=lxde; + ;; + LXQt) + DE=lxqt; + ;; + MATE) + DE=mate; + ;; + XFCE) + DE=xfce + ;; + X-Generic) + DE=generic + ;; + esac + fi + + # shellcheck disable=SC2153 + if [ -z "$DE" ]; then + # classic fallbacks + if [ -n "$KDE_FULL_SESSION" ]; then DE=kde; + elif [ -n "$GNOME_DESKTOP_SESSION_ID" ]; then DE=gnome; + elif [ -n "$MATE_DESKTOP_SESSION_ID" ]; then DE=mate; + elif dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetNameOwner string:org.gnome.SessionManager > /dev/null 2>&1 ; then DE=gnome; + elif xprop -root _DT_SAVE_MODE 2> /dev/null | grep ' = \"xfce4\"$' >/dev/null 2>&1; then DE=xfce; + elif xprop -root 2> /dev/null | grep -i '^xfce_desktop_window' >/dev/null 2>&1; then DE=xfce + elif echo "$DESKTOP" | grep -q '^Enlightenment'; then DE=enlightenment; + elif [ -n "$LXQT_SESSION_CONFIG" ]; then DE=lxqt; + fi + fi + + if [ -z "$DE" ]; then + # fallback to checking $DESKTOP_SESSION + case "$DESKTOP_SESSION" in + gnome) + DE=gnome; + ;; + LXDE|Lubuntu) + DE=lxde; + ;; + MATE) + DE=mate; + ;; + xfce|xfce4|'Xfce Session') + DE=xfce; + ;; + esac + fi + + if [ -z "$DE" ]; then + # fallback to uname output for other platforms + case "$(uname 2>/dev/null)" in + CYGWIN*) + DE=cygwin; + ;; + Darwin) + DE=darwin; + ;; + Linux) + grep -q microsoft /proc/version > /dev/null 2>&1 && \ + command -v explorer.exe > /dev/null 2>&1 && \ + DE=wsl; + ;; + esac + fi + + if [ x"$DE" = x"gnome" ]; then + # gnome-default-applications-properties is only available in GNOME 2.x + # but not in GNOME 3.x + command -v gnome-default-applications-properties > /dev/null || DE="gnome3" + fi + + if [ -f "$XDG_RUNTIME_DIR/flatpak-info" ]; then + DE="flatpak" + fi +} + +#---------------------------------------------------------------------------- +# kfmclient exec/openURL can give bogus exit value in KDE <= 3.5.4 +# It also always returns 1 in KDE 3.4 and earlier +# Simply return 0 in such case + +kfmclient_fix_exit_code() +{ + version="$(LC_ALL=C.UTF-8 kde-config --version 2>/dev/null | grep '^KDE')" + major="$(echo "$version" | sed 's/KDE.*: \([0-9]\).*/\1/')" + minor="$(echo "$version" | sed 's/KDE.*: [0-9]*\.\([0-9]\).*/\1/')" + release="$(echo "$version" | sed 's/KDE.*: [0-9]*\.[0-9]*\.\([0-9]\).*/\1/')" + test "$major" -gt 3 && return "$1" + test "$minor" -gt 5 && return "$1" + test "$release" -gt 4 && return "$1" + return 0 +} + +#---------------------------------------------------------------------------- +# Returns true if there is a graphical display attached. + +has_display() +{ + if [ -n "$DISPLAY" ] || [ -n "$WAYLAND_DISPLAY" ]; then + return 0 + else + return 1 + fi +} + +#---------------------------------------------------------------------------- +# Prefixes a path with a "./" if it starts with a "-". +# This is useful for programs to not confuse paths with options. + +unoption_path() +{ + case "$1" in + -*) + printf "./%s" "$1" ;; + *) + printf "%s" "$1" ;; + esac +} + +#---------------------------------------------------------------------------- +# Performs a symlink and relative path resolving for a single argument. +# This will always fail if the given file does not exist! + +xdg_realpath() +{ + # allow caching and external configuration + if [ -z "$XDG_UTILS_REALPATH_BACKEND" ] ; then + if command -v realpath >/dev/null 2>/dev/null ; then + lines="$(realpath -- / 2>&1)" + if [ $? = 0 ] && [ "$lines" = "/" ] ; then + XDG_UTILS_REALPATH_BACKEND="realpath" + else + # The realpath took the -- literally, probably the busybox implementation + XDG_UTILS_REALPATH_BACKEND="busybox-realpath" + fi + unset lines + elif command -v readlink >/dev/null 2>/dev/null ; then + XDG_UTILS_REALPATH_BACKEND="readlink" + else + exit_failure_operation_failed "No usable realpath backend found. Have a realpath binary or a readlink -f that canonicalizes paths." + fi + fi + # Always fail if the file doesn't exist (busybox realpath does that for example) + [ -e "$1" ] || return 1 + case "$XDG_UTILS_REALPATH_BACKEND" in + realpath) + realpath -- "$1" + ;; + busybox-realpath) + # busybox style realpath implementations have options too + realpath "$(unoption_path "$1")" + ;; + readlink) + readlink -f "$(unoption_path "$1")" + ;; + *) + exit_failure_operation_impossible "Realpath backend '$XDG_UTILS_REALPATH_BACKEND' not recognized." + ;; + esac +} + +# This handles backslashes but not quote marks. +last_word() +{ + # Backslash handling is intended, not using `first` too + # shellcheck disable=SC2162,SC2034 + read first rest + echo "$rest" +} + +# Get the value of a key in a desktop file's Desktop Entry group. +# Example: Use get_key foo.desktop Exec +# to get the values of the Exec= key for the Desktop Entry group. +get_key() +{ + local file="${1}" + local key="${2}" + local desktop_entry="" + + IFS_="${IFS}" + IFS="" + # No backslash handling here, first_word and last_word do that + while read -r line + do + case "$line" in + "[Desktop Entry]") + desktop_entry="y" + ;; + # Reset match flag for other groups + "["*) + desktop_entry="" + ;; + "${key}="*) + # Only match Desktop Entry group + if [ -n "${desktop_entry}" ] + then + echo "${line}" | cut -d= -f 2- + fi + esac + done < "${file}" + IFS="${IFS_}" +} + +has_url_scheme() +{ + echo "$1" | LC_ALL=C grep -Eq '^[[:alpha:]][[:alpha:][:digit:]+\.\-]*:' +} + +# Returns true if argument is a file:// URL or path +is_file_url_or_path() +{ + if echo "$1" | grep -q '^file://' || ! has_url_scheme "$1" ; then + return 0 + else + return 1 + fi +} + +get_hostname() { + if [ -z "$HOSTNAME" ]; then + if command -v hostname > /dev/null; then + HOSTNAME=$(hostname) + else + HOSTNAME=$(uname -n) + fi + fi +} + +# If argument is a file URL, convert it to a (percent-decoded) path. +# If not, leave it as it is. +file_url_to_path() +{ + local file="$1" + get_hostname + if echo "$file" | grep -q '^file://'; then + file=${file#file://localhost} + file=${file#file://"$HOSTNAME"} + file=${file#file://} + if ! echo "$file" | grep -q '^/'; then + echo "$file" + return + fi + file=${file%%#*} + file=${file%%\?*} + local printf=printf + if [ -x /usr/bin/printf ]; then + printf=/usr/bin/printf + fi + file=$($printf "$(echo "$file" | sed -e 's@%\([a-f0-9A-F]\{2\}\)@\\x\1@g')") + fi + echo "$file" +} + +open_cygwin() +{ + cygstart "$1" + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_darwin() +{ + open "$1" + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_kde() +{ + if [ -n "${KDE_SESSION_VERSION}" ]; then + case "${KDE_SESSION_VERSION}" in + 4) + kde-open "$1" + ;; + 5) + "kde-open${KDE_SESSION_VERSION}" "$1" + ;; + 6) + kde-open "$1" + ;; + esac + else + kfmclient exec "$1" + kfmclient_fix_exit_code $? + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_deepin() +{ + if dde-open -version >/dev/null 2>&1; then + dde-open "$1" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_gnome3() +{ + if gio help open 2>/dev/null 1>&2; then + gio open "$1" + elif gvfs-open --help 2>/dev/null 1>&2; then + gvfs-open "$1" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_gnome() +{ + if gio help open 2>/dev/null 1>&2; then + gio open "$1" + elif gvfs-open --help 2>/dev/null 1>&2; then + gvfs-open "$1" + elif gnome-open --help 2>/dev/null 1>&2; then + gnome-open "$1" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_mate() +{ + if gio help open 2>/dev/null 1>&2; then + gio open "$1" + elif gvfs-open --help 2>/dev/null 1>&2; then + gvfs-open "$1" + elif mate-open --help 2>/dev/null 1>&2; then + mate-open "$1" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_xfce() +{ + if exo-open --help 2>/dev/null 1>&2; then + exo-open "$1" + elif gio help open 2>/dev/null 1>&2; then + gio open "$1" + elif gvfs-open --help 2>/dev/null 1>&2; then + gvfs-open "$1" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_enlightenment() +{ + if enlightenment_open --help 2>/dev/null 1>&2; then + enlightenment_open "$1" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_flatpak() +{ + if is_file_url_or_path "$1"; then + local file + file="$(file_url_to_path "$1")" + + check_input_file "$file" + + gdbus call --session \ + --dest org.freedesktop.portal.Desktop \ + --object-path /org/freedesktop/portal/desktop \ + --method org.freedesktop.portal.OpenURI.OpenFile \ + --timeout 5 \ + "" "3" {} 3< "$file" + else + # $1 contains an URI + + gdbus call --session \ + --dest org.freedesktop.portal.Desktop \ + --object-path /org/freedesktop/portal/desktop \ + --method org.freedesktop.portal.OpenURI.OpenURI \ + --timeout 5 \ + "" "$1" {} + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +#----------------------------------------- +# Recursively search .desktop file + +#(application, directory, target file, target_url) +search_desktop_file() +{ + local default="$1" + local dir="$2" + local target="$3" + local target_uri="$4" + + local file="" + # look for both vendor-app.desktop, vendor/app.desktop + if [ -r "$dir/$default" ]; then + file="$dir/$default" + elif [ -r "$dir/$(echo "$default" | sed -e 's|-|/|')" ]; then + file="$dir/$(echo "$default" | sed -e 's|-|/|')" + fi + + if [ -r "$file" ] ; then + command="$(get_key "${file}" "Exec" | first_word)" + if command -v "$command" >/dev/null; then + icon="$(get_key "${file}" "Icon")" + # FIXME: Actually LC_MESSAGES should be used as described in + # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s04.html + localised_name="$(get_key "${file}" "Name")" + #shellcheck disable=SC2046 # Splitting is intentional here + set -- $(get_key "${file}" "Exec" | last_word) + # We need to replace any occurrence of "%f", "%F" and + # the like by the target file. We examine each + # argument and append the modified argument to the + # end then shift. + local args=$# + local replaced=0 + while [ $args -gt 0 ]; do + case $1 in + %[c]) + replaced=1 + arg="${localised_name}" + shift + set -- "$@" "$arg" + ;; + %[fF]) + # if there is only a target_url return, + # this application can't handle it. + [ -n "$target" ] || return + replaced=1 + arg="$target" + shift + set -- "$@" "$arg" + ;; + %[uU]) + replaced=1 + # When an URI is requested use it, + # otherwise fall back to the filepath. + arg="${target_uri:-$target}" + shift + set -- "$@" "$arg" + ;; + %[i]) + replaced=1 + shift + set -- "$@" "--icon" "$icon" + ;; + *) + arg="$1" + shift + set -- "$@" "$arg" + ;; + esac + args=$(( args - 1 )) + done + [ $replaced -eq 1 ] || set -- "$@" "${target:-$target_uri}" + env "$command" "$@" + exit_success + fi + fi + + for d in "$dir/"*/; do + [ -d "$d" ] && search_desktop_file "$default" "$d" "$target" "$target_uri" + done +} + +# (file (or empty), mimetype, optional url) +open_generic_xdg_mime() +{ + filetype="$2" + default="$(xdg-mime query default "$filetype")" + if [ -n "$default" ] ; then + xdg_user_dir="$XDG_DATA_HOME" + [ -n "$xdg_user_dir" ] || xdg_user_dir="$HOME/.local/share" + + xdg_system_dirs="$XDG_DATA_DIRS" + [ -n "$xdg_system_dirs" ] || xdg_system_dirs=/usr/local/share/:/usr/share/ + + search_dirs="$xdg_user_dir:$xdg_system_dirs" + DEBUG 3 "$search_dirs" + old_ifs="$IFS" + IFS=: + for x in $search_dirs ; do + IFS="$old_ifs" + search_desktop_file "$default" "$x/applications/" "$1" "$3" + done + fi +} + +open_generic_xdg_x_scheme_handler() +{ + scheme="$(echo "$1" | LC_ALL=C sed -n 's/\(^[[:alpha:]][[:alnum:]+\.-]*\):.*$/\1/p')" + if [ -n "$scheme" ]; then + filetype="x-scheme-handler/$scheme" + open_generic_xdg_mime "" "$filetype" "$1" + fi +} + +has_single_argument() +{ + test $# = 1 +} + +open_envvar() +{ + local oldifs="$IFS" + local browser + + IFS=":" + for browser in $BROWSER; do + IFS="$oldifs" + + if [ -z "$browser" ]; then + continue + fi + + if echo "$browser" | grep -q %s; then + # Avoid argument injection. + # See https://bugs.freedesktop.org/show_bug.cgi?id=103807 + # URIs don't have IFS characters spaces anyway. + # shellcheck disable=SC2086,SC2091,SC2059 + # All the scary things here are intentional + has_single_argument $1 && $(printf "$browser" "$1") + else + $browser "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + fi + done +} + +open_wsl() +{ + local win_path + if is_file_url_or_path "$1" ; then + win_path="$(file_url_to_path "$1")" + win_path="$(wslpath -aw "$win_path")" + [ $? -eq 0 ] || exit_failure_operation_failed + explorer.exe "${win_path}" + else + rundll32.exe url.dll,FileProtocolHandler "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_generic() +{ + if is_file_url_or_path "$1"; then + local file + file="$(file_url_to_path "$1")" + + check_input_file "$file" + + if has_display; then + filetype="$(xdg-mime query filetype "$file" | sed "s/;.*//")" + # passing a path a url is okay too, + # see desktop file specification for '%u' + open_generic_xdg_mime "$file" "$filetype" "$1" + fi + + if command -v run-mailcap >/dev/null; then + run-mailcap --action=view "$file" + if [ $? -eq 0 ]; then + exit_success + fi + fi + + if has_display && mimeopen -v 2>/dev/null 1>&2; then + mimeopen -L -n "$file" + if [ $? -eq 0 ]; then + exit_success + fi + fi + fi + + if has_display; then + open_generic_xdg_x_scheme_handler "$1" + fi + + if [ -n "$BROWSER" ]; then + open_envvar "$1" + fi + + # if BROWSER variable is not set, check some well known browsers instead + if [ x"$BROWSER" = x"" ]; then + BROWSER=www-browser:links2:elinks:links:lynx:w3m + if has_display; then + BROWSER=x-www-browser:firefox:iceweasel:seamonkey:mozilla:epiphany:konqueror:chromium:chromium-browser:google-chrome:$BROWSER + fi + fi + + open_envvar "$1" + + exit_failure_operation_impossible "no method available for opening '$1'" +} + +open_lxde() +{ + + # pcmanfm only knows how to handle file:// urls and filepaths, it seems. + if pcmanfm --help >/dev/null 2>&1 && is_file_url_or_path "$1"; then + local file + file="$(file_url_to_path "$1")" + + # handle relative paths + if ! echo "$file" | grep -q ^/; then + file="$(pwd)/$file" + fi + + pcmanfm "$file" + else + open_generic "$1" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +open_lxqt() +{ + if qtxdg-mat open --help 2>/dev/null 1>&2; then + qtxdg-mat open "$1" + else + exit_failure_operation_impossible "no method available for opening '$1'" + fi + + if [ $? -eq 0 ]; then + exit_success + else + exit_failure_operation_failed + fi +} + +[ x"$1" != x"" ] || exit_failure_syntax + +url= +while [ $# -gt 0 ] ; do + parm="$1" + shift + + case "$parm" in + -*) + exit_failure_syntax "unexpected option '$parm'" + ;; + + *) + if [ -n "$url" ] ; then + exit_failure_syntax "unexpected argument '$parm'" + fi + url="$parm" + ;; + esac +done + +if [ -z "${url}" ] ; then + exit_failure_syntax "file or URL argument missing" +fi + +detectDE + +if [ x"$DE" = x"" ]; then + DE=generic +fi + +DEBUG 2 "Selected DE $DE" + +# sanitize BROWSER (avoid calling ourselves in particular) +case "${BROWSER}" in + *:"xdg-open"|"xdg-open":*) + BROWSER="$(echo "$BROWSER" | sed -e 's|:xdg-open||g' -e 's|xdg-open:||g')" + ;; + "xdg-open") + BROWSER= + ;; +esac + +case "$DE" in + kde) + open_kde "$url" + ;; + + deepin) + open_deepin "$url" + ;; + + gnome3|cinnamon) + open_gnome3 "$url" + ;; + + gnome) + open_gnome "$url" + ;; + + mate) + open_mate "$url" + ;; + + xfce) + open_xfce "$url" + ;; + + lxde) + open_lxde "$url" + ;; + + lxqt) + open_lxqt "$url" + ;; + + enlightenment) + open_enlightenment "$url" + ;; + + cygwin) + open_cygwin "$url" + ;; + + darwin) + open_darwin "$url" + ;; + + flatpak) + open_flatpak "$url" + ;; + + wsl) + open_wsl "$url" + ;; + + generic) + open_generic "$url" + ;; + + *) + exit_failure_operation_impossible "no method available for opening '$url'" + ;; +esac diff --git a/tools/ui/node_modules/opener/LICENSE.txt b/tools/ui/node_modules/opener/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..f74bd1310f4e027b00ea2e0bd9b23be93ecc5b38 --- /dev/null +++ b/tools/ui/node_modules/opener/LICENSE.txt @@ -0,0 +1,47 @@ +Dual licensed under WTFPL and MIT: + +--- + +Copyright © 2012–2020 Domenic Denicola + +This work is free. You can redistribute it and/or modify it under the +terms of the Do What The Fuck You Want To Public License, Version 2, +as published by Sam Hocevar. See below for more details. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2004 Sam Hocevar + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. + +--- + +The MIT License (MIT) + +Copyright © 2012–2020 Domenic Denicola + +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. diff --git a/tools/ui/node_modules/opener/README.md b/tools/ui/node_modules/opener/README.md new file mode 100644 index 0000000000000000000000000000000000000000..51cc1a28c56d3b0949a353a27ae8345ccdcc56a7 --- /dev/null +++ b/tools/ui/node_modules/opener/README.md @@ -0,0 +1,54 @@ +# It Opens Stuff + +That is, in your desktop environment. This will make *actual windows pop up*, with stuff in them: + +```bash +npm install opener -g + +opener http://google.com +opener ./my-file.txt +opener firefox +opener npm run lint +``` + +Also if you want to use it programmatically you can do that too: + +```js +var opener = require("opener"); + +opener("http://google.com"); +opener("./my-file.txt"); +opener("firefox"); +opener("npm run lint"); +``` + +Plus, it returns the child process created, so you can do things like let your script exit while the window stays open: + +```js +var editor = opener("documentation.odt"); +editor.unref(); +// These other unrefs may be necessary if your OS's opener process +// exits before the process it started is complete. +editor.stdin.unref(); +editor.stdout.unref(); +editor.stderr.unref(); +``` + +## Use It for Good + +Like opening the user's browser with a test harness in your package's test script: + +```json +{ + "scripts": { + "test": "opener ./test/runner.html" + }, + "devDependencies": { + "opener": "*" + } +} +``` + +## Why + +Because Windows has `start`, Macs have `open`, and *nix has `xdg-open`. At least [according to some person on StackOverflow](http://stackoverflow.com/q/1480971/3191). And I like things that work on all three. Like Node.js. And Opener. diff --git a/tools/ui/node_modules/opener/bin/opener-bin.js b/tools/ui/node_modules/opener/bin/opener-bin.js new file mode 100644 index 0000000000000000000000000000000000000000..a051ea8f03f192c2a3e96a76fa53b474d817bbef --- /dev/null +++ b/tools/ui/node_modules/opener/bin/opener-bin.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node +"use strict"; + +var opener = require(".."); + +opener(process.argv.slice(2), function (error) { + if (error) { + throw error; + } +}); diff --git a/tools/ui/node_modules/opener/lib/opener.js b/tools/ui/node_modules/opener/lib/opener.js new file mode 100644 index 0000000000000000000000000000000000000000..08888c6bb8a2a76e0fded230c4129ae2604a742f --- /dev/null +++ b/tools/ui/node_modules/opener/lib/opener.js @@ -0,0 +1,66 @@ +"use strict"; +var childProcess = require("child_process"); +var os = require("os"); + +module.exports = function opener(args, options, callback) { + var platform = process.platform; + + // Attempt to detect Windows Subystem for Linux (WSL). WSL itself as Linux (which works in most cases), but in + // this specific case we need to treat it as actually being Windows. The "Windows-way" of opening things through + // cmd.exe works just fine here, whereas using xdg-open does not, since there is no X Windows in WSL. + if (platform === "linux" && os.release().indexOf("Microsoft") !== -1) { + platform = "win32"; + } + + // http://stackoverflow.com/q/1480971/3191, but see below for Windows. + var command; + switch (platform) { + case "win32": { + command = "cmd.exe"; + break; + } + case "darwin": { + command = "open"; + break; + } + default: { + command = "xdg-open"; + break; + } + } + + if (typeof args === "string") { + args = [args]; + } + + if (typeof options === "function") { + callback = options; + options = {}; + } + + if (options && typeof options === "object" && options.command) { + if (platform === "win32") { + // *always* use cmd on windows + args = [options.command].concat(args); + } else { + command = options.command; + } + } + + if (platform === "win32") { + // On Windows, we really want to use the "start" command. But, the rules regarding arguments with spaces, and + // escaping them with quotes, can get really arcane. So the easiest way to deal with this is to pass off the + // responsibility to "cmd /c", which has that logic built in. + // + // Furthermore, if "cmd /c" double-quoted the first parameter, then "start" will interpret it as a window title, + // so we need to add a dummy empty-string window title: http://stackoverflow.com/a/154090/3191 + // + // Additionally, on Windows ampersand and caret need to be escaped when passed to "start" + args = args.map(function (value) { + return value.replace(/[&^]/g, "^$&"); + }); + args = ["/c", "start", "\"\""].concat(args); + } + + return childProcess.execFile(command, args, options, callback); +}; diff --git a/tools/ui/node_modules/opener/package.json b/tools/ui/node_modules/opener/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0af377d15f72a132156d67220bb692c9aa16e827 --- /dev/null +++ b/tools/ui/node_modules/opener/package.json @@ -0,0 +1,20 @@ +{ + "name": "opener", + "description": "Opens stuff, like webpages and files and executables, cross-platform", + "version": "1.5.2", + "author": "Domenic Denicola (https://domenic.me/)", + "license": "(WTFPL OR MIT)", + "repository": "domenic/opener", + "main": "lib/opener.js", + "bin": "bin/opener-bin.js", + "files": [ + "lib/", + "bin/" + ], + "scripts": { + "lint": "eslint ." + }, + "devDependencies": { + "eslint": "^7.7.0" + } +} diff --git a/tools/ui/node_modules/optionator/CHANGELOG.md b/tools/ui/node_modules/optionator/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2928cc2ced55510e091a38d82516d3b97a196de0 --- /dev/null +++ b/tools/ui/node_modules/optionator/CHANGELOG.md @@ -0,0 +1,59 @@ +# 0.9.0 +- update dependencies, in particular `levn` and `type-check` - this could affect behaviour of argument parsing + +# 0.8.3 +- changes dependency from `wordwrap` to `word-wrap` due to license issue +- update dependencies + +# 0.8.2 +- fix bug #18 - detect missing value when flag is last item +- update dependencies + +# 0.8.1 +- update `fast-levenshtein` dependency + +# 0.8.0 +- update `levn` dependency - supplying a float value to an option with type `Int` now throws an error, instead of silently converting to an `Int` + +# 0.7.1 +- fix bug with use of `defaults` and `concatRepeatedArrays` or `mergeRepeatedObjects` + +# 0.7.0 +- added `concatrepeatedarrays` option: `oneValuePerFlag`, only allows one array value per flag +- added `typeAliases` option +- added `parseArgv` which takes an array and parses with the first two items sliced off +- changed enum help style +- bug fixes (#12) +- use of `concatRepeatedArrays` and `mergeRepeatedObjects` at the top level is deprecated, use it as either a per-option option, or set them in the `defaults` object to set them for all objects + +# 0.6.0 +- added `defaults` lib-option flag, allowing one to set default properties for all options +- added `concatRepeatedArrays` and `mergeRepeatedObjects` as option level properties, allowing you to turn this feature on for specific options only + +# 0.5.0 +- `Boolean` flags with `default: 'true'`, and no short aliases, will by default show the `--no` version in help + +# 0.4.0 +- add `mergeRepeatedObjects` setting + +# 0.3.0 +- add `concatRepeatedArrays` setting +- add `overrideRequired` option setting +- use just Levenshtein string compare algo rather than Levenshtein Damerau to due dependency license issue + +# 0.2.2 +- bug fixes + +# 0.2.1 +- improved interpolation +- added changelog + +# 0.2.0 +- add dependency checks to options - added `dependsOn` as an option property +- add interpolation for `prepend` and `append` text with new `generateHelp` option, `interpolate` + +# 0.1.1 +- update dependencies + +# 0.1.0 +- initial release diff --git a/tools/ui/node_modules/optionator/LICENSE b/tools/ui/node_modules/optionator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..525b11850e6f2cc73b10854d14a4532797ed0a07 --- /dev/null +++ b/tools/ui/node_modules/optionator/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) George Zahariev + +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. diff --git a/tools/ui/node_modules/optionator/README.md b/tools/ui/node_modules/optionator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9cd0bb43e2bbab62df993780ce433ebde012c28b --- /dev/null +++ b/tools/ui/node_modules/optionator/README.md @@ -0,0 +1,238 @@ +# Optionator + + +Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). + +For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). + +[About](#about) · [Usage](#usage) · [Settings Format](#settings-format) · [Argument Format](#argument-format) + +## Why? +The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. +With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). +If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. + + $ cmd --halp + Invalid option '--halp' - perhaps you meant '--help'? + + $ cmd --count str + Invalid value for option 'count' - expected type Int, received value: str. + +Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. + +## About +Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. + +MIT license. Version 0.9.4 + + npm install optionator + +For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). + +Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. + +## Usage +`require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. + +```js +var optionator = require('optionator')({ + prepend: 'Usage: cmd [options]', + append: 'Version 1.0.0', + options: [{ + option: 'help', + alias: 'h', + type: 'Boolean', + description: 'displays help' + }, { + option: 'count', + alias: 'c', + type: 'Int', + description: 'number of things', + example: 'cmd --count 2' + }] +}); + +var options = optionator.parseArgv(process.argv); +if (options.help) { + console.log(optionator.generateHelp()); +} +... +``` + +### parse(input, parseOptions) +`parse` processes the `input` according to your settings, and returns an object with the results. + +##### arguments +* input - `[String] | Object | String` - the input you wish to parse +* parseOptions - `{slice: Int}` - all options optional + - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) + +##### returns +`Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. + +##### example +```js +parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} +parse('--count 2 positional'); // {count: 2, _: ['positional']} +parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} +``` + +### parseArgv(input) +`parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. + +##### arguments +* input - `[String]` - the input you wish to parse + +##### returns +See "returns" section in "parse" + +##### example +```js +parseArgv(process.argv); +``` + +### generateHelp(helpOptions) +`generateHelp` produces help text based on your settings. + +##### arguments +* helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional + - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` + - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` + +##### returns +`String` - the generated help text + +##### example +```js +generateHelp(); /* +"Usage: cmd [options] positional + + -h, --help displays help + -c, --count Int number of things + +Version 1.0.0 +"*/ +``` + +### generateHelpForOption(optionName) +`generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. + +##### arguments +* optionName - `String` - the name of the option to display + +##### returns +`String` - the generated help text for the option + +##### example +```js +generateHelpForOption('count'); /* +"-c, --count Int +description: number of things +example: cmd --count 2 +"*/ +``` + +## Settings Format +When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: + + { + prepend: String, + append: String, + options: [{heading: String} | { + option: String, + alias: [String] | String, + type: String, + enum: [String], + default: String, + restPositional: Boolean, + required: Boolean, + overrideRequired: Boolean, + dependsOn: [String] | String, + concatRepeatedArrays: Boolean | (Boolean, Object), + mergeRepeatedObjects: Boolean, + description: String, + longDescription: String, + example: [String] | String + }], + helpStyle: { + aliasSeparator: String, + typeSeparator: String, + descriptionSeparator: String, + initialIndent: Int, + secondaryIndent: Int, + maxPadFactor: Number + }, + mutuallyExclusive: [[String | [String]]], + concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object + mergeRepeatedObjects: Boolean, // deprecated, set in defaults object + positionalAnywhere: Boolean, + typeAliases: Object, + defaults: Object + } + +All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. + +### Top Level Properties +* `prepend` is an optional string to be placed before the options in the help text +* `append` is an optional string to be placed after the options in the help text +* `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified +* `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text +* `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present +* `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property +* `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property +* `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` +* `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` +* `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property + +#### Heading Properties +* `heading` a required string, the name of the heading + +#### Option Properties +* `option` the required name of the option - use dash-case, without the leading dashes +* `alias` is an optional string or array of strings which specify any aliases for the option +* `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it +* `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` +* `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` +* `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument +* `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined +* `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags +* `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` + + You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. +* `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` +* `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set +* `description` is an optional string, which will be displayed next to the option in the help text +* `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used +* `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used + +#### Help Style Properties +* `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' +* `typeSeparator` is an optional string, separates the type from the names - default: ' ' +* `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' +* `initialIndent` is an optional int - the amount of indent for options - default: 2 +* `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 +* `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 + +## Argument Format +At the highest level there are two types of arguments: named, and positional. + +Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). + +There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. + +For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. + +You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. + +Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. + +Everything after an `--` is positional, even if it looks like a named argument. + +You may optionally use `=` to separate option names from values, for example: `--count=2`. + +If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. + +If duplicate named arguments are present, the last one will be taken. + +## Technical About +`optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. diff --git a/tools/ui/node_modules/optionator/lib/help.js b/tools/ui/node_modules/optionator/lib/help.js new file mode 100644 index 0000000000000000000000000000000000000000..59e6f9694c95847ad99da3a9c442790a56d2ee3a --- /dev/null +++ b/tools/ui/node_modules/optionator/lib/help.js @@ -0,0 +1,260 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var ref$, id, find, sort, min, max, map, unlines, nameToRaw, dasherize, naturalJoin, wordWrap, wordwrap, getPreText, setHelpStyleDefaults, generateHelpForOption, generateHelp; + ref$ = require('prelude-ls'), id = ref$.id, find = ref$.find, sort = ref$.sort, min = ref$.min, max = ref$.max, map = ref$.map, unlines = ref$.unlines; + ref$ = require('./util'), nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin; + wordWrap = require('word-wrap'); + wordwrap = function(a, b){ + var ref$, indent, width; + ref$ = b === undefined + ? ['', a - 1] + : [repeatString$(' ', a), b - a - 1], indent = ref$[0], width = ref$[1]; + return function(text){ + return wordWrap(text, { + indent: indent, + width: width, + trim: true + }); + }; + }; + getPreText = function(option, arg$, maxWidth){ + var mainName, shortNames, ref$, longNames, type, description, aliasSeparator, typeSeparator, initialIndent, names, namesString, namesStringLen, typeSeparatorString, typeSeparatorStringLen, wrap; + mainName = option.option, shortNames = (ref$ = option.shortNames) != null + ? ref$ + : [], longNames = (ref$ = option.longNames) != null + ? ref$ + : [], type = option.type, description = option.description; + aliasSeparator = arg$.aliasSeparator, typeSeparator = arg$.typeSeparator, initialIndent = arg$.initialIndent; + if (option.negateName) { + mainName = "no-" + mainName; + if (longNames) { + longNames = map(function(it){ + return "no-" + it; + }, longNames); + } + } + names = mainName.length === 1 + ? [mainName].concat(shortNames, longNames) + : shortNames.concat([mainName], longNames); + namesString = map(nameToRaw, names).join(aliasSeparator); + namesStringLen = namesString.length; + typeSeparatorString = mainName === 'NUM' ? '::' : typeSeparator; + typeSeparatorStringLen = typeSeparatorString.length; + if (maxWidth != null && !option.boolean && initialIndent + namesStringLen + typeSeparatorStringLen + type.length > maxWidth) { + wrap = wordwrap(initialIndent + namesStringLen + typeSeparatorStringLen, maxWidth); + return namesString + "" + typeSeparatorString + wrap(type).replace(/^\s+/, ''); + } else { + return namesString + "" + (option.boolean + ? '' + : typeSeparatorString + "" + type); + } + }; + setHelpStyleDefaults = function(helpStyle){ + helpStyle.aliasSeparator == null && (helpStyle.aliasSeparator = ', '); + helpStyle.typeSeparator == null && (helpStyle.typeSeparator = ' '); + helpStyle.descriptionSeparator == null && (helpStyle.descriptionSeparator = ' '); + helpStyle.initialIndent == null && (helpStyle.initialIndent = 2); + helpStyle.secondaryIndent == null && (helpStyle.secondaryIndent = 4); + helpStyle.maxPadFactor == null && (helpStyle.maxPadFactor = 1.5); + }; + generateHelpForOption = function(getOption, arg$){ + var stdout, helpStyle, ref$; + stdout = arg$.stdout, helpStyle = (ref$ = arg$.helpStyle) != null + ? ref$ + : {}; + setHelpStyleDefaults(helpStyle); + return function(optionName){ + var maxWidth, wrap, option, e, pre, defaultString, restPositionalString, description, fullDescription, that, preDescription, descriptionString, exampleString, examples, seperator; + maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null; + wrap = maxWidth ? wordwrap(maxWidth) : id; + try { + option = getOption(dasherize(optionName)); + } catch (e$) { + e = e$; + return e.message; + } + pre = getPreText(option, helpStyle); + defaultString = option['default'] && !option.negateName ? "\ndefault: " + option['default'] : ''; + restPositionalString = option.restPositional ? 'Everything after this option is considered a positional argument, even if it looks like an option.' : ''; + description = option.longDescription || option.description && sentencize(option.description); + fullDescription = description && restPositionalString + ? description + " " + restPositionalString + : (that = description || restPositionalString) ? that : ''; + preDescription = 'description:'; + descriptionString = !fullDescription + ? '' + : maxWidth && fullDescription.length - 1 - preDescription.length > maxWidth + ? "\n" + preDescription + "\n" + wrap(fullDescription) + : "\n" + preDescription + " " + fullDescription; + exampleString = (that = option.example) ? (examples = [].concat(that), examples.length > 1 + ? "\nexamples:\n" + unlines(examples) + : "\nexample: " + examples[0]) : ''; + seperator = defaultString || descriptionString || exampleString ? "\n" + repeatString$('=', pre.length) : ''; + return pre + "" + seperator + defaultString + descriptionString + exampleString; + }; + }; + generateHelp = function(arg$){ + var options, prepend, append, helpStyle, ref$, stdout, aliasSeparator, typeSeparator, descriptionSeparator, maxPadFactor, initialIndent, secondaryIndent; + options = arg$.options, prepend = arg$.prepend, append = arg$.append, helpStyle = (ref$ = arg$.helpStyle) != null + ? ref$ + : {}, stdout = arg$.stdout; + setHelpStyleDefaults(helpStyle); + aliasSeparator = helpStyle.aliasSeparator, typeSeparator = helpStyle.typeSeparator, descriptionSeparator = helpStyle.descriptionSeparator, maxPadFactor = helpStyle.maxPadFactor, initialIndent = helpStyle.initialIndent, secondaryIndent = helpStyle.secondaryIndent; + return function(arg$){ + var ref$, showHidden, interpolate, maxWidth, output, out, data, optionCount, totalPreLen, preLens, i$, len$, item, that, pre, descParts, desc, preLen, sortedPreLens, maxPreLen, preLenMean, x, padAmount, descSepLen, fullWrapCount, partialWrapCount, descLen, totalLen, initialSpace, wrapAllFull, i, wrap; + ref$ = arg$ != null + ? arg$ + : {}, showHidden = ref$.showHidden, interpolate = ref$.interpolate; + maxWidth = stdout != null && stdout.isTTY ? stdout.columns - 1 : null; + output = []; + out = function(it){ + return output.push(it != null ? it : ''); + }; + if (prepend) { + out(interpolate ? interp(prepend, interpolate) : prepend); + out(); + } + data = []; + optionCount = 0; + totalPreLen = 0; + preLens = []; + for (i$ = 0, len$ = (ref$ = options).length; i$ < len$; ++i$) { + item = ref$[i$]; + if (showHidden || !item.hidden) { + if (that = item.heading) { + data.push({ + type: 'heading', + value: that + }); + } else { + pre = getPreText(item, helpStyle, maxWidth); + descParts = []; + if ((that = item.description) != null) { + descParts.push(that); + } + if (that = item['enum']) { + descParts.push("either: " + naturalJoin(that)); + } + if (item['default'] && !item.negateName) { + descParts.push("default: " + item['default']); + } + desc = descParts.join(' - '); + data.push({ + type: 'option', + pre: pre, + desc: desc, + descLen: desc.length + }); + preLen = pre.length; + optionCount++; + totalPreLen += preLen; + preLens.push(preLen); + } + } + } + sortedPreLens = sort(preLens); + maxPreLen = sortedPreLens[sortedPreLens.length - 1]; + preLenMean = initialIndent + totalPreLen / optionCount; + x = optionCount > 2 ? min(preLenMean * maxPadFactor, maxPreLen) : maxPreLen; + for (i$ = sortedPreLens.length - 1; i$ >= 0; --i$) { + preLen = sortedPreLens[i$]; + if (preLen <= x) { + padAmount = preLen; + break; + } + } + descSepLen = descriptionSeparator.length; + if (maxWidth != null) { + fullWrapCount = 0; + partialWrapCount = 0; + for (i$ = 0, len$ = data.length; i$ < len$; ++i$) { + item = data[i$]; + if (item.type === 'option') { + pre = item.pre, desc = item.desc, descLen = item.descLen; + if (descLen === 0) { + item.wrap = 'none'; + } else { + preLen = max(padAmount, pre.length) + initialIndent + descSepLen; + totalLen = preLen + descLen; + if (totalLen > maxWidth) { + if (descLen / 2.5 > maxWidth - preLen) { + fullWrapCount++; + item.wrap = 'full'; + } else { + partialWrapCount++; + item.wrap = 'partial'; + } + } else { + item.wrap = 'none'; + } + } + } + } + } + initialSpace = repeatString$(' ', initialIndent); + wrapAllFull = optionCount > 1 && fullWrapCount + partialWrapCount * 0.5 > optionCount * 0.5; + for (i$ = 0, len$ = data.length; i$ < len$; ++i$) { + i = i$; + item = data[i$]; + if (item.type === 'heading') { + if (i !== 0) { + out(); + } + out(item.value + ":"); + } else { + pre = item.pre, desc = item.desc, descLen = item.descLen, wrap = item.wrap; + if (maxWidth != null) { + if (wrapAllFull || wrap === 'full') { + wrap = wordwrap(initialIndent + secondaryIndent, maxWidth); + out(initialSpace + "" + pre + "\n" + wrap(desc)); + continue; + } else if (wrap === 'partial') { + wrap = wordwrap(initialIndent + descSepLen + max(padAmount, pre.length), maxWidth); + out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + wrap(desc).replace(/^\s+/, '')); + continue; + } + } + if (descLen === 0) { + out(initialSpace + "" + pre); + } else { + out(initialSpace + "" + pad(pre, padAmount) + descriptionSeparator + desc); + } + } + } + if (append) { + out(); + out(interpolate ? interp(append, interpolate) : append); + } + return unlines(output); + }; + }; + function pad(str, num){ + var len, padAmount; + len = str.length; + padAmount = num - len; + return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0); + } + function sentencize(str){ + var first, rest, period; + first = str.charAt(0).toUpperCase(); + rest = str.slice(1); + period = /[\.!\?]$/.test(str) ? '' : '.'; + return first + "" + rest + period; + } + function interp(string, object){ + return string.replace(/{{([a-zA-Z$_][a-zA-Z$_0-9]*)}}/g, function(arg$, key){ + var ref$; + return (ref$ = object[key]) != null + ? ref$ + : "{{" + key + "}}"; + }); + } + module.exports = { + generateHelp: generateHelp, + generateHelpForOption: generateHelpForOption + }; + function repeatString$(str, n){ + for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str; + return r; + } +}).call(this); diff --git a/tools/ui/node_modules/optionator/lib/index.js b/tools/ui/node_modules/optionator/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..436b7cc929c99729bb462fa57d045766db56ce2e --- /dev/null +++ b/tools/ui/node_modules/optionator/lib/index.js @@ -0,0 +1,465 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice, arrayFrom$ = Array.from || function(x){return slice$.call(x);}; + VERSION = '0.9.4'; + ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize; + deepIs = require('deep-is'); + ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin; + ref$ = require('./help'), generateHelp = ref$.generateHelp, generateHelpForOption = ref$.generateHelpForOption; + ref$ = require('type-check'), parsedTypeCheck = ref$.parsedTypeCheck, parseType = ref$.parseType; + parseLevn = require('levn').parsedTypeParse; + camelizeKeys = function(obj){ + var key, value, resultObj$ = {}; + for (key in obj) { + value = obj[key]; + resultObj$[camelize(key)] = value; + } + return resultObj$; + }; + parseString = function(string){ + var assignOpt, regex, replaceRegex, result; + assignOpt = '--?[a-zA-Z][-a-z-A-Z0-9]*='; + regex = RegExp('(?:' + assignOpt + ')?(?:\'(?:\\\\\'|[^\'])+\'|"(?:\\\\"|[^"])+")|[^\'"\\s]+', 'g'); + replaceRegex = RegExp('^(' + assignOpt + ')?[\'"]([\\s\\S]*)[\'"]$'); + result = map(function(it){ + return it.replace(replaceRegex, '$1$2'); + }, string.match(regex) || []); + return result; + }; + main = function(libOptions){ + var opts, defaults, required, traverse, getOption, parse; + opts = {}; + defaults = {}; + required = []; + if (toString$.call(libOptions.stdout).slice(8, -1) === 'Undefined') { + libOptions.stdout = process.stdout; + } + libOptions.positionalAnywhere == null && (libOptions.positionalAnywhere = true); + libOptions.typeAliases == null && (libOptions.typeAliases = {}); + libOptions.defaults == null && (libOptions.defaults = {}); + if (libOptions.concatRepeatedArrays != null) { + libOptions.defaults.concatRepeatedArrays = libOptions.concatRepeatedArrays; + } + if (libOptions.mergeRepeatedObjects != null) { + libOptions.defaults.mergeRepeatedObjects = libOptions.mergeRepeatedObjects; + } + traverse = function(options){ + var i$, len$, option, name, k, ref$, v, type, that, e, parsedPossibilities, parsedType, j$, len1$, possibility, rawDependsType, dependsOpts, dependsType, cra, alias, shortNames, longNames; + if (toString$.call(options).slice(8, -1) !== 'Array') { + throw new Error('No options defined.'); + } + for (i$ = 0, len$ = options.length; i$ < len$; ++i$) { + option = options[i$]; + if (option.heading == null) { + name = option.option; + if (opts[name] != null) { + throw new Error("Option '" + name + "' already defined."); + } + for (k in ref$ = libOptions.defaults) { + v = ref$[k]; + option[k] == null && (option[k] = v); + } + if (option.type === 'Boolean') { + option.boolean == null && (option.boolean = true); + } + if (option.parsedType == null) { + if (!option.type) { + throw new Error("No type defined for option '" + name + "'."); + } + try { + type = (that = libOptions.typeAliases[option.type]) != null + ? that + : option.type; + option.parsedType = parseType(type); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing type '" + option.type + "': " + e.message); + } + } + if (option['default']) { + try { + defaults[name] = parseLevn(option.parsedType, option['default']); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing default value '" + option['default'] + "' for type '" + option.type + "': " + e.message); + } + } + if (option['enum'] && !option.parsedPossiblities) { + parsedPossibilities = []; + parsedType = option.parsedType; + for (j$ = 0, len1$ = (ref$ = option['enum']).length; j$ < len1$; ++j$) { + possibility = ref$[j$]; + try { + parsedPossibilities.push(parseLevn(parsedType, possibility)); + } catch (e$) { + e = e$; + throw new Error("Option '" + name + "': Error parsing enum value '" + possibility + "' for type '" + option.type + "': " + e.message); + } + } + option.parsedPossibilities = parsedPossibilities; + } + if (that = option.dependsOn) { + if (that.length) { + ref$ = [].concat(option.dependsOn), rawDependsType = ref$[0], dependsOpts = slice$.call(ref$, 1); + dependsType = rawDependsType.toLowerCase(); + if (dependsOpts.length) { + if (dependsType === 'and' || dependsType === 'or') { + option.dependsOn = [dependsType].concat(arrayFrom$(dependsOpts)); + } else { + throw new Error("Option '" + name + "': If you have more than one dependency, you must specify either 'and' or 'or'"); + } + } else { + if ((ref$ = dependsType.toLowerCase()) === 'and' || ref$ === 'or') { + option.dependsOn = null; + } else { + option.dependsOn = ['and', rawDependsType]; + } + } + } else { + option.dependsOn = null; + } + } + if (option.required) { + required.push(name); + } + opts[name] = option; + if (option.concatRepeatedArrays != null) { + cra = option.concatRepeatedArrays; + if ('Boolean' === toString$.call(cra).slice(8, -1)) { + option.concatRepeatedArrays = [cra, {}]; + } else if (cra.length === 1) { + option.concatRepeatedArrays = [cra[0], {}]; + } else if (cra.length !== 2) { + throw new Error("Invalid setting for concatRepeatedArrays"); + } + } + if (option.alias || option.aliases) { + if (name === 'NUM') { + throw new Error("-NUM option can't have aliases."); + } + if (option.alias) { + option.aliases == null && (option.aliases = [].concat(option.alias)); + } + for (j$ = 0, len1$ = (ref$ = option.aliases).length; j$ < len1$; ++j$) { + alias = ref$[j$]; + if (opts[alias] != null) { + throw new Error("Option '" + alias + "' already defined."); + } + opts[alias] = option; + } + ref$ = partition(fn$, option.aliases), shortNames = ref$[0], longNames = ref$[1]; + option.shortNames == null && (option.shortNames = shortNames); + option.longNames == null && (option.longNames = longNames); + } + if ((!option.aliases || option.shortNames.length === 0) && option.type === 'Boolean' && option['default'] === 'true') { + option.negateName = true; + } + } + } + function fn$(it){ + return it.length === 1; + } + }; + traverse(libOptions.options); + getOption = function(name){ + var opt, possiblyMeant; + opt = opts[name]; + if (opt == null) { + possiblyMeant = closestString(keys(opts), name); + throw new Error("Invalid option '" + nameToRaw(name) + "'" + (possiblyMeant ? " - perhaps you meant '" + nameToRaw(possiblyMeant) + "'?" : '.')); + } + return opt; + }; + parse = function(input, arg$){ + var slice, obj, positional, restPositional, overrideRequired, prop, setValue, setDefaults, checkRequired, mutuallyExclusiveError, checkMutuallyExclusive, checkDependency, checkDependencies, checkProp, args, key, value, option, ref$, i$, len$, arg, that, result, short, argName, usingAssign, val, flags, len, j$, len1$, i, flag, opt, name, valPrime, negated, noedName; + slice = (arg$ != null + ? arg$ + : {}).slice; + obj = {}; + positional = []; + restPositional = false; + overrideRequired = false; + prop = null; + setValue = function(name, value){ + var opt, val, cra, e, currentType; + opt = getOption(name); + if (opt.boolean) { + val = value; + } else { + try { + cra = opt.concatRepeatedArrays; + if (cra != null && cra[0] && cra[1].oneValuePerFlag && opt.parsedType.length === 1 && opt.parsedType[0].structure === 'array') { + val = [parseLevn(opt.parsedType[0].of, value)]; + } else { + val = parseLevn(opt.parsedType, value); + } + } catch (e$) { + e = e$; + throw new Error("Invalid value for option '" + name + "' - expected type " + opt.type + ", received value: " + value + "."); + } + if (opt['enum'] && !any(function(it){ + return deepIs(it, val); + }, opt.parsedPossibilities)) { + throw new Error("Option " + name + ": '" + val + "' not one of " + naturalJoin(opt['enum']) + "."); + } + } + currentType = toString$.call(obj[name]).slice(8, -1); + if (obj[name] != null) { + if (opt.concatRepeatedArrays != null && opt.concatRepeatedArrays[0] && currentType === 'Array') { + obj[name] = obj[name].concat(val); + } else if (opt.mergeRepeatedObjects && currentType === 'Object') { + import$(obj[name], val); + } else { + obj[name] = val; + } + } else { + obj[name] = val; + } + if (opt.restPositional) { + restPositional = true; + } + if (opt.overrideRequired) { + overrideRequired = true; + } + }; + setDefaults = function(){ + var name, ref$, value; + for (name in ref$ = defaults) { + value = ref$[name]; + if (obj[name] == null) { + obj[name] = value; + } + } + }; + checkRequired = function(){ + var i$, ref$, len$, name; + if (overrideRequired) { + return; + } + for (i$ = 0, len$ = (ref$ = required).length; i$ < len$; ++i$) { + name = ref$[i$]; + if (!obj[name]) { + throw new Error("Option " + nameToRaw(name) + " is required."); + } + } + }; + mutuallyExclusiveError = function(first, second){ + throw new Error("The options " + nameToRaw(first) + " and " + nameToRaw(second) + " are mutually exclusive - you cannot use them at the same time."); + }; + checkMutuallyExclusive = function(){ + var rules, i$, len$, rule, present, j$, len1$, element, k$, len2$, opt; + rules = libOptions.mutuallyExclusive; + if (!rules) { + return; + } + for (i$ = 0, len$ = rules.length; i$ < len$; ++i$) { + rule = rules[i$]; + present = null; + for (j$ = 0, len1$ = rule.length; j$ < len1$; ++j$) { + element = rule[j$]; + if (toString$.call(element).slice(8, -1) === 'Array') { + for (k$ = 0, len2$ = element.length; k$ < len2$; ++k$) { + opt = element[k$]; + if (opt in obj) { + if (present != null) { + mutuallyExclusiveError(present, opt); + } else { + present = opt; + break; + } + } + } + } else { + if (element in obj) { + if (present != null) { + mutuallyExclusiveError(present, element); + } else { + present = element; + } + } + } + } + } + }; + checkDependency = function(option){ + var dependsOn, type, targetOptionNames, i$, len$, targetOptionName, targetOption; + dependsOn = option.dependsOn; + if (!dependsOn || option.dependenciesMet) { + return true; + } + type = dependsOn[0], targetOptionNames = slice$.call(dependsOn, 1); + for (i$ = 0, len$ = targetOptionNames.length; i$ < len$; ++i$) { + targetOptionName = targetOptionNames[i$]; + targetOption = obj[targetOptionName]; + if (targetOption && checkDependency(targetOption)) { + if (type === 'or') { + return true; + } + } else if (type === 'and') { + throw new Error("The option '" + option.option + "' did not have its dependencies met."); + } + } + if (type === 'and') { + return true; + } else { + throw new Error("The option '" + option.option + "' did not meet any of its dependencies."); + } + }; + checkDependencies = function(){ + var name; + for (name in obj) { + checkDependency(opts[name]); + } + }; + checkProp = function(){ + if (prop) { + throw new Error("Value for '" + prop + "' of type '" + getOption(prop).type + "' required."); + } + }; + switch (toString$.call(input).slice(8, -1)) { + case 'String': + args = parseString(input.slice(slice != null ? slice : 0)); + break; + case 'Array': + args = input.slice(slice != null ? slice : 2); + break; + case 'Object': + obj = {}; + for (key in input) { + value = input[key]; + if (key !== '_') { + option = getOption(dasherize(key)); + if (parsedTypeCheck(option.parsedType, value)) { + obj[option.option] = value; + } else { + throw new Error("Option '" + option.option + "': Invalid type for '" + value + "' - expected type '" + option.type + "'."); + } + } + } + checkMutuallyExclusive(); + checkDependencies(); + setDefaults(); + checkRequired(); + return ref$ = camelizeKeys(obj), ref$._ = input._ || [], ref$; + default: + throw new Error("Invalid argument to 'parse': " + input + "."); + } + for (i$ = 0, len$ = args.length; i$ < len$; ++i$) { + arg = args[i$]; + if (arg === '--') { + restPositional = true; + } else if (restPositional) { + positional.push(arg); + } else { + if (that = arg.match(/^(--?)([a-zA-Z][-a-zA-Z0-9]*)(=)?(.*)?$/)) { + result = that; + checkProp(); + short = result[1].length === 1; + argName = result[2]; + usingAssign = result[3] != null; + val = result[4]; + if (usingAssign && val == null) { + throw new Error("No value for '" + argName + "' specified."); + } + if (short) { + flags = chars(argName); + len = flags.length; + for (j$ = 0, len1$ = flags.length; j$ < len1$; ++j$) { + i = j$; + flag = flags[j$]; + opt = getOption(flag); + name = opt.option; + if (restPositional) { + positional.push(flag); + } else if (i === len - 1) { + if (usingAssign) { + valPrime = opt.boolean ? parseLevn([{ + type: 'Boolean' + }], val) : val; + setValue(name, valPrime); + } else if (opt.boolean) { + setValue(name, true); + } else { + prop = name; + } + } else if (opt.boolean) { + setValue(name, true); + } else { + throw new Error("Can't set argument '" + flag + "' when not last flag in a group of short flags."); + } + } + } else { + negated = false; + if (that = argName.match(/^no-(.+)$/)) { + negated = true; + noedName = that[1]; + opt = getOption(noedName); + } else { + opt = getOption(argName); + } + name = opt.option; + if (opt.boolean) { + valPrime = usingAssign ? parseLevn([{ + type: 'Boolean' + }], val) : true; + if (negated) { + setValue(name, !valPrime); + } else { + setValue(name, valPrime); + } + } else { + if (negated) { + throw new Error("Only use 'no-' prefix for Boolean options, not with '" + noedName + "'."); + } + if (usingAssign) { + setValue(name, val); + } else { + prop = name; + } + } + } + } else if (that = arg.match(/^-([0-9]+(?:\.[0-9]+)?)$/)) { + opt = opts.NUM; + if (!opt) { + throw new Error('No -NUM option defined.'); + } + setValue(opt.option, that[1]); + } else { + if (prop) { + setValue(prop, arg); + prop = null; + } else { + positional.push(arg); + if (!libOptions.positionalAnywhere) { + restPositional = true; + } + } + } + } + } + checkProp(); + checkMutuallyExclusive(); + checkDependencies(); + setDefaults(); + checkRequired(); + return ref$ = camelizeKeys(obj), ref$._ = positional, ref$; + }; + return { + parse: parse, + parseArgv: function(it){ + return parse(it, { + slice: 2 + }); + }, + generateHelp: generateHelp(libOptions), + generateHelpForOption: generateHelpForOption(getOption, libOptions) + }; + }; + main.VERSION = VERSION; + module.exports = main; + function import$(obj, src){ + var own = {}.hasOwnProperty; + for (var key in src) if (own.call(src, key)) obj[key] = src[key]; + return obj; + } +}).call(this); diff --git a/tools/ui/node_modules/optionator/lib/util.js b/tools/ui/node_modules/optionator/lib/util.js new file mode 100644 index 0000000000000000000000000000000000000000..5bc0cbb69e66aab262d0c2f400c4588a49c0da55 --- /dev/null +++ b/tools/ui/node_modules/optionator/lib/util.js @@ -0,0 +1,54 @@ +// Generated by LiveScript 1.6.0 +(function(){ + var prelude, map, sortBy, fl, closestString, nameToRaw, dasherize, naturalJoin; + prelude = require('prelude-ls'), map = prelude.map, sortBy = prelude.sortBy; + fl = require('fast-levenshtein'); + closestString = function(possibilities, input){ + var distances, ref$, string, distance; + if (!possibilities.length) { + return; + } + distances = map(function(it){ + var ref$, longer, shorter; + ref$ = input.length > it.length + ? [input, it] + : [it, input], longer = ref$[0], shorter = ref$[1]; + return { + string: it, + distance: fl.get(longer, shorter) + }; + })( + possibilities); + ref$ = sortBy(function(it){ + return it.distance; + }, distances)[0], string = ref$.string, distance = ref$.distance; + return string; + }; + nameToRaw = function(name){ + if (name.length === 1 || name === 'NUM') { + return "-" + name; + } else { + return "--" + name; + } + }; + dasherize = function(string){ + if (/^[A-Z]/.test(string)) { + return string; + } else { + return prelude.dasherize(string); + } + }; + naturalJoin = function(array){ + if (array.length < 3) { + return array.join(' or '); + } else { + return array.slice(0, -1).join(', ') + ", or " + array[array.length - 1]; + } + }; + module.exports = { + closestString: closestString, + nameToRaw: nameToRaw, + dasherize: dasherize, + naturalJoin: naturalJoin + }; +}).call(this); diff --git a/tools/ui/node_modules/optionator/package.json b/tools/ui/node_modules/optionator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..72b21bab6ed10cda5d019f51c662faf695f2c801 --- /dev/null +++ b/tools/ui/node_modules/optionator/package.json @@ -0,0 +1,43 @@ +{ + "name": "optionator", + "version": "0.9.4", + "author": "George Zahariev ", + "description": "option parsing and help generation", + "homepage": "https://github.com/gkz/optionator", + "keywords": [ + "options", + "flags", + "option parsing", + "cli" + ], + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "main": "./lib/", + "bugs": "https://github.com/gkz/optionator/issues", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/gkz/optionator.git" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "prelude-ls": "^1.2.1", + "deep-is": "^0.1.3", + "word-wrap": "^1.2.5", + "type-check": "^0.4.0", + "levn": "^0.4.1", + "fast-levenshtein": "^2.0.6" + }, + "devDependencies": { + "livescript": "^1.6.0", + "mocha": "^10.4.0" + } +} diff --git a/tools/ui/node_modules/own-keys/.eslintrc b/tools/ui/node_modules/own-keys/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..a5b9db5cd1fa6067a6b506e2d4e74999aa3775cd --- /dev/null +++ b/tools/ui/node_modules/own-keys/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": "off", + "id-length": "off", + "max-lines-per-function": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/tools/ui/node_modules/own-keys/.github/FUNDING.yml b/tools/ui/node_modules/own-keys/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..174d3e1ec6da850935533be4e5e472ba3e02e2a8 --- /dev/null +++ b/tools/ui/node_modules/own-keys/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/own-keys +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tools/ui/node_modules/own-keys/.nycrc b/tools/ui/node_modules/own-keys/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/tools/ui/node_modules/own-keys/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/tools/ui/node_modules/own-keys/CHANGELOG.md b/tools/ui/node_modules/own-keys/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e27b88880b9291019b19591c63f3a64aab4ec401 --- /dev/null +++ b/tools/ui/node_modules/own-keys/CHANGELOG.md @@ -0,0 +1,23 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/own-keys/compare/v1.0.0...v1.0.1) - 2024-12-29 + +### Commits + +- [Tests] sort with a proper comparator [`4a65b56`](https://github.com/ljharb/own-keys/commit/4a65b569d10985032a0773806dcdec8866132baa) +- [Fix] fix function name when `Reflect.ownKeys` is absent [`5cf17cb`](https://github.com/ljharb/own-keys/commit/5cf17cb1c9adfa836a1ddc467da4da20973db2ae) + +## v1.0.0 - 2024-12-28 + +### Commits + +- Initial implementation, tests, readme, types [`870a06f`](https://github.com/ljharb/own-keys/commit/870a06f9d7a2a6ecee283319d9a7388f8fc1c811) +- Initial commit [`70323dc`](https://github.com/ljharb/own-keys/commit/70323dc09541b4ee80426acfc89762605d7fc7bf) +- npm init [`4a3ad06`](https://github.com/ljharb/own-keys/commit/4a3ad0659defe9a67541c198743bd7733d437725) +- [Tests] node 0.8 sorts object keys differently [`b449364`](https://github.com/ljharb/own-keys/commit/b4493649ead7441fd8e65ab4718acbd088ceac70) +- Only apps should have lockfiles [`a54acbf`](https://github.com/ljharb/own-keys/commit/a54acbf2c6b8ef320abf7493b7c88002c690f9c0) diff --git a/tools/ui/node_modules/own-keys/LICENSE b/tools/ui/node_modules/own-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f82f38963b0d282b529f64def2bcd40be3a9a947 --- /dev/null +++ b/tools/ui/node_modules/own-keys/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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. diff --git a/tools/ui/node_modules/own-keys/README.md b/tools/ui/node_modules/own-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b54eb91b3cbc07a75cc50682cc1a53ed1914ce33 --- /dev/null +++ b/tools/ui/node_modules/own-keys/README.md @@ -0,0 +1,45 @@ +# own-keys [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly get an object's own property keys (strings and symbols), including non-enumerables when possible. + +## Getting started + +```sh +npm install --save own-keys +``` + +## Usage/Examples + +```js +var ownKeys = require('own-keys'); +var assert = require('assert'); + +assert.deepEqual(ownKeys({ a: 1, b: 2 }), ['a', 'b']); +assert.deepEqual(ownKeys([1, 2, 3]), [0, 1, 2, 'length']); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/own-keys +[npm-version-svg]: https://versionbadg.es/ljharb/own-keys.svg +[deps-svg]: https://david-dm.org/ljharb/own-keys.svg +[deps-url]: https://david-dm.org/ljharb/own-keys +[dev-deps-svg]: https://david-dm.org/ljharb/own-keys/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/own-keys#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/own-keys.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/own-keys.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/own-keys.svg +[downloads-url]: https://npm-stat.com/charts.html?package=own-keys +[codecov-image]: https://codecov.io/gh/ljharb/own-keys/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/own-keys/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/own-keys +[actions-url]: https://github.com/ljharb/own-keys/actions diff --git a/tools/ui/node_modules/own-keys/index.d.ts b/tools/ui/node_modules/own-keys/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67b3fd269f230a7073f5caad08a6f9bac022766e --- /dev/null +++ b/tools/ui/node_modules/own-keys/index.d.ts @@ -0,0 +1,3 @@ +declare function ownKeys, V>(object: T): (keyof T)[]; + +export = ownKeys; diff --git a/tools/ui/node_modules/own-keys/index.js b/tools/ui/node_modules/own-keys/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e43ce7348ca682dca6a9d9458ffc319640dd0737 --- /dev/null +++ b/tools/ui/node_modules/own-keys/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var safePushApply = require('safe-push-apply'); + +var $ownKeys = GetIntrinsic('%Reflect.ownKeys%', true); +var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%', true); +var $gOPS = GetIntrinsic('%Object.getOwnPropertySymbols%', true); + +var keys = require('object-keys'); + +/** @type {import('.')} */ +module.exports = $ownKeys || function ownKeys(source) { + /** @type {(keyof typeof source)[]} */ + var sourceKeys = ($gOPN || keys)(source); + if ($gOPS) { + safePushApply(sourceKeys, $gOPS(source)); + } + return sourceKeys; +}; diff --git a/tools/ui/node_modules/own-keys/package.json b/tools/ui/node_modules/own-keys/package.json new file mode 100644 index 0000000000000000000000000000000000000000..915f1adc5314a5e9dfa2cd75ece3253d0b587d0e --- /dev/null +++ b/tools/ui/node_modules/own-keys/package.json @@ -0,0 +1,91 @@ +{ + "name": "own-keys", + "version": "1.0.1", + "description": "Robustly get an object's own property keys (strings and symbols), including non-enumerables when possible", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "tests-only": "nyc tape test", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production" + }, + "keywords": [ + "own", + "key", + "keys", + "propertykey", + "string", + "symbol", + "enumerable", + "non-enumerable", + "robust" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/own-keys.git" + }, + "bugs": { + "url": "https://github.com/ljharb/own-keys/issues" + }, + "homepage": "https://github.com/ljharb/own-keys#readme", + "dependencies": { + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.2", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/get-intrinsic": "^1.2.3", + "@types/isarray": "^2.0.3", + "@types/object-keys": "^1.0.3", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "has-property-descriptors": "^1.0.2", + "has-symbols": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/tools/ui/node_modules/own-keys/test/index.js b/tools/ui/node_modules/own-keys/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2e78c6e9918ecbc68c8f69a5b6ef78f7d5a26b49 --- /dev/null +++ b/tools/ui/node_modules/own-keys/test/index.js @@ -0,0 +1,72 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('has-symbols/shams')(); +var hasPropertyDescriptors = require('has-property-descriptors')(); + +var ownKeys = require('../'); + +/** @type {(a: PropertyKey, b: PropertyKey) => number} */ +function comparator(a, b) { + if (typeof a === 'string' && typeof b === 'string') { + return a.localeCompare(b); + } + if (typeof a === 'number' && typeof b === 'number') { + return a - b; + } + return typeof a === 'symbol' ? 1 : -1; +} + +test('ownKeys', function (t) { + t.equal(typeof ownKeys, 'function', 'is a function'); + t.equal( + ownKeys.length, + 1, + 'has a length of 1' + ); + + t.test('basics', function (st) { + var obj = { a: 1, b: 2 }; + if (hasPropertyDescriptors) { + Object.defineProperty(obj, 'c', { + configurable: true, + enumerable: false, + writable: true, + value: 3 + }); + } + + st.deepEqual( + ownKeys(obj).sort(comparator), + (hasPropertyDescriptors ? ['a', 'b', 'c'] : ['a', 'b']).sort(comparator), + 'includes non-enumerable properties' + ); + + st.end(); + }); + + t.test('symbols', { skip: !hasSymbols }, function (st) { + /** @type {Record} */ + var obj = { a: 1 }; + var sym = Symbol('b'); + obj[sym] = 2; + + var nonEnumSym = Symbol('c'); + Object.defineProperty(obj, nonEnumSym, { + configurable: true, + enumerable: false, + writable: true, + value: 3 + }); + + st.deepEqual( + ownKeys(obj).sort(comparator), + ['a', sym, nonEnumSym].sort(comparator), + 'works with symbols, both enum and non-enum' + ); + + st.end(); + }); + + t.end(); +}); diff --git a/tools/ui/node_modules/own-keys/tsconfig.json b/tools/ui/node_modules/own-keys/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..0ce1896d10cdec1dc2e6fc181a65fd41b7fc8208 --- /dev/null +++ b/tools/ui/node_modules/own-keys/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/tools/ui/node_modules/oxc-parser/LICENSE b/tools/ui/node_modules/oxc-parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..444bffc00e5190817c0092e5e6fde787102977d2 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2024-present VoidZero Inc. & Contributors +Copyright (c) 2023 Boshen + +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. diff --git a/tools/ui/node_modules/oxc-parser/README.md b/tools/ui/node_modules/oxc-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac5827691e4f4c723613717d05252a2f3a27ff9 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/README.md @@ -0,0 +1,167 @@ +# Oxc Parser + +See [usage instructions](https://oxc.rs/docs/guide/usage/parser). + +## Features + +### Supports WASM + +See https://stackblitz.com/edit/oxc-parser for usage example. + +### ESTree + +When parsing JS or JSX files, the AST returned is fully conformant with the +[ESTree standard](https://github.com/estree/estree), the same as produced by +[Acorn](https://npmx.dev/package/acorn). + +When parsing TypeScript, the AST conforms to [@typescript-eslint/typescript-estree](https://npmx.dev/package/@typescript-eslint/typescript-estree)'s TS-ESTree format. + +If you need all ASTs in the same with-TS-properties format, use the `astType: 'ts'` option. + +The only differences between Oxc's AST and ESTree / TS-ESTree are: + +- Support for Stage 3 [decorators](https://github.com/tc39/proposal-decorators). +- Support for Stage 3 ECMA features [`import defer`](https://github.com/tc39/proposal-defer-import-eval) + and [`import source`](https://github.com/tc39/proposal-source-phase-imports). +- In TS-ESTree AST, `import.defer(...)` and `import.source(...)` are represented as an `ImportExpression` + with `'defer'` or `'source'` in `phase` field (as in ESTree spec), where TS-ESLint represents these + as a `CallExpression` with `MetaProperty` as its `callee`. +- Addition of a non-standard `hashbang` field to `Program`. + +That aside, the AST should completely align with Acorn's ESTree AST or TS-ESLint's TS-ESTree. +Any deviation would be considered a bug. + +### AST Types + +[@oxc-project/types](https://npmx.dev/package/@oxc-project/types) can be used. For example: + +```typescript +import { Statement } from "@oxc-project/types"; +``` + +### Visitor + +An AST visitor is provided. See example below. + +This package also exports visitor keys which can be used with any other ESTree walker. + +```js +import { visitorKeys } from "oxc-parser"; +``` + +### Fast Mode + +By default, Oxc parser does not produce semantic errors where symbols and scopes are needed. + +To enable semantic errors, apply the option `showSemanticErrors: true`. + +For example, + +```js +let foo; +let foo; +``` + +Does not produce any errors when `showSemanticErrors` is `false`, which is the default behavior. + +Fast mode is best suited for parser plugins, where other parts of your build pipeline has already checked for errors. + +Please note that turning off fast mode ​incurs​ a small performance overhead. + +### Returns ESM information. + +It is likely that you are writing a parser plugin that requires ESM information. + +To avoid walking the AST again, Oxc Parser returns ESM information directly. + +This information can be used to rewrite import and exports with the help of [`magic-string`](https://npmx.dev/package/magic-string), +without any AST manipulations. + +```ts +export interface EcmaScriptModule { + /** + * Has ESM syntax. + * + * i.e. `import` and `export` statements, and `import.meta`. + * + * Dynamic imports `import('foo')` are ignored since they can be used in non-ESM files. + */ + hasModuleSyntax: boolean; + /** Import statements */ + staticImports: Array; + /** Export statements */ + staticExports: Array; + /** Dynamic import expressions */ + dynamicImports: Array; + /** Span positions of `import.meta` */ + importMetas: Array; +} +``` + +## API + +### Functions + +```typescript +// Synchronous parsing +parseSync(filename: string, sourceText: string, options?: ParserOptions): ParseResult + +// Asynchronous parsing +parse(filename: string, sourceText: string, options?: ParserOptions): Promise +``` + +Use `parseSync` for synchronous parsing. Use `parse` for asynchronous parsing, which can be beneficial in I/O-bound or concurrent scenarios, though it adds async overhead. + +### Example + +```javascript +import { parseSync, Visitor } from "oxc-parser"; + +const code = "const url: String = /* 🤨 */ import.meta.url;"; + +// File extension is used to determine which dialect to parse source as. +const filename = "test.tsx"; + +const result = parseSync(filename, code); +// Or use async version: const result = await parse(filename, code); + +// An array of errors, if any. +console.log(result.errors); + +// AST and comments. +console.log(result.program, result.comments); + +// ESM information - imports, exports, `import.meta`s. +console.log(result.module); + +// Visit the AST +const visitations = []; + +const visitor = new Visitor({ + VariableDeclaration(decl) { + visitations.push(`enter ${decl.kind}`); + }, + "VariableDeclaration:exit"(decl) { + visitations.push(`exit ${decl.kind}`); + }, + Identifier(ident) { + visitations.push(ident.name); + }, +}); + +visitor.visit(result.program); + +// Logs: [ 'enter const', 'url', 'String', 'import', 'meta', 'url', 'exit const' ] +console.log(visitations); +``` + +### Options + +All options are optional. + +- `lang`: `'js'` | `'jsx'` | `'ts'` | `'tsx'`. Set language of source. If omitted, language is deduced from file extension. +- `sourceType`: `'script'` | `'module'` | `'unambiguous'`. Set source type. Defaults to `'module'`. +- `astType`: `'js'` | `'ts'`. Set to `'ts'` if you want ASTs of plain JS/JSX files to contain TypeScript-specific properties. +- `range`: `true` | `false`. If `true`, AST nodes contain a `range` field. Defaults to `false`. +- `preserveParens`: `true` | `false`. If `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` and `TSParenthesizedType` AST nodes. Defaults to `true`. +- `showSemanticErrors`: `true` | `false`. If `true`, check file for semantic errors which parser does not otherwise emit e.g. `let x; let x;`. Has a small performance cost. Defaults to `false`. diff --git a/tools/ui/node_modules/oxc-parser/package.json b/tools/ui/node_modules/oxc-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6aab53c16adc5cfa3368bc5543188dcfca5792ab --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/package.json @@ -0,0 +1,151 @@ +{ + "name": "oxc-parser", + "version": "0.127.0", + "description": "Oxc Parser Node API", + "keywords": [ + "ast", + "estree", + "javascript", + "oxc", + "parser", + "typescript" + ], + "homepage": "https://oxc.rs/docs/guide/usage/parser", + "bugs": "https://github.com/oxc-project/oxc/issues", + "license": "MIT", + "author": "Boshen and oxc contributors", + "repository": { + "type": "git", + "url": "git+https://github.com/oxc-project/oxc.git", + "directory": "napi/parser" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "files": [ + "src-js/bindings.js", + "src-js/index.d.ts", + "src-js/index.js", + "src-js/wasm.js", + "src-js/webcontainer-fallback.cjs", + "src-js/wrap.js", + "src-js/generated/constants.js", + "src-js/raw-transfer/common.js", + "src-js/raw-transfer/eager.js", + "src-js/raw-transfer/lazy-common.js", + "src-js/raw-transfer/lazy.js", + "src-js/raw-transfer/node-array.js", + "src-js/raw-transfer/supported.js", + "src-js/raw-transfer/visitor.js", + "src-js/visit/index.js", + "src-js/visit/visitor.js", + "src-js/generated/deserialize/js.js", + "src-js/generated/deserialize/js_range.js", + "src-js/generated/deserialize/ts.js", + "src-js/generated/deserialize/ts_range.js", + "src-js/generated/lazy/constructors.js", + "src-js/generated/lazy/type_ids.js", + "src-js/generated/lazy/walk.js", + "src-js/generated/visit/keys.js", + "src-js/generated/visit/type_ids.js", + "src-js/generated/visit/visitor.d.ts", + "src-js/generated/visit/walk.js" + ], + "type": "module", + "main": "src-js/index.js", + "browser": "src-js/wasm.js", + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "dependencies": { + "@oxc-project/types": "^0.127.0" + }, + "devDependencies": { + "@codspeed/vitest-plugin": "^5.0.0", + "@napi-rs/cli": "3.6.2", + "@napi-rs/wasm-runtime": "1.1.3", + "@types/node": "24.1.0", + "@typescript-eslint/visitor-keys": "^8.54.0", + "@vitest/browser": "4.1.4", + "@vitest/browser-playwright": "4.1.4", + "esbuild": "^0.28.0", + "playwright": "^1.51.0", + "publint": "0.3.18", + "tinypool": "^2.0.0", + "vitest": "4.1.4" + }, + "napi": { + "binaryName": "parser", + "dtsHeaderFile": "src-js/header.d.ts", + "packageName": "@oxc-parser/binding", + "targets": [ + "aarch64-apple-darwin", + "aarch64-linux-android", + "aarch64-pc-windows-msvc", + "aarch64-unknown-linux-gnu", + "aarch64-unknown-linux-musl", + "aarch64-unknown-linux-ohos", + "armv7-linux-androideabi", + "armv7-unknown-linux-gnueabihf", + "armv7-unknown-linux-musleabihf", + "i686-pc-windows-msvc", + "powerpc64le-unknown-linux-gnu", + "riscv64gc-unknown-linux-gnu", + "riscv64gc-unknown-linux-musl", + "s390x-unknown-linux-gnu", + "wasm32-wasip1-threads", + "x86_64-apple-darwin", + "x86_64-pc-windows-msvc", + "x86_64-unknown-freebsd", + "x86_64-unknown-linux-gnu", + "x86_64-unknown-linux-musl" + ], + "wasm": { + "browser": { + "fs": false + } + } + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@oxc-parser/binding-darwin-arm64": "0.127.0", + "@oxc-parser/binding-android-arm64": "0.127.0", + "@oxc-parser/binding-win32-arm64-msvc": "0.127.0", + "@oxc-parser/binding-linux-arm64-gnu": "0.127.0", + "@oxc-parser/binding-linux-arm64-musl": "0.127.0", + "@oxc-parser/binding-openharmony-arm64": "0.127.0", + "@oxc-parser/binding-android-arm-eabi": "0.127.0", + "@oxc-parser/binding-linux-arm-gnueabihf": "0.127.0", + "@oxc-parser/binding-linux-arm-musleabihf": "0.127.0", + "@oxc-parser/binding-win32-ia32-msvc": "0.127.0", + "@oxc-parser/binding-linux-ppc64-gnu": "0.127.0", + "@oxc-parser/binding-linux-riscv64-gnu": "0.127.0", + "@oxc-parser/binding-linux-riscv64-musl": "0.127.0", + "@oxc-parser/binding-linux-s390x-gnu": "0.127.0", + "@oxc-parser/binding-wasm32-wasi": "0.127.0", + "@oxc-parser/binding-darwin-x64": "0.127.0", + "@oxc-parser/binding-win32-x64-msvc": "0.127.0", + "@oxc-parser/binding-freebsd-x64": "0.127.0", + "@oxc-parser/binding-linux-x64-gnu": "0.127.0", + "@oxc-parser/binding-linux-x64-musl": "0.127.0" + }, + "scripts": { + "build-dev": "napi build --esm --platform --js bindings.js --dts index.d.ts --output-dir src-js", + "build-test": "pnpm run build-dev --profile coverage", + "build": "pnpm run build-dev --features allocator --release", + "postbuild": "publint", + "postbuild-dev": "node scripts/patch.js", + "build-wasi": "napi build --target wasm32-wasip1-threads", + "build-wasm": "pnpm run build-wasm-dev --release", + "build-wasm-dev": "pnpm run build-dev --target wasm32-wasip1-threads", + "build-npm-dir": "rm -rf npm-dir && napi create-npm-dirs --npm-dir npm-dir && pnpm napi artifacts --npm-dir npm-dir --output-dir src-js", + "build-browser-bundle": "node scripts/build-browser-bundle.js", + "test": "pnpm run test-node run", + "test-node": "vitest --dir ./test", + "test-browser": "vitest -c vitest.config.browser.ts", + "bench": "vitest bench --run ./bench.bench.js" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/oxc-parser/src-js/bindings.js b/tools/ui/node_modules/oxc-parser/src-js/bindings.js new file mode 100644 index 0000000000000000000000000000000000000000..62a62496193a4ddb13160d2dab01addcd77f0eab --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/bindings.js @@ -0,0 +1,601 @@ +// prettier-ignore +/* eslint-disable */ +// @ts-nocheck +/* auto-generated by NAPI-RS */ + +import { createRequire } from 'node:module' +const require = createRequire(import.meta.url) +const __dirname = new URL('.', import.meta.url).pathname + +const { readFileSync } = require('node:fs') +let nativeBinding = null +const loadErrors = [] + +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} + +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') + +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (typeof process.report?.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return true + } + } + return false +} + +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./parser.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-android-arm64') + const bindingPackageVersion = require('@oxc-parser/binding-android-arm64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./parser.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-android-arm-eabi') + const bindingPackageVersion = require('@oxc-parser/binding-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if (process.config?.variables?.shlib_suffix === 'dll.a' || process.config?.variables?.node_target_type === 'shared_library') { + try { + return require('./parser.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-win32-x64-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./parser.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-win32-x64-msvc') + const bindingPackageVersion = require('@oxc-parser/binding-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./parser.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-win32-ia32-msvc') + const bindingPackageVersion = require('@oxc-parser/binding-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./parser.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-win32-arm64-msvc') + const bindingPackageVersion = require('@oxc-parser/binding-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./parser.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-darwin-universal') + const bindingPackageVersion = require('@oxc-parser/binding-darwin-universal/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./parser.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-darwin-x64') + const bindingPackageVersion = require('@oxc-parser/binding-darwin-x64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./parser.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-darwin-arm64') + const bindingPackageVersion = require('@oxc-parser/binding-darwin-arm64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./parser.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-freebsd-x64') + const bindingPackageVersion = require('@oxc-parser/binding-freebsd-x64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./parser.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-freebsd-arm64') + const bindingPackageVersion = require('@oxc-parser/binding-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./parser.linux-x64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-x64-musl') + const bindingPackageVersion = require('@oxc-parser/binding-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./parser.linux-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-x64-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm64') { + if (isMusl()) { + try { + return require('./parser.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-arm64-musl') + const bindingPackageVersion = require('@oxc-parser/binding-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./parser.linux-arm64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-arm64-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./parser.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-arm-musleabihf') + const bindingPackageVersion = require('@oxc-parser/binding-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./parser.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-arm-gnueabihf') + const bindingPackageVersion = require('@oxc-parser/binding-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./parser.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-loong64-musl') + const bindingPackageVersion = require('@oxc-parser/binding-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./parser.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-loong64-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./parser.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-riscv64-musl') + const bindingPackageVersion = require('@oxc-parser/binding-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./parser.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-riscv64-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./parser.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-ppc64-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./parser.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-linux-s390x-gnu') + const bindingPackageVersion = require('@oxc-parser/binding-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./parser.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-openharmony-arm64') + const bindingPackageVersion = require('@oxc-parser/binding-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./parser.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-openharmony-x64') + const bindingPackageVersion = require('@oxc-parser/binding-openharmony-x64/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./parser.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-parser/binding-openharmony-arm') + const bindingPackageVersion = require('@oxc-parser/binding-openharmony-arm/package.json').version + if (bindingPackageVersion !== '0.127.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 0.127.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +nativeBinding = requireNative() + +if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { + let wasiBinding = null + let wasiBindingError = null + try { + wasiBinding = require('./parser.wasi.cjs') + nativeBinding = wasiBinding + } catch (err) { + if (process.env.NAPI_RS_FORCE_WASI) { + wasiBindingError = err + } + } + if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { + try { + wasiBinding = require('@oxc-parser/binding-wasm32-wasi') + nativeBinding = wasiBinding + } catch (err) { + if (process.env.NAPI_RS_FORCE_WASI) { + if (!wasiBindingError) { + wasiBindingError = err + } else { + wasiBindingError.cause = err + } + loadErrors.push(err) + } + } + } + if (process.env.NAPI_RS_FORCE_WASI === 'error' && !wasiBinding) { + const error = new Error('WASI binding not found and NAPI_RS_FORCE_WASI is set to error') + error.cause = wasiBindingError + throw error + } +} + +if (!nativeBinding && globalThis.process?.versions?.["webcontainer"]) { + try { + nativeBinding = require('./webcontainer-fallback.cjs'); + } catch (err) { + loadErrors.push(err) + } +} + +if (!nativeBinding) { + if (loadErrors.length > 0) { + throw new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + { + cause: loadErrors.reduce((err, cur) => { + cur.cause = err + return cur + }), + }, + ) + } + throw new Error(`Failed to load native binding`) +} + +const { Severity, ParseResult, ExportExportNameKind, ExportImportNameKind, ExportLocalNameKind, ImportNameKind, parse, parseSync, rawTransferSupported } = nativeBinding +export { Severity } +export { ParseResult } +export { ExportExportNameKind } +export { ExportImportNameKind } +export { ExportLocalNameKind } +export { ImportNameKind } +export { parse } +export { parseSync } +export { rawTransferSupported } +const { getBufferOffset, parseRaw, parseRawSync } = nativeBinding +export { getBufferOffset, parseRaw, parseRawSync } diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/constants.js b/tools/ui/node_modules/oxc-parser/src-js/generated/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..321e08fd194975c66656b13a83a13e4715e4fe20 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/constants.js @@ -0,0 +1,95 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer.rs`. + +/** + * Total size of the transfer buffer in bytes (block size minus allocator metadata). + */ +export const BUFFER_SIZE = 2147483616; + +/** + * Required alignment of the transfer buffer (4 GiB). + */ +export const BUFFER_ALIGN = 4294967296; + +/** + * Size of the active data area in bytes (buffer size minus raw metadata and chunk footer). + */ +export const ACTIVE_SIZE = 2147483552; + +/** + * Byte offset of the data pointer within the buffer, divided by 4 (for `Int32Array` indexing). + */ +export const DATA_POINTER_POS_32 = 536870900; + +/** + * Byte offset of the `is_ts` flag within the buffer. + */ +export const IS_TS_FLAG_POS = 2147483612; + +/** + * Byte offset of the `is_jsx` flag within the buffer. + */ +export const IS_JSX_FLAG_POS = 2147483613; + +/** + * Byte offset of the `has_bom` flag within the buffer. + */ +export const HAS_BOM_FLAG_POS = 2147483614; + +/** + * Byte offset of the tokens offset within the buffer, divided by 4 (for `Int32Array` indexing). + */ +export const TOKENS_OFFSET_POS_32 = 536870901; + +/** + * Byte offset of the tokens length within the buffer, divided by 4 (for `Int32Array` indexing). + */ +export const TOKENS_LEN_POS_32 = 536870902; + +/** + * Byte offset of the `program` field, relative to start of `RawTransferData`. + */ +export const PROGRAM_OFFSET = 0; + +/** + * Byte offset of pointer to start of source text, relative to start of `Program`. + */ +export const SOURCE_START_OFFSET = 16; + +/** + * Byte offset of length of source text, relative to start of `Program`. + */ +export const SOURCE_LEN_OFFSET = 24; + +/** + * Byte offset of comments `Vec` pointer, relative to start of `Program`. + */ +export const COMMENTS_OFFSET = 32; + +/** + * Byte offset of comments `Vec` length, relative to start of `Program`. + */ +export const COMMENTS_LEN_OFFSET = 40; + +/** + * Size of `Comment` struct in bytes. + */ +export const COMMENT_SIZE = 16; + +/** + * Byte offset of `kind` field, relative to start of `Comment` struct. + */ +export const COMMENT_KIND_OFFSET = 12; + +/** + * Byte offset of the deserialized flag within each token/comment entry. + * + * Corresponds to `content` field of `Comment` struct, and unused bytes in `Token`. + * Initialized to 0 by Rust. JS side sets to 1 after deserialization. + */ +export const DESERIALIZED_FLAG_OFFSET = 15; + +/** + * Discriminant value for `CommentKind::Line`. + */ +export const COMMENT_LINE_KIND = 0; diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/js.js b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/js.js new file mode 100644 index 0000000000000000000000000000000000000000..261a5e2c53b0319c826f30c78462c0014fb77c05 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/js.js @@ -0,0 +1,5840 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer.rs`. + +let uint8, + int32, + float64, + sourceText, + sourceTextLatin, + sourceEndPos = 0, + firstNonAsciiPos = 0; + +const { fromCharCode } = String, + { utf8Slice, latin1Slice } = Buffer.prototype, + stringDecodeArrays = Array(65).fill(null); +for (let i = 0; i <= 64; i++) stringDecodeArrays[i] = Array(i).fill(0); + +export function deserialize(buffer, sourceText, sourceByteLen) { + sourceEndPos = sourceByteLen; + return deserializeWith(buffer, sourceText, sourceByteLen, deserializeRawTransferData); +} + +function deserializeWith(buffer, sourceTextInput, sourceByteLen, deserialize) { + uint8 = buffer; + int32 = buffer.int32; + float64 = buffer.float64; + sourceText = sourceTextInput; + if (sourceText.length === sourceByteLen) { + firstNonAsciiPos = sourceByteLen; + sourceTextLatin = sourceText; + } else { + let i = 0; + for (; i < sourceByteLen && uint8[i] < 128; i++); + firstNonAsciiPos = i; + sourceTextLatin = latin1Slice.call(uint8, 0, sourceByteLen); + } + let data = deserialize(int32[536870900]); + resetBuffer(); + return data; +} + +export function resetBuffer() { + // Clear buffer and source text strings to allow them to be garbage collected + uint8 = int32 = float64 = sourceText = sourceTextLatin = void 0; +} + +function deserializeProgram(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + program = { + type: "Program", + body: null, + sourceType: deserializeModuleKind(pos + 137), + hashbang: null, + start, + end, + }; + program.hashbang = deserializeOptionHashbang(pos + 56); + (program.body = deserializeVecDirective(pos + 88)).push(...deserializeVecStatement(pos + 112)); + return program; +} + +function deserializeExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Expression`); + } +} + +function deserializeIdentifierName(pos) { + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeIdentifierReference(pos) { + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeBindingIdentifier(pos) { + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeLabelIdentifier(pos) { + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeThisExpression(pos) { + return { + type: "ThisExpression", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeArrayExpression(pos) { + let node = { + type: "ArrayExpression", + elements: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.elements = deserializeVecArrayExpressionElement(pos + 16); + return node; +} + +function deserializeArrayExpressionElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + case 65: + return deserializeElision(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ArrayExpressionElement`); + } +} + +function deserializeElision(pos) { + return null; +} + +function deserializeObjectExpression(pos) { + let node = { + type: "ObjectExpression", + properties: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.properties = deserializeVecObjectPropertyKind(pos + 16); + return node; +} + +function deserializeObjectPropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxObjectProperty(pos + 8); + case 1: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ObjectPropertyKind`); + } +} + +function deserializeObjectProperty(pos) { + let node = { + type: "Property", + kind: deserializePropertyKind(pos + 12), + key: null, + value: null, + method: deserializeBool(pos + 13), + shorthand: deserializeBool(pos + 14), + computed: deserializeBool(pos + 15), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeExpression(pos + 32); + return node; +} + +function deserializePropertyKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxIdentifierName(pos + 8); + case 65: + return deserializeBoxPrivateIdentifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKey`); + } +} + +function deserializePropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return "init"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKind`); + } +} + +function deserializeTemplateLiteral(pos) { + let node = { + type: "TemplateLiteral", + quasis: null, + expressions: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.expressions = deserializeVecExpression(pos + 40); + return node; +} + +function deserializeTaggedTemplateExpression(pos) { + let node = { + type: "TaggedTemplateExpression", + tag: null, + quasi: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.tag = deserializeExpression(pos + 16); + node.quasi = deserializeTemplateLiteral(pos + 40); + return node; +} + +function deserializeTemplateElement(pos) { + let tail = deserializeBool(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + value = deserializeTemplateElementValue(pos + 16); + value.cooked !== null && + deserializeBool(pos + 13) && + (value.cooked = value.cooked.replace(/\uFFFD(.{4})/g, (_, hex) => + String.fromCodePoint(parseInt(hex, 16)), + )); + return { + type: "TemplateElement", + value, + tail, + start, + end, + }; +} + +function deserializeTemplateElementValue(pos) { + return { + raw: deserializeStr(pos), + cooked: deserializeOptionStr(pos + 16), + }; +} + +function deserializeComputedMemberExpression(pos) { + let node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: true, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeExpression(pos + 32); + return node; +} + +function deserializeStaticMemberExpression(pos) { + let node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializePrivateFieldExpression(pos) { + let node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializePrivateIdentifier(pos + 32); + return node; +} + +function deserializeCallExpression(pos) { + let node = { + type: "CallExpression", + callee: null, + arguments: null, + optional: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.callee = deserializeExpression(pos + 16); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeNewExpression(pos) { + let node = { + type: "NewExpression", + callee: null, + arguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.callee = deserializeExpression(pos + 16); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeMetaProperty(pos) { + let node = { + type: "MetaProperty", + meta: null, + property: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.meta = deserializeIdentifierName(pos + 16); + node.property = deserializeIdentifierName(pos + 48); + return node; +} + +function deserializeSpreadElement(pos) { + let node = { + type: "SpreadElement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeArgument(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Argument`); + } +} + +function deserializeUpdateExpression(pos) { + let node = { + type: "UpdateExpression", + operator: deserializeUpdateOperator(pos + 12), + prefix: deserializeBool(pos + 13), + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeSimpleAssignmentTarget(pos + 16); + return node; +} + +function deserializeUnaryExpression(pos) { + let node = { + type: "UnaryExpression", + operator: deserializeUnaryOperator(pos + 12), + argument: null, + prefix: true, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeBinaryExpression(pos) { + let node = { + type: "BinaryExpression", + left: null, + operator: deserializeBinaryOperator(pos + 12), + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializePrivateInExpression(pos) { + let node = { + type: "BinaryExpression", + left: null, + operator: "in", + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializePrivateIdentifier(pos + 16); + node.right = deserializeExpression(pos + 48); + return node; +} + +function deserializeLogicalExpression(pos) { + let node = { + type: "LogicalExpression", + left: null, + operator: deserializeLogicalOperator(pos + 12), + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeConditionalExpression(pos) { + let node = { + type: "ConditionalExpression", + test: null, + consequent: null, + alternate: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeExpression(pos + 32); + node.alternate = deserializeExpression(pos + 48); + return node; +} + +function deserializeAssignmentExpression(pos) { + let node = { + type: "AssignmentExpression", + operator: deserializeAssignmentOperator(pos + 12), + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTarget`); + } +} + +function deserializeSimpleAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for SimpleAssignmentTarget`); + } +} + +function deserializeArrayAssignmentTarget(pos) { + let node = { + type: "ArrayPattern", + elements: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + elements = deserializeVecOptionAssignmentTargetMaybeDefault(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeObjectAssignmentTarget(pos) { + let node = { + type: "ObjectPattern", + properties: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + properties = deserializeVecAssignmentTargetProperty(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeAssignmentTargetRest(pos) { + let node = { + type: "RestElement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeAssignmentTarget(pos + 16); + return node; +} + +function deserializeAssignmentTargetMaybeDefault(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxAssignmentTargetWithDefault(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetMaybeDefault`); + } +} + +function deserializeAssignmentTargetWithDefault(pos) { + let node = { + type: "AssignmentPattern", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTargetProperty(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxAssignmentTargetPropertyIdentifier(pos + 8); + case 1: + return deserializeBoxAssignmentTargetPropertyProperty(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetProperty`); + } +} + +function deserializeAssignmentTargetPropertyIdentifier(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: true, + computed: false, + start, + end, + }, + key = deserializeIdentifierReference(pos + 16), + value = { + type: "Identifier", + name: key.name, + start: key.start, + end: key.end, + }, + init = deserializeOptionExpression(pos + 48); + init !== null && + (value = { + type: "AssignmentPattern", + left: value, + right: init, + start, + end, + }); + node.key = key; + node.value = value; + return node; +} + +function deserializeAssignmentTargetPropertyProperty(pos) { + let node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: false, + computed: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeAssignmentTargetMaybeDefault(pos + 32); + return node; +} + +function deserializeSequenceExpression(pos) { + let node = { + type: "SequenceExpression", + expressions: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expressions = deserializeVecExpression(pos + 16); + return node; +} + +function deserializeSuper(pos) { + return { + type: "Super", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeAwaitExpression(pos) { + let node = { + type: "AwaitExpression", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeChainExpression(pos) { + let node = { + type: "ChainExpression", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeChainElement(pos + 16); + return node; +} + +function deserializeChainElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxCallExpression(pos + 8); + case 1: + return deserializeBoxTSNonNullExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ChainElement`); + } +} + +function deserializeParenthesizedExpression(pos) { + let node; + node = { + type: "ParenthesizedExpression", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeStatement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBlockStatement(pos + 8); + case 1: + return deserializeBoxBreakStatement(pos + 8); + case 2: + return deserializeBoxContinueStatement(pos + 8); + case 3: + return deserializeBoxDebuggerStatement(pos + 8); + case 4: + return deserializeBoxDoWhileStatement(pos + 8); + case 5: + return deserializeBoxEmptyStatement(pos + 8); + case 6: + return deserializeBoxExpressionStatement(pos + 8); + case 7: + return deserializeBoxForInStatement(pos + 8); + case 8: + return deserializeBoxForOfStatement(pos + 8); + case 9: + return deserializeBoxForStatement(pos + 8); + case 10: + return deserializeBoxIfStatement(pos + 8); + case 11: + return deserializeBoxLabeledStatement(pos + 8); + case 12: + return deserializeBoxReturnStatement(pos + 8); + case 13: + return deserializeBoxSwitchStatement(pos + 8); + case 14: + return deserializeBoxThrowStatement(pos + 8); + case 15: + return deserializeBoxTryStatement(pos + 8); + case 16: + return deserializeBoxWhileStatement(pos + 8); + case 17: + return deserializeBoxWithStatement(pos + 8); + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + case 64: + return deserializeBoxImportDeclaration(pos + 8); + case 65: + return deserializeBoxExportAllDeclaration(pos + 8); + case 66: + return deserializeBoxExportDefaultDeclaration(pos + 8); + case 67: + return deserializeBoxExportNamedDeclaration(pos + 8); + case 68: + return deserializeBoxTSExportAssignment(pos + 8); + case 69: + return deserializeBoxTSNamespaceExportDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Statement`); + } +} + +function deserializeDirective(pos) { + let node = { + type: "ExpressionStatement", + expression: null, + directive: deserializeStr(pos + 64), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeHashbang(pos) { + return { + type: "Hashbang", + value: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeBlockStatement(pos) { + let node = { + type: "BlockStatement", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeDeclaration(pos) { + switch (uint8[pos]) { + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Declaration`); + } +} + +function deserializeVariableDeclaration(pos) { + let node = { + type: "VariableDeclaration", + kind: deserializeVariableDeclarationKind(pos + 12), + declarations: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.declarations = deserializeVecVariableDeclarator(pos + 16); + return node; +} + +function deserializeVariableDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "var"; + case 1: + return "let"; + case 2: + return "const"; + case 3: + return "using"; + case 4: + return "await using"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for VariableDeclarationKind`); + } +} + +function deserializeVariableDeclarator(pos) { + let node = { + type: "VariableDeclarator", + id: null, + init: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingPattern(pos + 16); + node.init = deserializeOptionExpression(pos + 40); + return node; +} + +function deserializeEmptyStatement(pos) { + return { + type: "EmptyStatement", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeExpressionStatement(pos) { + let node = { + type: "ExpressionStatement", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeIfStatement(pos) { + let node = { + type: "IfStatement", + test: null, + consequent: null, + alternate: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeStatement(pos + 32); + node.alternate = deserializeOptionStatement(pos + 48); + return node; +} + +function deserializeDoWhileStatement(pos) { + let node = { + type: "DoWhileStatement", + body: null, + test: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeStatement(pos + 16); + node.test = deserializeExpression(pos + 32); + return node; +} + +function deserializeWhileStatement(pos) { + let node = { + type: "WhileStatement", + test: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeForStatement(pos) { + let node = { + type: "ForStatement", + init: null, + test: null, + update: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.init = deserializeOptionForStatementInit(pos + 16); + node.test = deserializeOptionExpression(pos + 32); + node.update = deserializeOptionExpression(pos + 48); + node.body = deserializeStatement(pos + 64); + return node; +} + +function deserializeForStatementInit(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxVariableDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementInit`); + } +} + +function deserializeForInStatement(pos) { + let node = { + type: "ForInStatement", + left: null, + right: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeForStatementLeft(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxVariableDeclaration(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementLeft`); + } +} + +function deserializeForOfStatement(pos) { + let node = { + type: "ForOfStatement", + await: deserializeBool(pos + 64), + left: null, + right: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeContinueStatement(pos) { + let node = { + type: "ContinueStatement", + label: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeBreakStatement(pos) { + let node = { + type: "BreakStatement", + label: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeReturnStatement(pos) { + let node = { + type: "ReturnStatement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeWithStatement(pos) { + let node = { + type: "WithStatement", + object: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeSwitchStatement(pos) { + let node = { + type: "SwitchStatement", + discriminant: null, + cases: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.discriminant = deserializeExpression(pos + 16); + node.cases = deserializeVecSwitchCase(pos + 32); + return node; +} + +function deserializeSwitchCase(pos) { + let node = { + type: "SwitchCase", + test: null, + consequent: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeOptionExpression(pos + 16); + node.consequent = deserializeVecStatement(pos + 32); + return node; +} + +function deserializeLabeledStatement(pos) { + let node = { + type: "LabeledStatement", + label: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeLabelIdentifier(pos + 16); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeThrowStatement(pos) { + let node = { + type: "ThrowStatement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeTryStatement(pos) { + let node = { + type: "TryStatement", + block: null, + handler: null, + finalizer: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.block = deserializeBoxBlockStatement(pos + 16); + node.handler = deserializeOptionBoxCatchClause(pos + 24); + node.finalizer = deserializeOptionBoxBlockStatement(pos + 32); + return node; +} + +function deserializeCatchClause(pos) { + let node = { + type: "CatchClause", + param: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.param = deserializeOptionCatchParameter(pos + 16); + node.body = deserializeBoxBlockStatement(pos + 56); + return node; +} + +function deserializeCatchParameter(pos) { + return deserializeBindingPattern(pos + 16); +} + +function deserializeDebuggerStatement(pos) { + return { + type: "DebuggerStatement", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeBindingPattern(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBindingIdentifier(pos + 8); + case 1: + return deserializeBoxObjectPattern(pos + 8); + case 2: + return deserializeBoxArrayPattern(pos + 8); + case 3: + return deserializeBoxAssignmentPattern(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BindingPattern`); + } +} + +function deserializeAssignmentPattern(pos) { + let node = { + type: "AssignmentPattern", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeBindingPattern(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeObjectPattern(pos) { + let node = { + type: "ObjectPattern", + properties: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + properties = deserializeVecBindingProperty(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeBindingProperty(pos) { + let node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: deserializeBool(pos + 12), + computed: deserializeBool(pos + 13), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeBindingPattern(pos + 32); + return node; +} + +function deserializeArrayPattern(pos) { + let node = { + type: "ArrayPattern", + elements: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + elements = deserializeVecOptionBindingPattern(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeBindingRestElement(pos) { + let node = { + type: "RestElement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeBindingPattern(pos + 16); + return node; +} + +function deserializeFunction(pos) { + let node = { + type: deserializeFunctionType(pos + 88), + id: null, + generator: deserializeBool(pos + 89), + async: deserializeBool(pos + 90), + params: null, + body: null, + expression: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 64); + node.id = deserializeOptionBindingIdentifier(pos + 16); + node.params = params; + node.body = deserializeOptionBoxFunctionBody(pos + 80); + return node; +} + +function deserializeFunctionType(pos) { + switch (uint8[pos]) { + case 0: + return "FunctionDeclaration"; + case 1: + return "FunctionExpression"; + case 2: + return "TSDeclareFunction"; + case 3: + return "TSEmptyBodyFunctionExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for FunctionType`); + } +} + +function deserializeFormalParameters(pos) { + let params = deserializeVecFormalParameter(pos + 16), + restFieldPos32 = (pos >> 2) + 10; + if (int32[restFieldPos32] !== 0 && int32[restFieldPos32 + 1] !== 0) { + pos = int32[restFieldPos32]; + let rest = { + type: "RestElement", + argument: null, + start: deserializeI32(pos + 40), + end: deserializeI32(pos + 44), + }; + rest.argument = deserializeBindingPattern(pos + 56); + params.push(rest); + } + return params; +} + +function deserializeFormalParameter(pos) { + let param, + initializerFieldPos32 = (pos >> 2) + 16; + if (int32[initializerFieldPos32] !== 0 && int32[initializerFieldPos32 + 1] !== 0) { + param = { + type: "AssignmentPattern", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + param.left = deserializeBindingPattern(pos + 40); + param.right = deserializeOptionBoxExpression(pos + 64); + } else param = deserializeBindingPattern(pos + 40); + return param; +} + +function deserializeFunctionBody(pos) { + let node = { + type: "BlockStatement", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeArrowFunctionExpression(pos) { + let expression = deserializeBool(pos + 48), + node = { + type: "ArrowFunctionExpression", + expression, + async: deserializeBool(pos + 49), + params: null, + body: null, + id: null, + generator: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + body = deserializeBoxFunctionBody(pos + 40); + expression === true && (body = body.body[0].expression); + node.params = deserializeBoxFormalParameters(pos + 24); + node.body = body; + return node; +} + +function deserializeYieldExpression(pos) { + let node = { + type: "YieldExpression", + delegate: deserializeBool(pos + 12), + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeClass(pos) { + let node = { + type: deserializeClassType(pos + 136), + decorators: null, + id: null, + superClass: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.id = deserializeOptionBindingIdentifier(pos + 40); + node.superClass = deserializeOptionExpression(pos + 80); + node.body = deserializeBoxClassBody(pos + 128); + return node; +} + +function deserializeClassType(pos) { + switch (uint8[pos]) { + case 0: + return "ClassDeclaration"; + case 1: + return "ClassExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassType`); + } +} + +function deserializeClassBody(pos) { + let node = { + type: "ClassBody", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecClassElement(pos + 16); + return node; +} + +function deserializeClassElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStaticBlock(pos + 8); + case 1: + return deserializeBoxMethodDefinition(pos + 8); + case 2: + return deserializeBoxPropertyDefinition(pos + 8); + case 3: + return deserializeBoxAccessorProperty(pos + 8); + case 4: + return deserializeBoxTSIndexSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassElement`); + } +} + +function deserializeMethodDefinition(pos) { + let node = { + type: deserializeMethodDefinitionType(pos + 12), + decorators: null, + key: null, + value: null, + kind: deserializeMethodDefinitionKind(pos + 13), + computed: deserializeBool(pos + 14), + static: deserializeBool(pos + 15), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeBoxFunction(pos + 56); + return node; +} + +function deserializeMethodDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "MethodDefinition"; + case 1: + return "TSAbstractMethodDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionType`); + } +} + +function deserializePropertyDefinition(pos) { + let node = { + type: deserializePropertyDefinitionType(pos + 12), + decorators: null, + key: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializePropertyDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "PropertyDefinition"; + case 1: + return "TSAbstractPropertyDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyDefinitionType`); + } +} + +function deserializeMethodDefinitionKind(pos) { + switch (uint8[pos]) { + case 0: + return "constructor"; + case 1: + return "method"; + case 2: + return "get"; + case 3: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionKind`); + } +} + +function deserializePrivateIdentifier(pos) { + return { + type: "PrivateIdentifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeStaticBlock(pos) { + let node = { + type: "StaticBlock", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeAccessorPropertyType(pos) { + switch (uint8[pos]) { + case 0: + return "AccessorProperty"; + case 1: + return "TSAbstractAccessorProperty"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AccessorPropertyType`); + } +} + +function deserializeAccessorProperty(pos) { + let node = { + type: deserializeAccessorPropertyType(pos + 12), + decorators: null, + key: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializeImportExpression(pos) { + let node = { + type: "ImportExpression", + source: null, + options: null, + phase: deserializeOptionImportPhase(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.source = deserializeExpression(pos + 16); + node.options = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeImportDeclaration(pos) { + let node = { + type: "ImportDeclaration", + specifiers: null, + source: null, + phase: deserializeOptionImportPhase(pos + 12), + attributes: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + specifiers = deserializeOptionVecImportDeclarationSpecifier(pos + 16); + specifiers === null && (specifiers = []); + let withClause = deserializeOptionBoxWithClause(pos + 88); + node.specifiers = specifiers; + node.source = deserializeStringLiteral(pos + 40); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeImportPhase(pos) { + switch (uint8[pos]) { + case 0: + return "source"; + case 1: + return "defer"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportPhase`); + } +} + +function deserializeImportDeclarationSpecifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxImportSpecifier(pos + 8); + case 1: + return deserializeBoxImportDefaultSpecifier(pos + 8); + case 2: + return deserializeBoxImportNamespaceSpecifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportDeclarationSpecifier`); + } +} + +function deserializeImportSpecifier(pos) { + let node = { + type: "ImportSpecifier", + imported: null, + local: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.imported = deserializeModuleExportName(pos + 16); + node.local = deserializeBindingIdentifier(pos + 72); + return node; +} + +function deserializeImportDefaultSpecifier(pos) { + let node = { + type: "ImportDefaultSpecifier", + local: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeImportNamespaceSpecifier(pos) { + let node = { + type: "ImportNamespaceSpecifier", + local: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeWithClause(pos) { + return { attributes: deserializeVecImportAttribute(pos + 16) }; +} + +function deserializeImportAttribute(pos) { + let node = { + type: "ImportAttribute", + key: null, + value: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializeImportAttributeKey(pos + 16); + node.value = deserializeStringLiteral(pos + 72); + return node; +} + +function deserializeImportAttributeKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportAttributeKey`); + } +} + +function deserializeExportNamedDeclaration(pos) { + let node = { + type: "ExportNamedDeclaration", + declaration: null, + specifiers: null, + source: null, + attributes: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + withClause = deserializeOptionBoxWithClause(pos + 104); + node.declaration = deserializeOptionDeclaration(pos + 16); + node.specifiers = deserializeVecExportSpecifier(pos + 32); + node.source = deserializeOptionStringLiteral(pos + 56); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportDefaultDeclaration(pos) { + let node = { + type: "ExportDefaultDeclaration", + declaration: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.declaration = deserializeExportDefaultDeclarationKind(pos + 16); + return node; +} + +function deserializeExportAllDeclaration(pos) { + let node = { + type: "ExportAllDeclaration", + exported: null, + source: null, + attributes: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + withClause = deserializeOptionBoxWithClause(pos + 120); + node.exported = deserializeOptionModuleExportName(pos + 16); + node.source = deserializeStringLiteral(pos + 72); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportSpecifier(pos) { + let node = { + type: "ExportSpecifier", + local: null, + exported: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.local = deserializeModuleExportName(pos + 16); + node.exported = deserializeModuleExportName(pos + 72); + return node; +} + +function deserializeExportDefaultDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxFunction(pos + 8); + case 65: + return deserializeBoxClass(pos + 8); + case 66: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportDefaultDeclarationKind`); + } +} + +function deserializeModuleExportName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeIdentifierReference(pos + 8); + case 2: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleExportName`); + } +} + +function deserializeV8IntrinsicExpression(pos) { + let node = { + type: "V8IntrinsicExpression", + name: null, + arguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeIdentifierName(pos + 16); + node.arguments = deserializeVecArgument(pos + 48); + return node; +} + +function deserializeBooleanLiteral(pos) { + let value = deserializeBool(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value, + raw: null, + start, + end, + }; + node.raw = start === 0 && end === 0 ? null : value + ""; + return node; +} + +function deserializeNullLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: null, + raw: start === 0 && end === 0 ? null : "null", + start, + end, + }; +} + +function deserializeNumericLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: deserializeF64(pos + 32), + raw: + int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + }; +} + +function deserializeStringLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + }, + value = deserializeStr(pos + 16); + deserializeBool(pos + 12) && + (value = value.replace(/\uFFFD(.{4})/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))); + node.value = value; + return node; +} + +function deserializeBigIntLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + bigint = deserializeStr(pos + 16); + return { + type: "Literal", + value: BigInt(bigint), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + bigint, + start, + end, + }; +} + +function deserializeRegExpLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 12] === 0 && int32[(pos >> 2) + 13] === 0 + ? null + : sourceText.slice(start, end), + regex: null, + start, + end, + }, + regex = deserializeRegExp(pos + 16), + value = null; + try { + value = new RegExp(regex.pattern, regex.flags); + } catch {} + node.value = value; + node.regex = regex; + return node; +} + +function deserializeRegExp(pos) { + return { + pattern: deserializeStr(pos), + flags: deserializeRegExpFlags(pos + 24), + }; +} + +function deserializeRegExpFlags(pos) { + let flagBits = deserializeU8(pos), + flags = ""; + // Alphabetical order + flagBits & 64 && (flags += "d"); + flagBits & 1 && (flags += "g"); + flagBits & 2 && (flags += "i"); + flagBits & 4 && (flags += "m"); + flagBits & 8 && (flags += "s"); + flagBits & 16 && (flags += "u"); + flagBits & 128 && (flags += "v"); + flagBits & 32 && (flags += "y"); + return flags; +} + +function deserializeJSXElement(pos) { + let node = { + type: "JSXElement", + openingElement: null, + children: null, + closingElement: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + closingElement = deserializeOptionBoxJSXClosingElement(pos + 48), + openingElement = deserializeBoxJSXOpeningElement(pos + 16); + closingElement === null && (openingElement.selfClosing = true); + node.openingElement = openingElement; + node.children = deserializeVecJSXChild(pos + 24); + node.closingElement = closingElement; + return node; +} + +function deserializeJSXOpeningElement(pos) { + let node = { + type: "JSXOpeningElement", + name: null, + attributes: null, + selfClosing: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeJSXElementName(pos + 16); + node.attributes = deserializeVecJSXAttributeItem(pos + 40); + return node; +} + +function deserializeJSXClosingElement(pos) { + let node = { + type: "JSXClosingElement", + name: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeJSXElementName(pos + 16); + return node; +} + +function deserializeJSXFragment(pos) { + let node = { + type: "JSXFragment", + openingFragment: null, + children: null, + closingFragment: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.openingFragment = deserializeJSXOpeningFragment(pos + 16); + node.children = deserializeVecJSXChild(pos + 32); + node.closingFragment = deserializeJSXClosingFragment(pos + 56); + return node; +} + +function deserializeJSXOpeningFragment(pos) { + return { + type: "JSXOpeningFragment", + attributes: [], + selfClosing: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXClosingFragment(pos) { + return { + type: "JSXClosingFragment", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXElementName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + }; + case 2: + return deserializeBoxJSXNamespacedName(pos + 8); + case 3: + return deserializeBoxJSXMemberExpression(pos + 8); + case 4: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXElementName`); + } +} + +function deserializeJSXNamespacedName(pos) { + let node = { + type: "JSXNamespacedName", + namespace: null, + name: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.namespace = deserializeJSXIdentifier(pos + 16); + node.name = deserializeJSXIdentifier(pos + 48); + return node; +} + +function deserializeJSXMemberExpression(pos) { + let node = { + type: "JSXMemberExpression", + object: null, + property: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeJSXMemberExpressionObject(pos + 16); + node.property = deserializeJSXIdentifier(pos + 32); + return node; +} + +function deserializeJSXMemberExpressionObject(pos) { + switch (uint8[pos]) { + case 0: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + }; + case 1: + return deserializeBoxJSXMemberExpression(pos + 8); + case 2: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXMemberExpressionObject`); + } +} + +function deserializeJSXExpressionContainer(pos) { + let node = { + type: "JSXExpressionContainer", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeJSXExpression(pos + 16); + return node; +} + +function deserializeJSXExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeJSXEmptyExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXExpression`); + } +} + +function deserializeJSXEmptyExpression(pos) { + return { + type: "JSXEmptyExpression", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXAttributeItem(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXAttribute(pos + 8); + case 1: + return deserializeBoxJSXSpreadAttribute(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeItem`); + } +} + +function deserializeJSXAttribute(pos) { + let node = { + type: "JSXAttribute", + name: null, + value: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeJSXAttributeName(pos + 16); + node.value = deserializeOptionJSXAttributeValue(pos + 32); + return node; +} + +function deserializeJSXSpreadAttribute(pos) { + let node = { + type: "JSXSpreadAttribute", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXAttributeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + return deserializeBoxJSXNamespacedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeName`); + } +} + +function deserializeJSXAttributeValue(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStringLiteral(pos + 8); + case 1: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 2: + return deserializeBoxJSXElement(pos + 8); + case 3: + return deserializeBoxJSXFragment(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeValue`); + } +} + +function deserializeJSXIdentifier(pos) { + return { + type: "JSXIdentifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXChild(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXText(pos + 8); + case 1: + return deserializeBoxJSXElement(pos + 8); + case 2: + return deserializeBoxJSXFragment(pos + 8); + case 3: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 4: + return deserializeBoxJSXSpreadChild(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXChild`); + } +} + +function deserializeJSXSpreadChild(pos) { + let node = { + type: "JSXSpreadChild", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXText(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "JSXText", + value: deserializeStr(pos + 16), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + }; +} + +function deserializeTSThisParameter(pos) { + let node = { + type: "Identifier", + decorators: [], + name: "this", + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 24); + return node; +} + +function deserializeTSEnumDeclaration(pos) { + let node = { + type: "TSEnumDeclaration", + id: null, + body: null, + const: deserializeBool(pos + 12), + declare: deserializeBool(pos + 13), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.body = deserializeTSEnumBody(pos + 48); + return node; +} + +function deserializeTSEnumBody(pos) { + let node = { + type: "TSEnumBody", + members: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.members = deserializeVecTSEnumMember(pos + 16); + return node; +} + +function deserializeTSEnumMember(pos) { + let node = { + type: "TSEnumMember", + id: null, + initializer: null, + computed: deserializeU8(pos + 16) > 1, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeTSEnumMemberName(pos + 16); + node.initializer = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeTSEnumMemberName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxStringLiteral(pos + 8); + case 2: + return deserializeBoxStringLiteral(pos + 8); + case 3: + return deserializeBoxTemplateLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSEnumMemberName`); + } +} + +function deserializeTSTypeAnnotation(pos) { + let node = { + type: "TSTypeAnnotation", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSLiteralType(pos) { + let node = { + type: "TSLiteralType", + literal: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.literal = deserializeTSLiteral(pos + 16); + return node; +} + +function deserializeTSLiteral(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNumericLiteral(pos + 8); + case 2: + return deserializeBoxBigIntLiteral(pos + 8); + case 3: + return deserializeBoxStringLiteral(pos + 8); + case 4: + return deserializeBoxTemplateLiteral(pos + 8); + case 5: + return deserializeBoxUnaryExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSLiteral`); + } +} + +function deserializeTSType(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSType`); + } +} + +function deserializeTSConditionalType(pos) { + let node = { + type: "TSConditionalType", + checkType: null, + extendsType: null, + trueType: null, + falseType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.checkType = deserializeTSType(pos + 16); + node.extendsType = deserializeTSType(pos + 32); + node.trueType = deserializeTSType(pos + 48); + node.falseType = deserializeTSType(pos + 64); + return node; +} + +function deserializeTSUnionType(pos) { + let node = { + type: "TSUnionType", + types: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSIntersectionType(pos) { + let node = { + type: "TSIntersectionType", + types: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSParenthesizedType(pos) { + let node; + node = { + type: "TSParenthesizedType", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTypeOperator(pos) { + let node = { + type: "TSTypeOperator", + operator: deserializeTSTypeOperatorOperator(pos + 12), + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTypeOperatorOperator(pos) { + switch (uint8[pos]) { + case 0: + return "keyof"; + case 1: + return "unique"; + case 2: + return "readonly"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeOperatorOperator`); + } +} + +function deserializeTSArrayType(pos) { + let node = { + type: "TSArrayType", + elementType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.elementType = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSIndexedAccessType(pos) { + let node = { + type: "TSIndexedAccessType", + objectType: null, + indexType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.objectType = deserializeTSType(pos + 16); + node.indexType = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTupleType(pos) { + let node = { + type: "TSTupleType", + elementTypes: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.elementTypes = deserializeVecTSTupleElement(pos + 16); + return node; +} + +function deserializeTSNamedTupleMember(pos) { + let node = { + type: "TSNamedTupleMember", + label: null, + elementType: null, + optional: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeIdentifierName(pos + 16); + node.elementType = deserializeTSTupleElement(pos + 48); + return node; +} + +function deserializeTSOptionalType(pos) { + let node = { + type: "TSOptionalType", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSRestType(pos) { + let node = { + type: "TSRestType", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTupleElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + case 64: + return deserializeBoxTSOptionalType(pos + 8); + case 65: + return deserializeBoxTSRestType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTupleElement`); + } +} + +function deserializeTSAnyKeyword(pos) { + return { + type: "TSAnyKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSStringKeyword(pos) { + return { + type: "TSStringKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSBooleanKeyword(pos) { + return { + type: "TSBooleanKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSNumberKeyword(pos) { + return { + type: "TSNumberKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSNeverKeyword(pos) { + return { + type: "TSNeverKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSIntrinsicKeyword(pos) { + return { + type: "TSIntrinsicKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSUnknownKeyword(pos) { + return { + type: "TSUnknownKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSNullKeyword(pos) { + return { + type: "TSNullKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSUndefinedKeyword(pos) { + return { + type: "TSUndefinedKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSVoidKeyword(pos) { + return { + type: "TSVoidKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSSymbolKeyword(pos) { + return { + type: "TSSymbolKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSThisType(pos) { + return { + type: "TSThisType", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSObjectKeyword(pos) { + return { + type: "TSObjectKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSBigIntKeyword(pos) { + return { + type: "TSBigIntKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSTypeReference(pos) { + let node = { + type: "TSTypeReference", + typeName: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeName = deserializeTSTypeName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeName`); + } +} + +function deserializeTSQualifiedName(pos) { + let node = { + type: "TSQualifiedName", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeTSTypeName(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSTypeParameterInstantiation(pos) { + let node = { + type: "TSTypeParameterInstantiation", + params: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.params = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSTypeParameter(pos) { + let node = { + type: "TSTypeParameter", + name: null, + constraint: null, + default: null, + in: deserializeBool(pos + 12), + out: deserializeBool(pos + 13), + const: deserializeBool(pos + 14), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeOptionTSType(pos + 48); + node.default = deserializeOptionTSType(pos + 64); + return node; +} + +function deserializeTSTypeParameterDeclaration(pos) { + let node = { + type: "TSTypeParameterDeclaration", + params: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.params = deserializeVecTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeAliasDeclaration(pos) { + let node = { + type: "TSTypeAliasDeclaration", + id: null, + typeParameters: null, + typeAnnotation: null, + declare: deserializeBool(pos + 72), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.typeAnnotation = deserializeTSType(pos + 56); + return node; +} + +function deserializeTSInterfaceDeclaration(pos) { + let node = { + type: "TSInterfaceDeclaration", + id: null, + typeParameters: null, + extends: null, + body: null, + declare: deserializeBool(pos + 88), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.extends = deserializeVecTSInterfaceHeritage(pos + 56); + node.body = deserializeBoxTSInterfaceBody(pos + 80); + return node; +} + +function deserializeTSInterfaceBody(pos) { + let node = { + type: "TSInterfaceBody", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSPropertySignature(pos) { + let node = { + type: "TSPropertySignature", + computed: deserializeBool(pos + 12), + optional: deserializeBool(pos + 13), + readonly: deserializeBool(pos + 14), + key: null, + typeAnnotation: null, + accessibility: null, + static: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSSignature(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSIndexSignature(pos + 8); + case 1: + return deserializeBoxTSPropertySignature(pos + 8); + case 2: + return deserializeBoxTSCallSignatureDeclaration(pos + 8); + case 3: + return deserializeBoxTSConstructSignatureDeclaration(pos + 8); + case 4: + return deserializeBoxTSMethodSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSSignature`); + } +} + +function deserializeTSIndexSignature(pos) { + let node = { + type: "TSIndexSignature", + parameters: null, + typeAnnotation: null, + readonly: deserializeBool(pos + 12), + static: deserializeBool(pos + 13), + accessibility: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.parameters = deserializeVecTSIndexSignatureName(pos + 16); + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSCallSignatureDeclaration(pos) { + let node = { + type: "TSCallSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSMethodSignatureKind(pos) { + switch (uint8[pos]) { + case 0: + return "method"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMethodSignatureKind`); + } +} + +function deserializeTSMethodSignature(pos) { + let node = { + type: "TSMethodSignature", + key: null, + computed: deserializeBool(pos + 64), + optional: deserializeBool(pos + 65), + kind: deserializeTSMethodSignatureKind(pos + 66), + typeParameters: null, + params: null, + returnType: null, + accessibility: null, + readonly: false, + static: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 48), + thisParam = deserializeOptionBoxTSThisParameter(pos + 40); + thisParam !== null && params.unshift(thisParam); + node.key = deserializePropertyKey(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 32); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 56); + return node; +} + +function deserializeTSConstructSignatureDeclaration(pos) { + let node = { + type: "TSConstructSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSIndexSignatureName(pos) { + let node = { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSInterfaceHeritage(pos) { + let node = { + type: "TSInterfaceHeritage", + expression: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypePredicate(pos) { + let node = { + type: "TSTypePredicate", + parameterName: null, + asserts: deserializeBool(pos + 12), + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.parameterName = deserializeTSTypePredicateName(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSTypePredicateName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeTSThisType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypePredicateName`); + } +} + +function deserializeTSModuleDeclaration(pos) { + let kind = deserializeTSModuleDeclarationKind(pos + 88), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + declare = deserializeBool(pos + 89), + node, + body = deserializeOptionTSModuleDeclarationBody(pos + 72); + if (body === null) { + node = { + type: "TSModuleDeclaration", + id: null, + // No `body` field + kind, + declare, + global: false, + start, + end, + }; + node.id = deserializeTSModuleDeclarationName(pos + 16); + } else { + node = { + type: "TSModuleDeclaration", + id: null, + body, + kind, + declare, + global: false, + start, + end, + }; + let id = deserializeTSModuleDeclarationName(pos + 16); + if (body.type === "TSModuleBlock") node.id = id; + else { + let innerId = body.id; + if (innerId.type === "Identifier") + node.id = { + type: "TSQualifiedName", + left: id, + right: innerId, + start: id.start, + end: innerId.end, + }; + else { + // Replace `left` of innermost `TSQualifiedName` with a nested `TSQualifiedName` with `id` of + // this module on left, and previous `left` of innermost `TSQualifiedName` on right + node.id = innerId; + let { start } = id; + for (;;) { + innerId.start = start; + if (innerId.left.type === "Identifier") break; + innerId = innerId.left; + } + let right = innerId.left; + innerId.left = { + type: "TSQualifiedName", + left: id, + right, + start, + end: right.end, + }; + } + if (Object.hasOwn(body, "body")) { + body = body.body; + node.body = body; + } else body = null; + } + } + return node; +} + +function deserializeTSModuleDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "module"; + case 1: + return "namespace"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationKind`); + } +} + +function deserializeTSModuleDeclarationName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBindingIdentifier(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationName`); + } +} + +function deserializeTSModuleDeclarationBody(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 1: + return deserializeBoxTSModuleBlock(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationBody`); + } +} + +function deserializeTSGlobalDeclaration(pos) { + let node = { + type: "TSModuleDeclaration", + id: null, + body: null, + kind: "global", + declare: deserializeBool(pos + 88), + global: true, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = { + type: "Identifier", + name: "global", + start: deserializeI32(pos + 16), + end: deserializeI32(pos + 20), + }; + node.body = deserializeTSModuleBlock(pos + 24); + return node; +} + +function deserializeTSModuleBlock(pos) { + let node = { + type: "TSModuleBlock", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeTSTypeLiteral(pos) { + let node = { + type: "TSTypeLiteral", + members: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.members = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSInferType(pos) { + let node = { + type: "TSInferType", + typeParameter: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeParameter = deserializeBoxTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeQuery(pos) { + let node = { + type: "TSTypeQuery", + exprName: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.exprName = deserializeTSTypeQueryExprName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeQueryExprName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + case 3: + return deserializeBoxTSImportType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeQueryExprName`); + } +} + +function deserializeTSImportType(pos) { + let node = { + type: "TSImportType", + source: null, + options: null, + qualifier: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.source = deserializeStringLiteral(pos + 16); + node.options = deserializeOptionBoxObjectExpression(pos + 64); + node.qualifier = deserializeOptionTSImportTypeQualifier(pos + 72); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 88); + return node; +} + +function deserializeTSImportTypeQualifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxTSImportTypeQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSImportTypeQualifier`); + } +} + +function deserializeTSImportTypeQualifiedName(pos) { + let node = { + type: "TSQualifiedName", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeTSImportTypeQualifier(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSFunctionType(pos) { + let node = { + type: "TSFunctionType", + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSConstructorType(pos) { + let node = { + type: "TSConstructorType", + abstract: deserializeBool(pos + 40), + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSMappedType(pos) { + let node = { + type: "TSMappedType", + key: null, + constraint: null, + nameType: null, + typeAnnotation: null, + optional: null, + readonly: deserializeOptionTSMappedTypeModifierOperator(pos + 97), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + optional = deserializeOptionTSMappedTypeModifierOperator(pos + 96); + optional === null && (optional = false); + node.key = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeTSType(pos + 48); + node.nameType = deserializeOptionTSType(pos + 64); + node.typeAnnotation = deserializeOptionTSType(pos + 80); + node.optional = optional; + return node; +} + +function deserializeTSMappedTypeModifierOperator(pos) { + switch (uint8[pos]) { + case 0: + return true; + case 1: + return "+"; + case 2: + return "-"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMappedTypeModifierOperator`); + } +} + +function deserializeTSTemplateLiteralType(pos) { + let node = { + type: "TSTemplateLiteralType", + quasis: null, + types: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.types = deserializeVecTSType(pos + 40); + return node; +} + +function deserializeTSAsExpression(pos) { + let node = { + type: "TSAsExpression", + expression: null, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSSatisfiesExpression(pos) { + let node = { + type: "TSSatisfiesExpression", + expression: null, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTypeAssertion(pos) { + let node = { + type: "TSTypeAssertion", + typeAnnotation: null, + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + node.expression = deserializeExpression(pos + 32); + return node; +} + +function deserializeTSImportEqualsDeclaration(pos) { + let node = { + type: "TSImportEqualsDeclaration", + id: null, + moduleReference: null, + importKind: deserializeImportOrExportKind(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.moduleReference = deserializeTSModuleReference(pos + 48); + return node; +} + +function deserializeTSModuleReference(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSExternalModuleReference(pos + 8); + case 1: + return deserializeBoxIdentifierReference(pos + 8); + case 2: + return deserializeBoxTSQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleReference`); + } +} + +function deserializeTSExternalModuleReference(pos) { + let node = { + type: "TSExternalModuleReference", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeTSNonNullExpression(pos) { + let node = { + type: "TSNonNullExpression", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeDecorator(pos) { + let node = { + type: "Decorator", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSExportAssignment(pos) { + let node = { + type: "TSExportAssignment", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSNamespaceExportDeclaration(pos) { + let node = { + type: "TSNamespaceExportDeclaration", + id: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeIdentifierName(pos + 16); + return node; +} + +function deserializeTSInstantiationExpression(pos) { + let node = { + type: "TSInstantiationExpression", + expression: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeImportOrExportKind(pos) { + switch (uint8[pos]) { + case 0: + return "value"; + case 1: + return "type"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportOrExportKind`); + } +} + +function deserializeJSDocNullableType(pos) { + let node = { + type: "TSJSDocNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocNonNullableType(pos) { + let node = { + type: "TSJSDocNonNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocUnknownType(pos) { + return { + type: "TSJSDocUnknownType", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeCommentKind(pos) { + switch (uint8[pos]) { + case 0: + return "Line"; + case 1: + return "Block"; + case 2: + return "Block"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for CommentKind`); + } +} + +function deserializeComment(pos) { + let type = deserializeCommentKind(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type, + value: sourceText.slice(start + 2, end - (type === "Line" ? 0 : 2)), + start, + end, + }; +} + +function deserializeModuleKind(pos) { + switch (uint8[pos]) { + case 0: + return "script"; + case 1: + return "module"; + case 3: + return "commonjs"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleKind`); + } +} + +function deserializeSpan(pos) { + return { + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeNameSpan(pos) { + return { + value: deserializeStr(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeImportEntry(pos) { + return { + importName: deserializeImportImportName(pos + 32), + localName: deserializeNameSpan(pos + 64), + isType: deserializeBool(pos + 88), + }; +} + +function deserializeImportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + return { + kind: "NamespaceObject", + name: null, + start: null, + end: null, + }; + case 2: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportImportName`); + } +} + +function deserializeExportEntry(pos) { + return { + moduleRequest: deserializeOptionNameSpan(pos + 16), + importName: deserializeExportImportName(pos + 40), + exportName: deserializeExportExportName(pos + 72), + localName: deserializeExportLocalName(pos + 104), + isType: deserializeBool(pos + 136), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeExportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + return { + kind: "All", + name: null, + start: null, + end: null, + }; + case 2: + return { + kind: "AllButDefault", + name: null, + start: null, + end: null, + }; + case 3: + return { + kind: "None", + name: null, + start: null, + end: null, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportImportName`); + } +} + +function deserializeExportExportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportExportName`); + } +} + +function deserializeExportLocalName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Default", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportLocalName`); + } +} + +function deserializeDynamicImport(pos) { + return { + moduleRequest: deserializeSpan(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeAssignmentOperator(pos) { + switch (uint8[pos]) { + case 0: + return "="; + case 1: + return "+="; + case 2: + return "-="; + case 3: + return "*="; + case 4: + return "/="; + case 5: + return "%="; + case 6: + return "**="; + case 7: + return "<<="; + case 8: + return ">>="; + case 9: + return ">>>="; + case 10: + return "|="; + case 11: + return "^="; + case 12: + return "&="; + case 13: + return "||="; + case 14: + return "&&="; + case 15: + return "??="; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentOperator`); + } +} + +function deserializeBinaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "=="; + case 1: + return "!="; + case 2: + return "==="; + case 3: + return "!=="; + case 4: + return "<"; + case 5: + return "<="; + case 6: + return ">"; + case 7: + return ">="; + case 8: + return "+"; + case 9: + return "-"; + case 10: + return "*"; + case 11: + return "/"; + case 12: + return "%"; + case 13: + return "**"; + case 14: + return "<<"; + case 15: + return ">>"; + case 16: + return ">>>"; + case 17: + return "|"; + case 18: + return "^"; + case 19: + return "&"; + case 20: + return "in"; + case 21: + return "instanceof"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BinaryOperator`); + } +} + +function deserializeLogicalOperator(pos) { + switch (uint8[pos]) { + case 0: + return "||"; + case 1: + return "&&"; + case 2: + return "??"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for LogicalOperator`); + } +} + +function deserializeUnaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "+"; + case 1: + return "-"; + case 2: + return "!"; + case 3: + return "~"; + case 4: + return "typeof"; + case 5: + return "void"; + case 6: + return "delete"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UnaryOperator`); + } +} + +function deserializeUpdateOperator(pos) { + switch (uint8[pos]) { + case 0: + return "++"; + case 1: + return "--"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UpdateOperator`); + } +} + +function deserializeRawTransferData(pos) { + return { + program: deserializeProgram(pos), + comments: deserializeVecComment(pos + 144), + module: deserializeEcmaScriptModule(pos + 168), + errors: deserializeVecError(pos + 272), + }; +} + +function deserializeError(pos) { + return { + severity: deserializeErrorSeverity(pos + 72), + message: deserializeStr(pos), + labels: deserializeVecErrorLabel(pos + 16), + helpMessage: deserializeOptionStr(pos + 40), + codeframe: deserializeStr(pos + 56), + }; +} + +function deserializeErrorSeverity(pos) { + switch (uint8[pos]) { + case 0: + return "Error"; + case 1: + return "Warning"; + case 2: + return "Advice"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ErrorSeverity`); + } +} + +function deserializeErrorLabel(pos) { + return { + message: deserializeOptionStr(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeEcmaScriptModule(pos) { + return { + hasModuleSyntax: deserializeBool(pos + 96), + staticImports: deserializeVecStaticImport(pos), + staticExports: deserializeVecStaticExport(pos + 24), + dynamicImports: deserializeVecDynamicImport(pos + 48), + importMetas: deserializeVecSpan(pos + 72), + }; +} + +function deserializeStaticImport(pos) { + return { + moduleRequest: deserializeNameSpan(pos + 8), + entries: deserializeVecImportEntry(pos + 32), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeStaticExport(pos) { + return { + entries: deserializeVecExportEntry(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeStr(pos) { + let pos32 = pos >> 2, + len = int32[pos32 + 2]; + if (len === 0) return ""; + pos = int32[pos32]; + let end = pos + len; + if (end <= firstNonAsciiPos) return sourceTextLatin.substr(pos, len); + // Use `utf8Slice` for strings longer than 64 bytes + if (len > 64) return utf8Slice.call(uint8, pos, end); + if (pos < sourceEndPos) { + // Check if all bytes are ASCII, use `utf8Slice` if not + for (let i = pos; i < end; i++) if (uint8[i] >= 128) return utf8Slice.call(uint8, pos, end); + // String is all ASCII, so slice from `sourceTextLatin` + return sourceTextLatin.substr(pos, len); + } + // String is not in source region - use `fromCharCode.apply` with a temp array of correct length. + // Copy bytes into temp array. + // If any byte is non-ASCII, use `utf8Slice`. + let arr = stringDecodeArrays[len]; + for (let i = 0; i < len; i++) { + let b = uint8[pos + i]; + if (b >= 128) return utf8Slice.call(uint8, pos, end); + arr[i] = b; + } + // Call `fromCharCode` with temp array + return fromCharCode.apply(null, arr); +} + +function deserializeVecComment(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeComment(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionHashbang(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeHashbang(pos); +} + +function deserializeVecDirective(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeDirective(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecStatement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeStatement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxBooleanLiteral(pos) { + return deserializeBooleanLiteral(int32[pos >> 2]); +} + +function deserializeBoxNullLiteral(pos) { + return deserializeNullLiteral(int32[pos >> 2]); +} + +function deserializeBoxNumericLiteral(pos) { + return deserializeNumericLiteral(int32[pos >> 2]); +} + +function deserializeBoxBigIntLiteral(pos) { + return deserializeBigIntLiteral(int32[pos >> 2]); +} + +function deserializeBoxRegExpLiteral(pos) { + return deserializeRegExpLiteral(int32[pos >> 2]); +} + +function deserializeBoxStringLiteral(pos) { + return deserializeStringLiteral(int32[pos >> 2]); +} + +function deserializeBoxTemplateLiteral(pos) { + return deserializeTemplateLiteral(int32[pos >> 2]); +} + +function deserializeBoxIdentifierReference(pos) { + return deserializeIdentifierReference(int32[pos >> 2]); +} + +function deserializeBoxMetaProperty(pos) { + return deserializeMetaProperty(int32[pos >> 2]); +} + +function deserializeBoxSuper(pos) { + return deserializeSuper(int32[pos >> 2]); +} + +function deserializeBoxArrayExpression(pos) { + return deserializeArrayExpression(int32[pos >> 2]); +} + +function deserializeBoxArrowFunctionExpression(pos) { + return deserializeArrowFunctionExpression(int32[pos >> 2]); +} + +function deserializeBoxAssignmentExpression(pos) { + return deserializeAssignmentExpression(int32[pos >> 2]); +} + +function deserializeBoxAwaitExpression(pos) { + return deserializeAwaitExpression(int32[pos >> 2]); +} + +function deserializeBoxBinaryExpression(pos) { + return deserializeBinaryExpression(int32[pos >> 2]); +} + +function deserializeBoxCallExpression(pos) { + return deserializeCallExpression(int32[pos >> 2]); +} + +function deserializeBoxChainExpression(pos) { + return deserializeChainExpression(int32[pos >> 2]); +} + +function deserializeBoxClass(pos) { + return deserializeClass(int32[pos >> 2]); +} + +function deserializeBoxConditionalExpression(pos) { + return deserializeConditionalExpression(int32[pos >> 2]); +} + +function deserializeBoxFunction(pos) { + return deserializeFunction(int32[pos >> 2]); +} + +function deserializeBoxImportExpression(pos) { + return deserializeImportExpression(int32[pos >> 2]); +} + +function deserializeBoxLogicalExpression(pos) { + return deserializeLogicalExpression(int32[pos >> 2]); +} + +function deserializeBoxNewExpression(pos) { + return deserializeNewExpression(int32[pos >> 2]); +} + +function deserializeBoxObjectExpression(pos) { + return deserializeObjectExpression(int32[pos >> 2]); +} + +function deserializeBoxParenthesizedExpression(pos) { + return deserializeParenthesizedExpression(int32[pos >> 2]); +} + +function deserializeBoxSequenceExpression(pos) { + return deserializeSequenceExpression(int32[pos >> 2]); +} + +function deserializeBoxTaggedTemplateExpression(pos) { + return deserializeTaggedTemplateExpression(int32[pos >> 2]); +} + +function deserializeBoxThisExpression(pos) { + return deserializeThisExpression(int32[pos >> 2]); +} + +function deserializeBoxUnaryExpression(pos) { + return deserializeUnaryExpression(int32[pos >> 2]); +} + +function deserializeBoxUpdateExpression(pos) { + return deserializeUpdateExpression(int32[pos >> 2]); +} + +function deserializeBoxYieldExpression(pos) { + return deserializeYieldExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateInExpression(pos) { + return deserializePrivateInExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXElement(pos) { + return deserializeJSXElement(int32[pos >> 2]); +} + +function deserializeBoxJSXFragment(pos) { + return deserializeJSXFragment(int32[pos >> 2]); +} + +function deserializeBoxTSAsExpression(pos) { + return deserializeTSAsExpression(int32[pos >> 2]); +} + +function deserializeBoxTSSatisfiesExpression(pos) { + return deserializeTSSatisfiesExpression(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAssertion(pos) { + return deserializeTSTypeAssertion(int32[pos >> 2]); +} + +function deserializeBoxTSNonNullExpression(pos) { + return deserializeTSNonNullExpression(int32[pos >> 2]); +} + +function deserializeBoxTSInstantiationExpression(pos) { + return deserializeTSInstantiationExpression(int32[pos >> 2]); +} + +function deserializeBoxV8IntrinsicExpression(pos) { + return deserializeV8IntrinsicExpression(int32[pos >> 2]); +} + +function deserializeVecArrayExpressionElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeArrayExpressionElement(pos)); + pos += 24; + } + return arr; +} + +function deserializeBoxSpreadElement(pos) { + return deserializeSpreadElement(int32[pos >> 2]); +} + +function deserializeVecObjectPropertyKind(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeObjectPropertyKind(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxObjectProperty(pos) { + return deserializeObjectProperty(int32[pos >> 2]); +} + +function deserializeBool(pos) { + return uint8[pos] === 1; +} + +function deserializeBoxIdentifierName(pos) { + return deserializeIdentifierName(int32[pos >> 2]); +} + +function deserializeBoxPrivateIdentifier(pos) { + return deserializePrivateIdentifier(int32[pos >> 2]); +} + +function deserializeVecTemplateElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTemplateElement(pos)); + pos += 48; + } + return arr; +} + +function deserializeVecExpression(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeExpression(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSTypeParameterInstantiation(pos) { + return deserializeTSTypeParameterInstantiation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterInstantiation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterInstantiation(pos); +} + +function deserializeOptionStr(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 ? null : deserializeStr(pos); +} + +function deserializeBoxComputedMemberExpression(pos) { + return deserializeComputedMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxStaticMemberExpression(pos) { + return deserializeStaticMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateFieldExpression(pos) { + return deserializePrivateFieldExpression(int32[pos >> 2]); +} + +function deserializeVecArgument(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeArgument(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxArrayAssignmentTarget(pos) { + return deserializeArrayAssignmentTarget(int32[pos >> 2]); +} + +function deserializeBoxObjectAssignmentTarget(pos) { + return deserializeObjectAssignmentTarget(int32[pos >> 2]); +} + +function deserializeOptionAssignmentTargetMaybeDefault(pos) { + return uint8[pos] === 51 ? null : deserializeAssignmentTargetMaybeDefault(pos); +} + +function deserializeVecOptionAssignmentTargetMaybeDefault(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionAssignmentTargetMaybeDefault(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetRest(pos) { + return deserializeAssignmentTargetRest(int32[pos >> 2]); +} + +function deserializeOptionBoxAssignmentTargetRest(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxAssignmentTargetRest(pos); +} + +function deserializeVecAssignmentTargetProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeAssignmentTargetProperty(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetWithDefault(pos) { + return deserializeAssignmentTargetWithDefault(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyIdentifier(pos) { + return deserializeAssignmentTargetPropertyIdentifier(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyProperty(pos) { + return deserializeAssignmentTargetPropertyProperty(int32[pos >> 2]); +} + +function deserializeOptionExpression(pos) { + return uint8[pos] === 51 ? null : deserializeExpression(pos); +} + +function deserializeBoxBlockStatement(pos) { + return deserializeBlockStatement(int32[pos >> 2]); +} + +function deserializeBoxBreakStatement(pos) { + return deserializeBreakStatement(int32[pos >> 2]); +} + +function deserializeBoxContinueStatement(pos) { + return deserializeContinueStatement(int32[pos >> 2]); +} + +function deserializeBoxDebuggerStatement(pos) { + return deserializeDebuggerStatement(int32[pos >> 2]); +} + +function deserializeBoxDoWhileStatement(pos) { + return deserializeDoWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxEmptyStatement(pos) { + return deserializeEmptyStatement(int32[pos >> 2]); +} + +function deserializeBoxExpressionStatement(pos) { + return deserializeExpressionStatement(int32[pos >> 2]); +} + +function deserializeBoxForInStatement(pos) { + return deserializeForInStatement(int32[pos >> 2]); +} + +function deserializeBoxForOfStatement(pos) { + return deserializeForOfStatement(int32[pos >> 2]); +} + +function deserializeBoxForStatement(pos) { + return deserializeForStatement(int32[pos >> 2]); +} + +function deserializeBoxIfStatement(pos) { + return deserializeIfStatement(int32[pos >> 2]); +} + +function deserializeBoxLabeledStatement(pos) { + return deserializeLabeledStatement(int32[pos >> 2]); +} + +function deserializeBoxReturnStatement(pos) { + return deserializeReturnStatement(int32[pos >> 2]); +} + +function deserializeBoxSwitchStatement(pos) { + return deserializeSwitchStatement(int32[pos >> 2]); +} + +function deserializeBoxThrowStatement(pos) { + return deserializeThrowStatement(int32[pos >> 2]); +} + +function deserializeBoxTryStatement(pos) { + return deserializeTryStatement(int32[pos >> 2]); +} + +function deserializeBoxWhileStatement(pos) { + return deserializeWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxWithStatement(pos) { + return deserializeWithStatement(int32[pos >> 2]); +} + +function deserializeBoxVariableDeclaration(pos) { + return deserializeVariableDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAliasDeclaration(pos) { + return deserializeTSTypeAliasDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSInterfaceDeclaration(pos) { + return deserializeTSInterfaceDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSEnumDeclaration(pos) { + return deserializeTSEnumDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSModuleDeclaration(pos) { + return deserializeTSModuleDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSGlobalDeclaration(pos) { + return deserializeTSGlobalDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSImportEqualsDeclaration(pos) { + return deserializeTSImportEqualsDeclaration(int32[pos >> 2]); +} + +function deserializeVecVariableDeclarator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeVariableDeclarator(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxTSTypeAnnotation(pos) { + return deserializeTSTypeAnnotation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeAnnotation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeAnnotation(pos); +} + +function deserializeOptionStatement(pos) { + return uint8[pos] === 70 ? null : deserializeStatement(pos); +} + +function deserializeOptionForStatementInit(pos) { + return uint8[pos] === 65 ? null : deserializeForStatementInit(pos); +} + +function deserializeOptionLabelIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeLabelIdentifier(pos); +} + +function deserializeVecSwitchCase(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeSwitchCase(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxCatchClause(pos) { + return deserializeCatchClause(int32[pos >> 2]); +} + +function deserializeOptionBoxCatchClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxCatchClause(pos); +} + +function deserializeOptionBoxBlockStatement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBlockStatement(pos); +} + +function deserializeOptionCatchParameter(pos) { + return uint8[pos + 16] === 4 ? null : deserializeCatchParameter(pos); +} + +function deserializeBoxBindingIdentifier(pos) { + return deserializeBindingIdentifier(int32[pos >> 2]); +} + +function deserializeBoxObjectPattern(pos) { + return deserializeObjectPattern(int32[pos >> 2]); +} + +function deserializeBoxArrayPattern(pos) { + return deserializeArrayPattern(int32[pos >> 2]); +} + +function deserializeBoxAssignmentPattern(pos) { + return deserializeAssignmentPattern(int32[pos >> 2]); +} + +function deserializeVecBindingProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeBindingProperty(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxBindingRestElement(pos) { + return deserializeBindingRestElement(int32[pos >> 2]); +} + +function deserializeOptionBoxBindingRestElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBindingRestElement(pos); +} + +function deserializeOptionBindingPattern(pos) { + return uint8[pos] === 4 ? null : deserializeBindingPattern(pos); +} + +function deserializeVecOptionBindingPattern(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionBindingPattern(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionBindingIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeBindingIdentifier(pos); +} + +function deserializeBoxTSTypeParameterDeclaration(pos) { + return deserializeTSTypeParameterDeclaration(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterDeclaration(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterDeclaration(pos); +} + +function deserializeBoxTSThisParameter(pos) { + return deserializeTSThisParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxTSThisParameter(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSThisParameter(pos); +} + +function deserializeBoxFormalParameters(pos) { + return deserializeFormalParameters(int32[pos >> 2]); +} + +function deserializeBoxFunctionBody(pos) { + return deserializeFunctionBody(int32[pos >> 2]); +} + +function deserializeOptionBoxFunctionBody(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxFunctionBody(pos); +} + +function deserializeVecFormalParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 72; + for (; pos !== endPos; ) { + arr.push(deserializeFormalParameter(pos)); + pos += 72; + } + return arr; +} + +function deserializeVecDecorator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeDecorator(pos)); + pos += 32; + } + return arr; +} + +function deserializeBoxExpression(pos) { + return deserializeExpression(int32[pos >> 2]); +} + +function deserializeOptionBoxExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxExpression(pos); +} + +function deserializeBoxClassBody(pos) { + return deserializeClassBody(int32[pos >> 2]); +} + +function deserializeVecClassElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeClassElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxStaticBlock(pos) { + return deserializeStaticBlock(int32[pos >> 2]); +} + +function deserializeBoxMethodDefinition(pos) { + return deserializeMethodDefinition(int32[pos >> 2]); +} + +function deserializeBoxPropertyDefinition(pos) { + return deserializePropertyDefinition(int32[pos >> 2]); +} + +function deserializeBoxAccessorProperty(pos) { + return deserializeAccessorProperty(int32[pos >> 2]); +} + +function deserializeBoxTSIndexSignature(pos) { + return deserializeTSIndexSignature(int32[pos >> 2]); +} + +function deserializeBoxImportDeclaration(pos) { + return deserializeImportDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportAllDeclaration(pos) { + return deserializeExportAllDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportDefaultDeclaration(pos) { + return deserializeExportDefaultDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportNamedDeclaration(pos) { + return deserializeExportNamedDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSExportAssignment(pos) { + return deserializeTSExportAssignment(int32[pos >> 2]); +} + +function deserializeBoxTSNamespaceExportDeclaration(pos) { + return deserializeTSNamespaceExportDeclaration(int32[pos >> 2]); +} + +function deserializeOptionImportPhase(pos) { + return uint8[pos] === 2 ? null : deserializeImportPhase(pos); +} + +function deserializeVecImportDeclarationSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeImportDeclarationSpecifier(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionVecImportDeclarationSpecifier(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeVecImportDeclarationSpecifier(pos); +} + +function deserializeBoxWithClause(pos) { + return deserializeWithClause(int32[pos >> 2]); +} + +function deserializeOptionBoxWithClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxWithClause(pos); +} + +function deserializeBoxImportSpecifier(pos) { + return deserializeImportSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportDefaultSpecifier(pos) { + return deserializeImportDefaultSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportNamespaceSpecifier(pos) { + return deserializeImportNamespaceSpecifier(int32[pos >> 2]); +} + +function deserializeVecImportAttribute(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 120; + for (; pos !== endPos; ) { + arr.push(deserializeImportAttribute(pos)); + pos += 120; + } + return arr; +} + +function deserializeOptionDeclaration(pos) { + return uint8[pos] === 31 ? null : deserializeDeclaration(pos); +} + +function deserializeVecExportSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 7); + for (; pos !== endPos; ) { + arr.push(deserializeExportSpecifier(pos)); + pos += 128; + } + return arr; +} + +function deserializeOptionStringLiteral(pos) { + return uint8[pos + 12] === 2 ? null : deserializeStringLiteral(pos); +} + +function deserializeOptionModuleExportName(pos) { + return uint8[pos] === 3 ? null : deserializeModuleExportName(pos); +} + +function deserializeF64(pos) { + return float64[pos >> 3]; +} + +function deserializeU8(pos) { + return uint8[pos]; +} + +function deserializeBoxJSXOpeningElement(pos) { + return deserializeJSXOpeningElement(int32[pos >> 2]); +} + +function deserializeVecJSXChild(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXChild(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXClosingElement(pos) { + return deserializeJSXClosingElement(int32[pos >> 2]); +} + +function deserializeOptionBoxJSXClosingElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxJSXClosingElement(pos); +} + +function deserializeVecJSXAttributeItem(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXAttributeItem(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXIdentifier(pos) { + return deserializeJSXIdentifier(int32[pos >> 2]); +} + +function deserializeBoxJSXNamespacedName(pos) { + return deserializeJSXNamespacedName(int32[pos >> 2]); +} + +function deserializeBoxJSXMemberExpression(pos) { + return deserializeJSXMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXAttribute(pos) { + return deserializeJSXAttribute(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadAttribute(pos) { + return deserializeJSXSpreadAttribute(int32[pos >> 2]); +} + +function deserializeOptionJSXAttributeValue(pos) { + return uint8[pos] === 4 ? null : deserializeJSXAttributeValue(pos); +} + +function deserializeBoxJSXExpressionContainer(pos) { + return deserializeJSXExpressionContainer(int32[pos >> 2]); +} + +function deserializeBoxJSXText(pos) { + return deserializeJSXText(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadChild(pos) { + return deserializeJSXSpreadChild(int32[pos >> 2]); +} + +function deserializeVecTSEnumMember(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTSEnumMember(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxTSAnyKeyword(pos) { + return deserializeTSAnyKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBigIntKeyword(pos) { + return deserializeTSBigIntKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBooleanKeyword(pos) { + return deserializeTSBooleanKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSIntrinsicKeyword(pos) { + return deserializeTSIntrinsicKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNeverKeyword(pos) { + return deserializeTSNeverKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNullKeyword(pos) { + return deserializeTSNullKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNumberKeyword(pos) { + return deserializeTSNumberKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSObjectKeyword(pos) { + return deserializeTSObjectKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSStringKeyword(pos) { + return deserializeTSStringKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSSymbolKeyword(pos) { + return deserializeTSSymbolKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUndefinedKeyword(pos) { + return deserializeTSUndefinedKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUnknownKeyword(pos) { + return deserializeTSUnknownKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSVoidKeyword(pos) { + return deserializeTSVoidKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSArrayType(pos) { + return deserializeTSArrayType(int32[pos >> 2]); +} + +function deserializeBoxTSConditionalType(pos) { + return deserializeTSConditionalType(int32[pos >> 2]); +} + +function deserializeBoxTSConstructorType(pos) { + return deserializeTSConstructorType(int32[pos >> 2]); +} + +function deserializeBoxTSFunctionType(pos) { + return deserializeTSFunctionType(int32[pos >> 2]); +} + +function deserializeBoxTSImportType(pos) { + return deserializeTSImportType(int32[pos >> 2]); +} + +function deserializeBoxTSIndexedAccessType(pos) { + return deserializeTSIndexedAccessType(int32[pos >> 2]); +} + +function deserializeBoxTSInferType(pos) { + return deserializeTSInferType(int32[pos >> 2]); +} + +function deserializeBoxTSIntersectionType(pos) { + return deserializeTSIntersectionType(int32[pos >> 2]); +} + +function deserializeBoxTSLiteralType(pos) { + return deserializeTSLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSMappedType(pos) { + return deserializeTSMappedType(int32[pos >> 2]); +} + +function deserializeBoxTSNamedTupleMember(pos) { + return deserializeTSNamedTupleMember(int32[pos >> 2]); +} + +function deserializeBoxTSTemplateLiteralType(pos) { + return deserializeTSTemplateLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSThisType(pos) { + return deserializeTSThisType(int32[pos >> 2]); +} + +function deserializeBoxTSTupleType(pos) { + return deserializeTSTupleType(int32[pos >> 2]); +} + +function deserializeBoxTSTypeLiteral(pos) { + return deserializeTSTypeLiteral(int32[pos >> 2]); +} + +function deserializeBoxTSTypeOperator(pos) { + return deserializeTSTypeOperator(int32[pos >> 2]); +} + +function deserializeBoxTSTypePredicate(pos) { + return deserializeTSTypePredicate(int32[pos >> 2]); +} + +function deserializeBoxTSTypeQuery(pos) { + return deserializeTSTypeQuery(int32[pos >> 2]); +} + +function deserializeBoxTSTypeReference(pos) { + return deserializeTSTypeReference(int32[pos >> 2]); +} + +function deserializeBoxTSUnionType(pos) { + return deserializeTSUnionType(int32[pos >> 2]); +} + +function deserializeBoxTSParenthesizedType(pos) { + return deserializeTSParenthesizedType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNullableType(pos) { + return deserializeJSDocNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNonNullableType(pos) { + return deserializeJSDocNonNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocUnknownType(pos) { + return deserializeJSDocUnknownType(int32[pos >> 2]); +} + +function deserializeVecTSType(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSType(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecTSTupleElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSTupleElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSOptionalType(pos) { + return deserializeTSOptionalType(int32[pos >> 2]); +} + +function deserializeBoxTSRestType(pos) { + return deserializeTSRestType(int32[pos >> 2]); +} + +function deserializeBoxTSQualifiedName(pos) { + return deserializeTSQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSType(pos) { + return uint8[pos] === 38 ? null : deserializeTSType(pos); +} + +function deserializeVecTSTypeParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeTSTypeParameter(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecTSInterfaceHeritage(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSInterfaceHeritage(pos)); + pos += 40; + } + return arr; +} + +function deserializeBoxTSInterfaceBody(pos) { + return deserializeTSInterfaceBody(int32[pos >> 2]); +} + +function deserializeVecTSSignature(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSSignature(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSPropertySignature(pos) { + return deserializeTSPropertySignature(int32[pos >> 2]); +} + +function deserializeBoxTSCallSignatureDeclaration(pos) { + return deserializeTSCallSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSConstructSignatureDeclaration(pos) { + return deserializeTSConstructSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSMethodSignature(pos) { + return deserializeTSMethodSignature(int32[pos >> 2]); +} + +function deserializeVecTSIndexSignatureName(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSIndexSignatureName(pos)); + pos += 40; + } + return arr; +} + +function deserializeOptionTSModuleDeclarationBody(pos) { + return uint8[pos] === 2 ? null : deserializeTSModuleDeclarationBody(pos); +} + +function deserializeBoxTSModuleBlock(pos) { + return deserializeTSModuleBlock(int32[pos >> 2]); +} + +function deserializeBoxTSTypeParameter(pos) { + return deserializeTSTypeParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxObjectExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxObjectExpression(pos); +} + +function deserializeOptionTSImportTypeQualifier(pos) { + return uint8[pos] === 2 ? null : deserializeTSImportTypeQualifier(pos); +} + +function deserializeBoxTSImportTypeQualifiedName(pos) { + return deserializeTSImportTypeQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSMappedTypeModifierOperator(pos) { + return uint8[pos] === 3 ? null : deserializeTSMappedTypeModifierOperator(pos); +} + +function deserializeBoxTSExternalModuleReference(pos) { + return deserializeTSExternalModuleReference(int32[pos >> 2]); +} + +function deserializeI32(pos) { + return int32[pos >> 2]; +} + +function deserializeOptionNameSpan(pos) { + return int32[(pos >> 2) + 2] === 0 && int32[(pos >> 2) + 3] === 0 + ? null + : deserializeNameSpan(pos); +} + +function deserializeVecError(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeError(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecErrorLabel(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeErrorLabel(pos)); + pos += 24; + } + return arr; +} + +function deserializeVecStaticImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeStaticImport(pos)); + pos += 56; + } + return arr; +} + +function deserializeVecStaticExport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeStaticExport(pos)); + pos += 32; + } + return arr; +} + +function deserializeVecDynamicImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeDynamicImport(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecSpan(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 3); + for (; pos !== endPos; ) { + arr.push(deserializeSpan(pos)); + pos += 8; + } + return arr; +} + +function deserializeVecImportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 96; + for (; pos !== endPos; ) { + arr.push(deserializeImportEntry(pos)); + pos += 96; + } + return arr; +} + +function deserializeVecExportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 144; + for (; pos !== endPos; ) { + arr.push(deserializeExportEntry(pos)); + pos += 144; + } + return arr; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/js_range.js b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/js_range.js new file mode 100644 index 0000000000000000000000000000000000000000..c1a496f881a1159abbee2c3da4c1b1f212c9db0d --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/js_range.js @@ -0,0 +1,6381 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer.rs`. + +let uint8, + int32, + float64, + sourceText, + sourceTextLatin, + sourceEndPos = 0, + firstNonAsciiPos = 0; + +const { fromCharCode } = String, + { utf8Slice, latin1Slice } = Buffer.prototype, + stringDecodeArrays = Array(65).fill(null); +for (let i = 0; i <= 64; i++) stringDecodeArrays[i] = Array(i).fill(0); + +export function deserialize(buffer, sourceText, sourceByteLen) { + sourceEndPos = sourceByteLen; + return deserializeWith(buffer, sourceText, sourceByteLen, deserializeRawTransferData); +} + +function deserializeWith(buffer, sourceTextInput, sourceByteLen, deserialize) { + uint8 = buffer; + int32 = buffer.int32; + float64 = buffer.float64; + sourceText = sourceTextInput; + if (sourceText.length === sourceByteLen) { + firstNonAsciiPos = sourceByteLen; + sourceTextLatin = sourceText; + } else { + let i = 0; + for (; i < sourceByteLen && uint8[i] < 128; i++); + firstNonAsciiPos = i; + sourceTextLatin = latin1Slice.call(uint8, 0, sourceByteLen); + } + let data = deserialize(int32[536870900]); + resetBuffer(); + return data; +} + +export function resetBuffer() { + // Clear buffer and source text strings to allow them to be garbage collected + uint8 = int32 = float64 = sourceText = sourceTextLatin = void 0; +} + +function deserializeProgram(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + program = { + type: "Program", + body: null, + sourceType: deserializeModuleKind(pos + 137), + hashbang: null, + start, + end, + range: [start, end], + }; + program.hashbang = deserializeOptionHashbang(pos + 56); + (program.body = deserializeVecDirective(pos + 88)).push(...deserializeVecStatement(pos + 112)); + return program; +} + +function deserializeExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Expression`); + } +} + +function deserializeIdentifierName(pos) { + let start, end; + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeIdentifierReference(pos) { + let start, end; + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeBindingIdentifier(pos) { + let start, end; + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeLabelIdentifier(pos) { + let start, end; + return { + type: "Identifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeThisExpression(pos) { + let start, end; + return { + type: "ThisExpression", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeArrayExpression(pos) { + let start, + end, + node = { + type: "ArrayExpression", + elements: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.elements = deserializeVecArrayExpressionElement(pos + 16); + return node; +} + +function deserializeArrayExpressionElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + case 65: + return deserializeElision(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ArrayExpressionElement`); + } +} + +function deserializeElision(pos) { + return null; +} + +function deserializeObjectExpression(pos) { + let start, + end, + node = { + type: "ObjectExpression", + properties: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.properties = deserializeVecObjectPropertyKind(pos + 16); + return node; +} + +function deserializeObjectPropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxObjectProperty(pos + 8); + case 1: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ObjectPropertyKind`); + } +} + +function deserializeObjectProperty(pos) { + let start, + end, + node = { + type: "Property", + kind: deserializePropertyKind(pos + 12), + key: null, + value: null, + method: deserializeBool(pos + 13), + shorthand: deserializeBool(pos + 14), + computed: deserializeBool(pos + 15), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeExpression(pos + 32); + return node; +} + +function deserializePropertyKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxIdentifierName(pos + 8); + case 65: + return deserializeBoxPrivateIdentifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKey`); + } +} + +function deserializePropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return "init"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKind`); + } +} + +function deserializeTemplateLiteral(pos) { + let start, + end, + node = { + type: "TemplateLiteral", + quasis: null, + expressions: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.expressions = deserializeVecExpression(pos + 40); + return node; +} + +function deserializeTaggedTemplateExpression(pos) { + let start, + end, + node = { + type: "TaggedTemplateExpression", + tag: null, + quasi: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.tag = deserializeExpression(pos + 16); + node.quasi = deserializeTemplateLiteral(pos + 40); + return node; +} + +function deserializeTemplateElement(pos) { + let tail = deserializeBool(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + value = deserializeTemplateElementValue(pos + 16); + value.cooked !== null && + deserializeBool(pos + 13) && + (value.cooked = value.cooked.replace(/\uFFFD(.{4})/g, (_, hex) => + String.fromCodePoint(parseInt(hex, 16)), + )); + return { + type: "TemplateElement", + value, + tail, + start, + end, + range: [start, end], + }; +} + +function deserializeTemplateElementValue(pos) { + return { + raw: deserializeStr(pos), + cooked: deserializeOptionStr(pos + 16), + }; +} + +function deserializeComputedMemberExpression(pos) { + let start, + end, + node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: true, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeExpression(pos + 32); + return node; +} + +function deserializeStaticMemberExpression(pos) { + let start, + end, + node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializePrivateFieldExpression(pos) { + let start, + end, + node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializePrivateIdentifier(pos + 32); + return node; +} + +function deserializeCallExpression(pos) { + let start, + end, + node = { + type: "CallExpression", + callee: null, + arguments: null, + optional: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.callee = deserializeExpression(pos + 16); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeNewExpression(pos) { + let start, + end, + node = { + type: "NewExpression", + callee: null, + arguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.callee = deserializeExpression(pos + 16); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeMetaProperty(pos) { + let start, + end, + node = { + type: "MetaProperty", + meta: null, + property: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.meta = deserializeIdentifierName(pos + 16); + node.property = deserializeIdentifierName(pos + 48); + return node; +} + +function deserializeSpreadElement(pos) { + let start, + end, + node = { + type: "SpreadElement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeArgument(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Argument`); + } +} + +function deserializeUpdateExpression(pos) { + let start, + end, + node = { + type: "UpdateExpression", + operator: deserializeUpdateOperator(pos + 12), + prefix: deserializeBool(pos + 13), + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeSimpleAssignmentTarget(pos + 16); + return node; +} + +function deserializeUnaryExpression(pos) { + let start, + end, + node = { + type: "UnaryExpression", + operator: deserializeUnaryOperator(pos + 12), + argument: null, + prefix: true, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeBinaryExpression(pos) { + let start, + end, + node = { + type: "BinaryExpression", + left: null, + operator: deserializeBinaryOperator(pos + 12), + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializePrivateInExpression(pos) { + let start, + end, + node = { + type: "BinaryExpression", + left: null, + operator: "in", + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializePrivateIdentifier(pos + 16); + node.right = deserializeExpression(pos + 48); + return node; +} + +function deserializeLogicalExpression(pos) { + let start, + end, + node = { + type: "LogicalExpression", + left: null, + operator: deserializeLogicalOperator(pos + 12), + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeConditionalExpression(pos) { + let start, + end, + node = { + type: "ConditionalExpression", + test: null, + consequent: null, + alternate: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeExpression(pos + 32); + node.alternate = deserializeExpression(pos + 48); + return node; +} + +function deserializeAssignmentExpression(pos) { + let start, + end, + node = { + type: "AssignmentExpression", + operator: deserializeAssignmentOperator(pos + 12), + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTarget`); + } +} + +function deserializeSimpleAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for SimpleAssignmentTarget`); + } +} + +function deserializeArrayAssignmentTarget(pos) { + let start, + end, + node = { + type: "ArrayPattern", + elements: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + elements = deserializeVecOptionAssignmentTargetMaybeDefault(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeObjectAssignmentTarget(pos) { + let start, + end, + node = { + type: "ObjectPattern", + properties: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + properties = deserializeVecAssignmentTargetProperty(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeAssignmentTargetRest(pos) { + let start, + end, + node = { + type: "RestElement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeAssignmentTarget(pos + 16); + return node; +} + +function deserializeAssignmentTargetMaybeDefault(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxAssignmentTargetWithDefault(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetMaybeDefault`); + } +} + +function deserializeAssignmentTargetWithDefault(pos) { + let start, + end, + node = { + type: "AssignmentPattern", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTargetProperty(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxAssignmentTargetPropertyIdentifier(pos + 8); + case 1: + return deserializeBoxAssignmentTargetPropertyProperty(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetProperty`); + } +} + +function deserializeAssignmentTargetPropertyIdentifier(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: true, + computed: false, + start, + end, + range: [start, end], + }, + key = deserializeIdentifierReference(pos + 16), + keyStart, + keyEnd, + value = { + type: "Identifier", + name: key.name, + start: (keyStart = key.start), + end: (keyEnd = key.end), + range: [keyStart, keyEnd], + }, + init = deserializeOptionExpression(pos + 48); + init !== null && + (value = { + type: "AssignmentPattern", + left: value, + right: init, + start, + end, + range: [start, end], + }); + node.key = key; + node.value = value; + return node; +} + +function deserializeAssignmentTargetPropertyProperty(pos) { + let start, + end, + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: false, + computed: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeAssignmentTargetMaybeDefault(pos + 32); + return node; +} + +function deserializeSequenceExpression(pos) { + let start, + end, + node = { + type: "SequenceExpression", + expressions: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expressions = deserializeVecExpression(pos + 16); + return node; +} + +function deserializeSuper(pos) { + let start, end; + return { + type: "Super", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeAwaitExpression(pos) { + let start, + end, + node = { + type: "AwaitExpression", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeChainExpression(pos) { + let start, + end, + node = { + type: "ChainExpression", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeChainElement(pos + 16); + return node; +} + +function deserializeChainElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxCallExpression(pos + 8); + case 1: + return deserializeBoxTSNonNullExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ChainElement`); + } +} + +function deserializeParenthesizedExpression(pos) { + let node; + { + let start, end; + node = { + type: "ParenthesizedExpression", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + } + return node; +} + +function deserializeStatement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBlockStatement(pos + 8); + case 1: + return deserializeBoxBreakStatement(pos + 8); + case 2: + return deserializeBoxContinueStatement(pos + 8); + case 3: + return deserializeBoxDebuggerStatement(pos + 8); + case 4: + return deserializeBoxDoWhileStatement(pos + 8); + case 5: + return deserializeBoxEmptyStatement(pos + 8); + case 6: + return deserializeBoxExpressionStatement(pos + 8); + case 7: + return deserializeBoxForInStatement(pos + 8); + case 8: + return deserializeBoxForOfStatement(pos + 8); + case 9: + return deserializeBoxForStatement(pos + 8); + case 10: + return deserializeBoxIfStatement(pos + 8); + case 11: + return deserializeBoxLabeledStatement(pos + 8); + case 12: + return deserializeBoxReturnStatement(pos + 8); + case 13: + return deserializeBoxSwitchStatement(pos + 8); + case 14: + return deserializeBoxThrowStatement(pos + 8); + case 15: + return deserializeBoxTryStatement(pos + 8); + case 16: + return deserializeBoxWhileStatement(pos + 8); + case 17: + return deserializeBoxWithStatement(pos + 8); + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + case 64: + return deserializeBoxImportDeclaration(pos + 8); + case 65: + return deserializeBoxExportAllDeclaration(pos + 8); + case 66: + return deserializeBoxExportDefaultDeclaration(pos + 8); + case 67: + return deserializeBoxExportNamedDeclaration(pos + 8); + case 68: + return deserializeBoxTSExportAssignment(pos + 8); + case 69: + return deserializeBoxTSNamespaceExportDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Statement`); + } +} + +function deserializeDirective(pos) { + let start, + end, + node = { + type: "ExpressionStatement", + expression: null, + directive: deserializeStr(pos + 64), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeHashbang(pos) { + let start, end; + return { + type: "Hashbang", + value: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeBlockStatement(pos) { + let start, + end, + node = { + type: "BlockStatement", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeDeclaration(pos) { + switch (uint8[pos]) { + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Declaration`); + } +} + +function deserializeVariableDeclaration(pos) { + let start, + end, + node = { + type: "VariableDeclaration", + kind: deserializeVariableDeclarationKind(pos + 12), + declarations: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.declarations = deserializeVecVariableDeclarator(pos + 16); + return node; +} + +function deserializeVariableDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "var"; + case 1: + return "let"; + case 2: + return "const"; + case 3: + return "using"; + case 4: + return "await using"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for VariableDeclarationKind`); + } +} + +function deserializeVariableDeclarator(pos) { + let start, + end, + node = { + type: "VariableDeclarator", + id: null, + init: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingPattern(pos + 16); + node.init = deserializeOptionExpression(pos + 40); + return node; +} + +function deserializeEmptyStatement(pos) { + let start, end; + return { + type: "EmptyStatement", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeExpressionStatement(pos) { + let start, + end, + node = { + type: "ExpressionStatement", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeIfStatement(pos) { + let start, + end, + node = { + type: "IfStatement", + test: null, + consequent: null, + alternate: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeStatement(pos + 32); + node.alternate = deserializeOptionStatement(pos + 48); + return node; +} + +function deserializeDoWhileStatement(pos) { + let start, + end, + node = { + type: "DoWhileStatement", + body: null, + test: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeStatement(pos + 16); + node.test = deserializeExpression(pos + 32); + return node; +} + +function deserializeWhileStatement(pos) { + let start, + end, + node = { + type: "WhileStatement", + test: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeForStatement(pos) { + let start, + end, + node = { + type: "ForStatement", + init: null, + test: null, + update: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.init = deserializeOptionForStatementInit(pos + 16); + node.test = deserializeOptionExpression(pos + 32); + node.update = deserializeOptionExpression(pos + 48); + node.body = deserializeStatement(pos + 64); + return node; +} + +function deserializeForStatementInit(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxVariableDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementInit`); + } +} + +function deserializeForInStatement(pos) { + let start, + end, + node = { + type: "ForInStatement", + left: null, + right: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeForStatementLeft(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxVariableDeclaration(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementLeft`); + } +} + +function deserializeForOfStatement(pos) { + let start, + end, + node = { + type: "ForOfStatement", + await: deserializeBool(pos + 64), + left: null, + right: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeContinueStatement(pos) { + let start, + end, + node = { + type: "ContinueStatement", + label: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeBreakStatement(pos) { + let start, + end, + node = { + type: "BreakStatement", + label: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeReturnStatement(pos) { + let start, + end, + node = { + type: "ReturnStatement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeWithStatement(pos) { + let start, + end, + node = { + type: "WithStatement", + object: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeSwitchStatement(pos) { + let start, + end, + node = { + type: "SwitchStatement", + discriminant: null, + cases: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.discriminant = deserializeExpression(pos + 16); + node.cases = deserializeVecSwitchCase(pos + 32); + return node; +} + +function deserializeSwitchCase(pos) { + let start, + end, + node = { + type: "SwitchCase", + test: null, + consequent: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeOptionExpression(pos + 16); + node.consequent = deserializeVecStatement(pos + 32); + return node; +} + +function deserializeLabeledStatement(pos) { + let start, + end, + node = { + type: "LabeledStatement", + label: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeLabelIdentifier(pos + 16); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeThrowStatement(pos) { + let start, + end, + node = { + type: "ThrowStatement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeTryStatement(pos) { + let start, + end, + node = { + type: "TryStatement", + block: null, + handler: null, + finalizer: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.block = deserializeBoxBlockStatement(pos + 16); + node.handler = deserializeOptionBoxCatchClause(pos + 24); + node.finalizer = deserializeOptionBoxBlockStatement(pos + 32); + return node; +} + +function deserializeCatchClause(pos) { + let start, + end, + node = { + type: "CatchClause", + param: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.param = deserializeOptionCatchParameter(pos + 16); + node.body = deserializeBoxBlockStatement(pos + 56); + return node; +} + +function deserializeCatchParameter(pos) { + return deserializeBindingPattern(pos + 16); +} + +function deserializeDebuggerStatement(pos) { + let start, end; + return { + type: "DebuggerStatement", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeBindingPattern(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBindingIdentifier(pos + 8); + case 1: + return deserializeBoxObjectPattern(pos + 8); + case 2: + return deserializeBoxArrayPattern(pos + 8); + case 3: + return deserializeBoxAssignmentPattern(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BindingPattern`); + } +} + +function deserializeAssignmentPattern(pos) { + let start, + end, + node = { + type: "AssignmentPattern", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeBindingPattern(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeObjectPattern(pos) { + let start, + end, + node = { + type: "ObjectPattern", + properties: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + properties = deserializeVecBindingProperty(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeBindingProperty(pos) { + let start, + end, + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: deserializeBool(pos + 12), + computed: deserializeBool(pos + 13), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeBindingPattern(pos + 32); + return node; +} + +function deserializeArrayPattern(pos) { + let start, + end, + node = { + type: "ArrayPattern", + elements: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + elements = deserializeVecOptionBindingPattern(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeBindingRestElement(pos) { + let start, + end, + node = { + type: "RestElement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeBindingPattern(pos + 16); + return node; +} + +function deserializeFunction(pos) { + let start, + end, + node = { + type: deserializeFunctionType(pos + 88), + id: null, + generator: deserializeBool(pos + 89), + async: deserializeBool(pos + 90), + params: null, + body: null, + expression: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 64); + node.id = deserializeOptionBindingIdentifier(pos + 16); + node.params = params; + node.body = deserializeOptionBoxFunctionBody(pos + 80); + return node; +} + +function deserializeFunctionType(pos) { + switch (uint8[pos]) { + case 0: + return "FunctionDeclaration"; + case 1: + return "FunctionExpression"; + case 2: + return "TSDeclareFunction"; + case 3: + return "TSEmptyBodyFunctionExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for FunctionType`); + } +} + +function deserializeFormalParameters(pos) { + let params = deserializeVecFormalParameter(pos + 16), + restFieldPos32 = (pos >> 2) + 10; + if (int32[restFieldPos32] !== 0 && int32[restFieldPos32 + 1] !== 0) { + pos = int32[restFieldPos32]; + let start, + end, + rest = { + type: "RestElement", + argument: null, + start: (start = deserializeI32(pos + 40)), + end: (end = deserializeI32(pos + 44)), + range: [start, end], + }; + rest.argument = deserializeBindingPattern(pos + 56); + params.push(rest); + } + return params; +} + +function deserializeFormalParameter(pos) { + let param, + initializerFieldPos32 = (pos >> 2) + 16; + if (int32[initializerFieldPos32] !== 0 && int32[initializerFieldPos32 + 1] !== 0) { + let start, end; + param = { + type: "AssignmentPattern", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + param.left = deserializeBindingPattern(pos + 40); + param.right = deserializeOptionBoxExpression(pos + 64); + } else param = deserializeBindingPattern(pos + 40); + return param; +} + +function deserializeFunctionBody(pos) { + let start, + end, + node = { + type: "BlockStatement", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeArrowFunctionExpression(pos) { + let expression = deserializeBool(pos + 48), + start, + end, + node = { + type: "ArrowFunctionExpression", + expression, + async: deserializeBool(pos + 49), + params: null, + body: null, + id: null, + generator: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + body = deserializeBoxFunctionBody(pos + 40); + expression === true && (body = body.body[0].expression); + node.params = deserializeBoxFormalParameters(pos + 24); + node.body = body; + return node; +} + +function deserializeYieldExpression(pos) { + let start, + end, + node = { + type: "YieldExpression", + delegate: deserializeBool(pos + 12), + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeClass(pos) { + let start, + end, + node = { + type: deserializeClassType(pos + 136), + decorators: null, + id: null, + superClass: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.id = deserializeOptionBindingIdentifier(pos + 40); + node.superClass = deserializeOptionExpression(pos + 80); + node.body = deserializeBoxClassBody(pos + 128); + return node; +} + +function deserializeClassType(pos) { + switch (uint8[pos]) { + case 0: + return "ClassDeclaration"; + case 1: + return "ClassExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassType`); + } +} + +function deserializeClassBody(pos) { + let start, + end, + node = { + type: "ClassBody", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecClassElement(pos + 16); + return node; +} + +function deserializeClassElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStaticBlock(pos + 8); + case 1: + return deserializeBoxMethodDefinition(pos + 8); + case 2: + return deserializeBoxPropertyDefinition(pos + 8); + case 3: + return deserializeBoxAccessorProperty(pos + 8); + case 4: + return deserializeBoxTSIndexSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassElement`); + } +} + +function deserializeMethodDefinition(pos) { + let start, + end, + node = { + type: deserializeMethodDefinitionType(pos + 12), + decorators: null, + key: null, + value: null, + kind: deserializeMethodDefinitionKind(pos + 13), + computed: deserializeBool(pos + 14), + static: deserializeBool(pos + 15), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeBoxFunction(pos + 56); + return node; +} + +function deserializeMethodDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "MethodDefinition"; + case 1: + return "TSAbstractMethodDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionType`); + } +} + +function deserializePropertyDefinition(pos) { + let start, + end, + node = { + type: deserializePropertyDefinitionType(pos + 12), + decorators: null, + key: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializePropertyDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "PropertyDefinition"; + case 1: + return "TSAbstractPropertyDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyDefinitionType`); + } +} + +function deserializeMethodDefinitionKind(pos) { + switch (uint8[pos]) { + case 0: + return "constructor"; + case 1: + return "method"; + case 2: + return "get"; + case 3: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionKind`); + } +} + +function deserializePrivateIdentifier(pos) { + let start, end; + return { + type: "PrivateIdentifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeStaticBlock(pos) { + let start, + end, + node = { + type: "StaticBlock", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeAccessorPropertyType(pos) { + switch (uint8[pos]) { + case 0: + return "AccessorProperty"; + case 1: + return "TSAbstractAccessorProperty"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AccessorPropertyType`); + } +} + +function deserializeAccessorProperty(pos) { + let start, + end, + node = { + type: deserializeAccessorPropertyType(pos + 12), + decorators: null, + key: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializeImportExpression(pos) { + let start, + end, + node = { + type: "ImportExpression", + source: null, + options: null, + phase: deserializeOptionImportPhase(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.source = deserializeExpression(pos + 16); + node.options = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeImportDeclaration(pos) { + let start, + end, + node = { + type: "ImportDeclaration", + specifiers: null, + source: null, + phase: deserializeOptionImportPhase(pos + 12), + attributes: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + specifiers = deserializeOptionVecImportDeclarationSpecifier(pos + 16); + specifiers === null && (specifiers = []); + let withClause = deserializeOptionBoxWithClause(pos + 88); + node.specifiers = specifiers; + node.source = deserializeStringLiteral(pos + 40); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeImportPhase(pos) { + switch (uint8[pos]) { + case 0: + return "source"; + case 1: + return "defer"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportPhase`); + } +} + +function deserializeImportDeclarationSpecifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxImportSpecifier(pos + 8); + case 1: + return deserializeBoxImportDefaultSpecifier(pos + 8); + case 2: + return deserializeBoxImportNamespaceSpecifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportDeclarationSpecifier`); + } +} + +function deserializeImportSpecifier(pos) { + let start, + end, + node = { + type: "ImportSpecifier", + imported: null, + local: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.imported = deserializeModuleExportName(pos + 16); + node.local = deserializeBindingIdentifier(pos + 72); + return node; +} + +function deserializeImportDefaultSpecifier(pos) { + let start, + end, + node = { + type: "ImportDefaultSpecifier", + local: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeImportNamespaceSpecifier(pos) { + let start, + end, + node = { + type: "ImportNamespaceSpecifier", + local: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeWithClause(pos) { + return { attributes: deserializeVecImportAttribute(pos + 16) }; +} + +function deserializeImportAttribute(pos) { + let start, + end, + node = { + type: "ImportAttribute", + key: null, + value: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializeImportAttributeKey(pos + 16); + node.value = deserializeStringLiteral(pos + 72); + return node; +} + +function deserializeImportAttributeKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportAttributeKey`); + } +} + +function deserializeExportNamedDeclaration(pos) { + let start, + end, + node = { + type: "ExportNamedDeclaration", + declaration: null, + specifiers: null, + source: null, + attributes: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + withClause = deserializeOptionBoxWithClause(pos + 104); + node.declaration = deserializeOptionDeclaration(pos + 16); + node.specifiers = deserializeVecExportSpecifier(pos + 32); + node.source = deserializeOptionStringLiteral(pos + 56); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportDefaultDeclaration(pos) { + let start, + end, + node = { + type: "ExportDefaultDeclaration", + declaration: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.declaration = deserializeExportDefaultDeclarationKind(pos + 16); + return node; +} + +function deserializeExportAllDeclaration(pos) { + let start, + end, + node = { + type: "ExportAllDeclaration", + exported: null, + source: null, + attributes: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + withClause = deserializeOptionBoxWithClause(pos + 120); + node.exported = deserializeOptionModuleExportName(pos + 16); + node.source = deserializeStringLiteral(pos + 72); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportSpecifier(pos) { + let start, + end, + node = { + type: "ExportSpecifier", + local: null, + exported: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.local = deserializeModuleExportName(pos + 16); + node.exported = deserializeModuleExportName(pos + 72); + return node; +} + +function deserializeExportDefaultDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxFunction(pos + 8); + case 65: + return deserializeBoxClass(pos + 8); + case 66: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportDefaultDeclarationKind`); + } +} + +function deserializeModuleExportName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeIdentifierReference(pos + 8); + case 2: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleExportName`); + } +} + +function deserializeV8IntrinsicExpression(pos) { + let start, + end, + node = { + type: "V8IntrinsicExpression", + name: null, + arguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeIdentifierName(pos + 16); + node.arguments = deserializeVecArgument(pos + 48); + return node; +} + +function deserializeBooleanLiteral(pos) { + let value = deserializeBool(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value, + raw: null, + start, + end, + range: [start, end], + }; + node.raw = start === 0 && end === 0 ? null : value + ""; + return node; +} + +function deserializeNullLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: null, + raw: start === 0 && end === 0 ? null : "null", + start, + end, + range: [start, end], + }; +} + +function deserializeNumericLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: deserializeF64(pos + 32), + raw: + int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + range: [start, end], + }; +} + +function deserializeStringLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + range: [start, end], + }, + value = deserializeStr(pos + 16); + deserializeBool(pos + 12) && + (value = value.replace(/\uFFFD(.{4})/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))); + node.value = value; + return node; +} + +function deserializeBigIntLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + bigint = deserializeStr(pos + 16); + return { + type: "Literal", + value: BigInt(bigint), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + bigint, + start, + end, + range: [start, end], + }; +} + +function deserializeRegExpLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 12] === 0 && int32[(pos >> 2) + 13] === 0 + ? null + : sourceText.slice(start, end), + regex: null, + start, + end, + range: [start, end], + }, + regex = deserializeRegExp(pos + 16), + value = null; + try { + value = new RegExp(regex.pattern, regex.flags); + } catch {} + node.value = value; + node.regex = regex; + return node; +} + +function deserializeRegExp(pos) { + return { + pattern: deserializeStr(pos), + flags: deserializeRegExpFlags(pos + 24), + }; +} + +function deserializeRegExpFlags(pos) { + let flagBits = deserializeU8(pos), + flags = ""; + // Alphabetical order + flagBits & 64 && (flags += "d"); + flagBits & 1 && (flags += "g"); + flagBits & 2 && (flags += "i"); + flagBits & 4 && (flags += "m"); + flagBits & 8 && (flags += "s"); + flagBits & 16 && (flags += "u"); + flagBits & 128 && (flags += "v"); + flagBits & 32 && (flags += "y"); + return flags; +} + +function deserializeJSXElement(pos) { + let start, + end, + node = { + type: "JSXElement", + openingElement: null, + children: null, + closingElement: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + closingElement = deserializeOptionBoxJSXClosingElement(pos + 48), + openingElement = deserializeBoxJSXOpeningElement(pos + 16); + closingElement === null && (openingElement.selfClosing = true); + node.openingElement = openingElement; + node.children = deserializeVecJSXChild(pos + 24); + node.closingElement = closingElement; + return node; +} + +function deserializeJSXOpeningElement(pos) { + let start, + end, + node = { + type: "JSXOpeningElement", + name: null, + attributes: null, + selfClosing: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeJSXElementName(pos + 16); + node.attributes = deserializeVecJSXAttributeItem(pos + 40); + return node; +} + +function deserializeJSXClosingElement(pos) { + let start, + end, + node = { + type: "JSXClosingElement", + name: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeJSXElementName(pos + 16); + return node; +} + +function deserializeJSXFragment(pos) { + let start, + end, + node = { + type: "JSXFragment", + openingFragment: null, + children: null, + closingFragment: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.openingFragment = deserializeJSXOpeningFragment(pos + 16); + node.children = deserializeVecJSXChild(pos + 32); + node.closingFragment = deserializeJSXClosingFragment(pos + 56); + return node; +} + +function deserializeJSXOpeningFragment(pos) { + let start, end; + return { + type: "JSXOpeningFragment", + attributes: [], + selfClosing: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXClosingFragment(pos) { + let start, end; + return { + type: "JSXClosingFragment", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXElementName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + range: ident.range, + }; + case 2: + return deserializeBoxJSXNamespacedName(pos + 8); + case 3: + return deserializeBoxJSXMemberExpression(pos + 8); + case 4: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + range: thisExpr.range, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXElementName`); + } +} + +function deserializeJSXNamespacedName(pos) { + let start, + end, + node = { + type: "JSXNamespacedName", + namespace: null, + name: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.namespace = deserializeJSXIdentifier(pos + 16); + node.name = deserializeJSXIdentifier(pos + 48); + return node; +} + +function deserializeJSXMemberExpression(pos) { + let start, + end, + node = { + type: "JSXMemberExpression", + object: null, + property: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeJSXMemberExpressionObject(pos + 16); + node.property = deserializeJSXIdentifier(pos + 32); + return node; +} + +function deserializeJSXMemberExpressionObject(pos) { + switch (uint8[pos]) { + case 0: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + range: ident.range, + }; + case 1: + return deserializeBoxJSXMemberExpression(pos + 8); + case 2: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + range: thisExpr.range, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXMemberExpressionObject`); + } +} + +function deserializeJSXExpressionContainer(pos) { + let start, + end, + node = { + type: "JSXExpressionContainer", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeJSXExpression(pos + 16); + return node; +} + +function deserializeJSXExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeJSXEmptyExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXExpression`); + } +} + +function deserializeJSXEmptyExpression(pos) { + let start, end; + return { + type: "JSXEmptyExpression", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXAttributeItem(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXAttribute(pos + 8); + case 1: + return deserializeBoxJSXSpreadAttribute(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeItem`); + } +} + +function deserializeJSXAttribute(pos) { + let start, + end, + node = { + type: "JSXAttribute", + name: null, + value: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeJSXAttributeName(pos + 16); + node.value = deserializeOptionJSXAttributeValue(pos + 32); + return node; +} + +function deserializeJSXSpreadAttribute(pos) { + let start, + end, + node = { + type: "JSXSpreadAttribute", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXAttributeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + return deserializeBoxJSXNamespacedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeName`); + } +} + +function deserializeJSXAttributeValue(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStringLiteral(pos + 8); + case 1: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 2: + return deserializeBoxJSXElement(pos + 8); + case 3: + return deserializeBoxJSXFragment(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeValue`); + } +} + +function deserializeJSXIdentifier(pos) { + let start, end; + return { + type: "JSXIdentifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXChild(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXText(pos + 8); + case 1: + return deserializeBoxJSXElement(pos + 8); + case 2: + return deserializeBoxJSXFragment(pos + 8); + case 3: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 4: + return deserializeBoxJSXSpreadChild(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXChild`); + } +} + +function deserializeJSXSpreadChild(pos) { + let start, + end, + node = { + type: "JSXSpreadChild", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXText(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "JSXText", + value: deserializeStr(pos + 16), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + range: [start, end], + }; +} + +function deserializeTSThisParameter(pos) { + let start, + end, + node = { + type: "Identifier", + decorators: [], + name: "this", + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 24); + return node; +} + +function deserializeTSEnumDeclaration(pos) { + let start, + end, + node = { + type: "TSEnumDeclaration", + id: null, + body: null, + const: deserializeBool(pos + 12), + declare: deserializeBool(pos + 13), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.body = deserializeTSEnumBody(pos + 48); + return node; +} + +function deserializeTSEnumBody(pos) { + let start, + end, + node = { + type: "TSEnumBody", + members: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.members = deserializeVecTSEnumMember(pos + 16); + return node; +} + +function deserializeTSEnumMember(pos) { + let start, + end, + node = { + type: "TSEnumMember", + id: null, + initializer: null, + computed: deserializeU8(pos + 16) > 1, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeTSEnumMemberName(pos + 16); + node.initializer = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeTSEnumMemberName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxStringLiteral(pos + 8); + case 2: + return deserializeBoxStringLiteral(pos + 8); + case 3: + return deserializeBoxTemplateLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSEnumMemberName`); + } +} + +function deserializeTSTypeAnnotation(pos) { + let start, + end, + node = { + type: "TSTypeAnnotation", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSLiteralType(pos) { + let start, + end, + node = { + type: "TSLiteralType", + literal: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.literal = deserializeTSLiteral(pos + 16); + return node; +} + +function deserializeTSLiteral(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNumericLiteral(pos + 8); + case 2: + return deserializeBoxBigIntLiteral(pos + 8); + case 3: + return deserializeBoxStringLiteral(pos + 8); + case 4: + return deserializeBoxTemplateLiteral(pos + 8); + case 5: + return deserializeBoxUnaryExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSLiteral`); + } +} + +function deserializeTSType(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSType`); + } +} + +function deserializeTSConditionalType(pos) { + let start, + end, + node = { + type: "TSConditionalType", + checkType: null, + extendsType: null, + trueType: null, + falseType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.checkType = deserializeTSType(pos + 16); + node.extendsType = deserializeTSType(pos + 32); + node.trueType = deserializeTSType(pos + 48); + node.falseType = deserializeTSType(pos + 64); + return node; +} + +function deserializeTSUnionType(pos) { + let start, + end, + node = { + type: "TSUnionType", + types: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSIntersectionType(pos) { + let start, + end, + node = { + type: "TSIntersectionType", + types: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSParenthesizedType(pos) { + let node; + { + let start, end; + node = { + type: "TSParenthesizedType", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + } + return node; +} + +function deserializeTSTypeOperator(pos) { + let start, + end, + node = { + type: "TSTypeOperator", + operator: deserializeTSTypeOperatorOperator(pos + 12), + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTypeOperatorOperator(pos) { + switch (uint8[pos]) { + case 0: + return "keyof"; + case 1: + return "unique"; + case 2: + return "readonly"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeOperatorOperator`); + } +} + +function deserializeTSArrayType(pos) { + let start, + end, + node = { + type: "TSArrayType", + elementType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.elementType = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSIndexedAccessType(pos) { + let start, + end, + node = { + type: "TSIndexedAccessType", + objectType: null, + indexType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.objectType = deserializeTSType(pos + 16); + node.indexType = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTupleType(pos) { + let start, + end, + node = { + type: "TSTupleType", + elementTypes: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.elementTypes = deserializeVecTSTupleElement(pos + 16); + return node; +} + +function deserializeTSNamedTupleMember(pos) { + let start, + end, + node = { + type: "TSNamedTupleMember", + label: null, + elementType: null, + optional: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeIdentifierName(pos + 16); + node.elementType = deserializeTSTupleElement(pos + 48); + return node; +} + +function deserializeTSOptionalType(pos) { + let start, + end, + node = { + type: "TSOptionalType", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSRestType(pos) { + let start, + end, + node = { + type: "TSRestType", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTupleElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + case 64: + return deserializeBoxTSOptionalType(pos + 8); + case 65: + return deserializeBoxTSRestType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTupleElement`); + } +} + +function deserializeTSAnyKeyword(pos) { + let start, end; + return { + type: "TSAnyKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSStringKeyword(pos) { + let start, end; + return { + type: "TSStringKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSBooleanKeyword(pos) { + let start, end; + return { + type: "TSBooleanKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSNumberKeyword(pos) { + let start, end; + return { + type: "TSNumberKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSNeverKeyword(pos) { + let start, end; + return { + type: "TSNeverKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSIntrinsicKeyword(pos) { + let start, end; + return { + type: "TSIntrinsicKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSUnknownKeyword(pos) { + let start, end; + return { + type: "TSUnknownKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSNullKeyword(pos) { + let start, end; + return { + type: "TSNullKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSUndefinedKeyword(pos) { + let start, end; + return { + type: "TSUndefinedKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSVoidKeyword(pos) { + let start, end; + return { + type: "TSVoidKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSSymbolKeyword(pos) { + let start, end; + return { + type: "TSSymbolKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSThisType(pos) { + let start, end; + return { + type: "TSThisType", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSObjectKeyword(pos) { + let start, end; + return { + type: "TSObjectKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSBigIntKeyword(pos) { + let start, end; + return { + type: "TSBigIntKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSTypeReference(pos) { + let start, + end, + node = { + type: "TSTypeReference", + typeName: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeName = deserializeTSTypeName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeName`); + } +} + +function deserializeTSQualifiedName(pos) { + let start, + end, + node = { + type: "TSQualifiedName", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeTSTypeName(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSTypeParameterInstantiation(pos) { + let start, + end, + node = { + type: "TSTypeParameterInstantiation", + params: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.params = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSTypeParameter(pos) { + let start, + end, + node = { + type: "TSTypeParameter", + name: null, + constraint: null, + default: null, + in: deserializeBool(pos + 12), + out: deserializeBool(pos + 13), + const: deserializeBool(pos + 14), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeOptionTSType(pos + 48); + node.default = deserializeOptionTSType(pos + 64); + return node; +} + +function deserializeTSTypeParameterDeclaration(pos) { + let start, + end, + node = { + type: "TSTypeParameterDeclaration", + params: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.params = deserializeVecTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeAliasDeclaration(pos) { + let start, + end, + node = { + type: "TSTypeAliasDeclaration", + id: null, + typeParameters: null, + typeAnnotation: null, + declare: deserializeBool(pos + 72), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.typeAnnotation = deserializeTSType(pos + 56); + return node; +} + +function deserializeTSInterfaceDeclaration(pos) { + let start, + end, + node = { + type: "TSInterfaceDeclaration", + id: null, + typeParameters: null, + extends: null, + body: null, + declare: deserializeBool(pos + 88), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.extends = deserializeVecTSInterfaceHeritage(pos + 56); + node.body = deserializeBoxTSInterfaceBody(pos + 80); + return node; +} + +function deserializeTSInterfaceBody(pos) { + let start, + end, + node = { + type: "TSInterfaceBody", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSPropertySignature(pos) { + let start, + end, + node = { + type: "TSPropertySignature", + computed: deserializeBool(pos + 12), + optional: deserializeBool(pos + 13), + readonly: deserializeBool(pos + 14), + key: null, + typeAnnotation: null, + accessibility: null, + static: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSSignature(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSIndexSignature(pos + 8); + case 1: + return deserializeBoxTSPropertySignature(pos + 8); + case 2: + return deserializeBoxTSCallSignatureDeclaration(pos + 8); + case 3: + return deserializeBoxTSConstructSignatureDeclaration(pos + 8); + case 4: + return deserializeBoxTSMethodSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSSignature`); + } +} + +function deserializeTSIndexSignature(pos) { + let start, + end, + node = { + type: "TSIndexSignature", + parameters: null, + typeAnnotation: null, + readonly: deserializeBool(pos + 12), + static: deserializeBool(pos + 13), + accessibility: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.parameters = deserializeVecTSIndexSignatureName(pos + 16); + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSCallSignatureDeclaration(pos) { + let start, + end, + node = { + type: "TSCallSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSMethodSignatureKind(pos) { + switch (uint8[pos]) { + case 0: + return "method"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMethodSignatureKind`); + } +} + +function deserializeTSMethodSignature(pos) { + let start, + end, + node = { + type: "TSMethodSignature", + key: null, + computed: deserializeBool(pos + 64), + optional: deserializeBool(pos + 65), + kind: deserializeTSMethodSignatureKind(pos + 66), + typeParameters: null, + params: null, + returnType: null, + accessibility: null, + readonly: false, + static: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 48), + thisParam = deserializeOptionBoxTSThisParameter(pos + 40); + thisParam !== null && params.unshift(thisParam); + node.key = deserializePropertyKey(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 32); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 56); + return node; +} + +function deserializeTSConstructSignatureDeclaration(pos) { + let start, + end, + node = { + type: "TSConstructSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSIndexSignatureName(pos) { + let start, + end, + node = { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSInterfaceHeritage(pos) { + let start, + end, + node = { + type: "TSInterfaceHeritage", + expression: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypePredicate(pos) { + let start, + end, + node = { + type: "TSTypePredicate", + parameterName: null, + asserts: deserializeBool(pos + 12), + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.parameterName = deserializeTSTypePredicateName(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSTypePredicateName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeTSThisType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypePredicateName`); + } +} + +function deserializeTSModuleDeclaration(pos) { + let kind = deserializeTSModuleDeclarationKind(pos + 88), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + declare = deserializeBool(pos + 89), + node, + body = deserializeOptionTSModuleDeclarationBody(pos + 72); + if (body === null) { + node = { + type: "TSModuleDeclaration", + id: null, + // No `body` field + kind, + declare, + global: false, + start, + end, + range: [start, end], + }; + node.id = deserializeTSModuleDeclarationName(pos + 16); + } else { + node = { + type: "TSModuleDeclaration", + id: null, + body, + kind, + declare, + global: false, + start, + end, + range: [start, end], + }; + let id = deserializeTSModuleDeclarationName(pos + 16); + if (body.type === "TSModuleBlock") node.id = id; + else { + let innerId = body.id; + if (innerId.type === "Identifier") { + let start, end; + node.id = { + type: "TSQualifiedName", + left: id, + right: innerId, + start: (start = id.start), + end: (end = innerId.end), + range: [start, end], + }; + } else { + // Replace `left` of innermost `TSQualifiedName` with a nested `TSQualifiedName` with `id` of + // this module on left, and previous `left` of innermost `TSQualifiedName` on right + node.id = innerId; + let { start } = id; + for (;;) { + innerId.start = innerId.range[0] = start; + if (innerId.left.type === "Identifier") break; + innerId = innerId.left; + } + let end, + right = innerId.left; + innerId.left = { + type: "TSQualifiedName", + left: id, + right, + start, + end: (end = right.end), + range: [start, end], + }; + } + if (Object.hasOwn(body, "body")) { + body = body.body; + node.body = body; + } else body = null; + } + } + return node; +} + +function deserializeTSModuleDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "module"; + case 1: + return "namespace"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationKind`); + } +} + +function deserializeTSModuleDeclarationName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBindingIdentifier(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationName`); + } +} + +function deserializeTSModuleDeclarationBody(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 1: + return deserializeBoxTSModuleBlock(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationBody`); + } +} + +function deserializeTSGlobalDeclaration(pos) { + let start, + end, + node = { + type: "TSModuleDeclaration", + id: null, + body: null, + kind: "global", + declare: deserializeBool(pos + 88), + global: true, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + keywordStart, + keywordEnd; + node.id = { + type: "Identifier", + name: "global", + start: (keywordStart = deserializeI32(pos + 16)), + end: (keywordEnd = deserializeI32(pos + 20)), + range: [keywordStart, keywordEnd], + }; + node.body = deserializeTSModuleBlock(pos + 24); + return node; +} + +function deserializeTSModuleBlock(pos) { + let start, + end, + node = { + type: "TSModuleBlock", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeTSTypeLiteral(pos) { + let start, + end, + node = { + type: "TSTypeLiteral", + members: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.members = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSInferType(pos) { + let start, + end, + node = { + type: "TSInferType", + typeParameter: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeParameter = deserializeBoxTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeQuery(pos) { + let start, + end, + node = { + type: "TSTypeQuery", + exprName: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.exprName = deserializeTSTypeQueryExprName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeQueryExprName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + case 3: + return deserializeBoxTSImportType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeQueryExprName`); + } +} + +function deserializeTSImportType(pos) { + let start, + end, + node = { + type: "TSImportType", + source: null, + options: null, + qualifier: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.source = deserializeStringLiteral(pos + 16); + node.options = deserializeOptionBoxObjectExpression(pos + 64); + node.qualifier = deserializeOptionTSImportTypeQualifier(pos + 72); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 88); + return node; +} + +function deserializeTSImportTypeQualifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxTSImportTypeQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSImportTypeQualifier`); + } +} + +function deserializeTSImportTypeQualifiedName(pos) { + let start, + end, + node = { + type: "TSQualifiedName", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeTSImportTypeQualifier(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSFunctionType(pos) { + let start, + end, + node = { + type: "TSFunctionType", + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSConstructorType(pos) { + let start, + end, + node = { + type: "TSConstructorType", + abstract: deserializeBool(pos + 40), + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSMappedType(pos) { + let start, + end, + node = { + type: "TSMappedType", + key: null, + constraint: null, + nameType: null, + typeAnnotation: null, + optional: null, + readonly: deserializeOptionTSMappedTypeModifierOperator(pos + 97), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + optional = deserializeOptionTSMappedTypeModifierOperator(pos + 96); + optional === null && (optional = false); + node.key = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeTSType(pos + 48); + node.nameType = deserializeOptionTSType(pos + 64); + node.typeAnnotation = deserializeOptionTSType(pos + 80); + node.optional = optional; + return node; +} + +function deserializeTSMappedTypeModifierOperator(pos) { + switch (uint8[pos]) { + case 0: + return true; + case 1: + return "+"; + case 2: + return "-"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMappedTypeModifierOperator`); + } +} + +function deserializeTSTemplateLiteralType(pos) { + let start, + end, + node = { + type: "TSTemplateLiteralType", + quasis: null, + types: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.types = deserializeVecTSType(pos + 40); + return node; +} + +function deserializeTSAsExpression(pos) { + let start, + end, + node = { + type: "TSAsExpression", + expression: null, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSSatisfiesExpression(pos) { + let start, + end, + node = { + type: "TSSatisfiesExpression", + expression: null, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTypeAssertion(pos) { + let start, + end, + node = { + type: "TSTypeAssertion", + typeAnnotation: null, + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + node.expression = deserializeExpression(pos + 32); + return node; +} + +function deserializeTSImportEqualsDeclaration(pos) { + let start, + end, + node = { + type: "TSImportEqualsDeclaration", + id: null, + moduleReference: null, + importKind: deserializeImportOrExportKind(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.moduleReference = deserializeTSModuleReference(pos + 48); + return node; +} + +function deserializeTSModuleReference(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSExternalModuleReference(pos + 8); + case 1: + return deserializeBoxIdentifierReference(pos + 8); + case 2: + return deserializeBoxTSQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleReference`); + } +} + +function deserializeTSExternalModuleReference(pos) { + let start, + end, + node = { + type: "TSExternalModuleReference", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeTSNonNullExpression(pos) { + let start, + end, + node = { + type: "TSNonNullExpression", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeDecorator(pos) { + let start, + end, + node = { + type: "Decorator", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSExportAssignment(pos) { + let start, + end, + node = { + type: "TSExportAssignment", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSNamespaceExportDeclaration(pos) { + let start, + end, + node = { + type: "TSNamespaceExportDeclaration", + id: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeIdentifierName(pos + 16); + return node; +} + +function deserializeTSInstantiationExpression(pos) { + let start, + end, + node = { + type: "TSInstantiationExpression", + expression: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeImportOrExportKind(pos) { + switch (uint8[pos]) { + case 0: + return "value"; + case 1: + return "type"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportOrExportKind`); + } +} + +function deserializeJSDocNullableType(pos) { + let start, + end, + node = { + type: "TSJSDocNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocNonNullableType(pos) { + let start, + end, + node = { + type: "TSJSDocNonNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocUnknownType(pos) { + let start, end; + return { + type: "TSJSDocUnknownType", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeCommentKind(pos) { + switch (uint8[pos]) { + case 0: + return "Line"; + case 1: + return "Block"; + case 2: + return "Block"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for CommentKind`); + } +} + +function deserializeComment(pos) { + let type = deserializeCommentKind(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type, + value: sourceText.slice(start + 2, end - (type === "Line" ? 0 : 2)), + start, + end, + range: [start, end], + }; +} + +function deserializeModuleKind(pos) { + switch (uint8[pos]) { + case 0: + return "script"; + case 1: + return "module"; + case 3: + return "commonjs"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleKind`); + } +} + +function deserializeSpan(pos) { + return { + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeNameSpan(pos) { + let start, end; + return { + value: deserializeStr(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeImportEntry(pos) { + return { + importName: deserializeImportImportName(pos + 32), + localName: deserializeNameSpan(pos + 64), + isType: deserializeBool(pos + 88), + }; +} + +function deserializeImportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + return { + kind: "NamespaceObject", + name: null, + start: null, + end: null, + range: [null, null], + }; + case 2: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + range: [start, end], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportImportName`); + } +} + +function deserializeExportEntry(pos) { + let start, end; + return { + moduleRequest: deserializeOptionNameSpan(pos + 16), + importName: deserializeExportImportName(pos + 40), + exportName: deserializeExportExportName(pos + 72), + localName: deserializeExportLocalName(pos + 104), + isType: deserializeBool(pos + 136), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeExportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + return { + kind: "All", + name: null, + start: null, + end: null, + range: [null, null], + }; + case 2: + return { + kind: "AllButDefault", + name: null, + start: null, + end: null, + range: [null, null], + }; + case 3: + return { + kind: "None", + name: null, + start: null, + end: null, + range: [null, null], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportImportName`); + } +} + +function deserializeExportExportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + range: [start, end], + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + range: [null, null], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportExportName`); + } +} + +function deserializeExportLocalName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Default", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + range: [null, null], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportLocalName`); + } +} + +function deserializeDynamicImport(pos) { + let start, end; + return { + moduleRequest: deserializeSpan(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeAssignmentOperator(pos) { + switch (uint8[pos]) { + case 0: + return "="; + case 1: + return "+="; + case 2: + return "-="; + case 3: + return "*="; + case 4: + return "/="; + case 5: + return "%="; + case 6: + return "**="; + case 7: + return "<<="; + case 8: + return ">>="; + case 9: + return ">>>="; + case 10: + return "|="; + case 11: + return "^="; + case 12: + return "&="; + case 13: + return "||="; + case 14: + return "&&="; + case 15: + return "??="; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentOperator`); + } +} + +function deserializeBinaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "=="; + case 1: + return "!="; + case 2: + return "==="; + case 3: + return "!=="; + case 4: + return "<"; + case 5: + return "<="; + case 6: + return ">"; + case 7: + return ">="; + case 8: + return "+"; + case 9: + return "-"; + case 10: + return "*"; + case 11: + return "/"; + case 12: + return "%"; + case 13: + return "**"; + case 14: + return "<<"; + case 15: + return ">>"; + case 16: + return ">>>"; + case 17: + return "|"; + case 18: + return "^"; + case 19: + return "&"; + case 20: + return "in"; + case 21: + return "instanceof"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BinaryOperator`); + } +} + +function deserializeLogicalOperator(pos) { + switch (uint8[pos]) { + case 0: + return "||"; + case 1: + return "&&"; + case 2: + return "??"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for LogicalOperator`); + } +} + +function deserializeUnaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "+"; + case 1: + return "-"; + case 2: + return "!"; + case 3: + return "~"; + case 4: + return "typeof"; + case 5: + return "void"; + case 6: + return "delete"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UnaryOperator`); + } +} + +function deserializeUpdateOperator(pos) { + switch (uint8[pos]) { + case 0: + return "++"; + case 1: + return "--"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UpdateOperator`); + } +} + +function deserializeRawTransferData(pos) { + return { + program: deserializeProgram(pos), + comments: deserializeVecComment(pos + 144), + module: deserializeEcmaScriptModule(pos + 168), + errors: deserializeVecError(pos + 272), + }; +} + +function deserializeError(pos) { + return { + severity: deserializeErrorSeverity(pos + 72), + message: deserializeStr(pos), + labels: deserializeVecErrorLabel(pos + 16), + helpMessage: deserializeOptionStr(pos + 40), + codeframe: deserializeStr(pos + 56), + }; +} + +function deserializeErrorSeverity(pos) { + switch (uint8[pos]) { + case 0: + return "Error"; + case 1: + return "Warning"; + case 2: + return "Advice"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ErrorSeverity`); + } +} + +function deserializeErrorLabel(pos) { + let start, end; + return { + message: deserializeOptionStr(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeEcmaScriptModule(pos) { + return { + hasModuleSyntax: deserializeBool(pos + 96), + staticImports: deserializeVecStaticImport(pos), + staticExports: deserializeVecStaticExport(pos + 24), + dynamicImports: deserializeVecDynamicImport(pos + 48), + importMetas: deserializeVecSpan(pos + 72), + }; +} + +function deserializeStaticImport(pos) { + let start, end; + return { + moduleRequest: deserializeNameSpan(pos + 8), + entries: deserializeVecImportEntry(pos + 32), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeStaticExport(pos) { + let start, end; + return { + entries: deserializeVecExportEntry(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeStr(pos) { + let pos32 = pos >> 2, + len = int32[pos32 + 2]; + if (len === 0) return ""; + pos = int32[pos32]; + let end = pos + len; + if (end <= firstNonAsciiPos) return sourceTextLatin.substr(pos, len); + // Use `utf8Slice` for strings longer than 64 bytes + if (len > 64) return utf8Slice.call(uint8, pos, end); + if (pos < sourceEndPos) { + // Check if all bytes are ASCII, use `utf8Slice` if not + for (let i = pos; i < end; i++) if (uint8[i] >= 128) return utf8Slice.call(uint8, pos, end); + // String is all ASCII, so slice from `sourceTextLatin` + return sourceTextLatin.substr(pos, len); + } + // String is not in source region - use `fromCharCode.apply` with a temp array of correct length. + // Copy bytes into temp array. + // If any byte is non-ASCII, use `utf8Slice`. + let arr = stringDecodeArrays[len]; + for (let i = 0; i < len; i++) { + let b = uint8[pos + i]; + if (b >= 128) return utf8Slice.call(uint8, pos, end); + arr[i] = b; + } + // Call `fromCharCode` with temp array + return fromCharCode.apply(null, arr); +} + +function deserializeVecComment(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeComment(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionHashbang(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeHashbang(pos); +} + +function deserializeVecDirective(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeDirective(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecStatement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeStatement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxBooleanLiteral(pos) { + return deserializeBooleanLiteral(int32[pos >> 2]); +} + +function deserializeBoxNullLiteral(pos) { + return deserializeNullLiteral(int32[pos >> 2]); +} + +function deserializeBoxNumericLiteral(pos) { + return deserializeNumericLiteral(int32[pos >> 2]); +} + +function deserializeBoxBigIntLiteral(pos) { + return deserializeBigIntLiteral(int32[pos >> 2]); +} + +function deserializeBoxRegExpLiteral(pos) { + return deserializeRegExpLiteral(int32[pos >> 2]); +} + +function deserializeBoxStringLiteral(pos) { + return deserializeStringLiteral(int32[pos >> 2]); +} + +function deserializeBoxTemplateLiteral(pos) { + return deserializeTemplateLiteral(int32[pos >> 2]); +} + +function deserializeBoxIdentifierReference(pos) { + return deserializeIdentifierReference(int32[pos >> 2]); +} + +function deserializeBoxMetaProperty(pos) { + return deserializeMetaProperty(int32[pos >> 2]); +} + +function deserializeBoxSuper(pos) { + return deserializeSuper(int32[pos >> 2]); +} + +function deserializeBoxArrayExpression(pos) { + return deserializeArrayExpression(int32[pos >> 2]); +} + +function deserializeBoxArrowFunctionExpression(pos) { + return deserializeArrowFunctionExpression(int32[pos >> 2]); +} + +function deserializeBoxAssignmentExpression(pos) { + return deserializeAssignmentExpression(int32[pos >> 2]); +} + +function deserializeBoxAwaitExpression(pos) { + return deserializeAwaitExpression(int32[pos >> 2]); +} + +function deserializeBoxBinaryExpression(pos) { + return deserializeBinaryExpression(int32[pos >> 2]); +} + +function deserializeBoxCallExpression(pos) { + return deserializeCallExpression(int32[pos >> 2]); +} + +function deserializeBoxChainExpression(pos) { + return deserializeChainExpression(int32[pos >> 2]); +} + +function deserializeBoxClass(pos) { + return deserializeClass(int32[pos >> 2]); +} + +function deserializeBoxConditionalExpression(pos) { + return deserializeConditionalExpression(int32[pos >> 2]); +} + +function deserializeBoxFunction(pos) { + return deserializeFunction(int32[pos >> 2]); +} + +function deserializeBoxImportExpression(pos) { + return deserializeImportExpression(int32[pos >> 2]); +} + +function deserializeBoxLogicalExpression(pos) { + return deserializeLogicalExpression(int32[pos >> 2]); +} + +function deserializeBoxNewExpression(pos) { + return deserializeNewExpression(int32[pos >> 2]); +} + +function deserializeBoxObjectExpression(pos) { + return deserializeObjectExpression(int32[pos >> 2]); +} + +function deserializeBoxParenthesizedExpression(pos) { + return deserializeParenthesizedExpression(int32[pos >> 2]); +} + +function deserializeBoxSequenceExpression(pos) { + return deserializeSequenceExpression(int32[pos >> 2]); +} + +function deserializeBoxTaggedTemplateExpression(pos) { + return deserializeTaggedTemplateExpression(int32[pos >> 2]); +} + +function deserializeBoxThisExpression(pos) { + return deserializeThisExpression(int32[pos >> 2]); +} + +function deserializeBoxUnaryExpression(pos) { + return deserializeUnaryExpression(int32[pos >> 2]); +} + +function deserializeBoxUpdateExpression(pos) { + return deserializeUpdateExpression(int32[pos >> 2]); +} + +function deserializeBoxYieldExpression(pos) { + return deserializeYieldExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateInExpression(pos) { + return deserializePrivateInExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXElement(pos) { + return deserializeJSXElement(int32[pos >> 2]); +} + +function deserializeBoxJSXFragment(pos) { + return deserializeJSXFragment(int32[pos >> 2]); +} + +function deserializeBoxTSAsExpression(pos) { + return deserializeTSAsExpression(int32[pos >> 2]); +} + +function deserializeBoxTSSatisfiesExpression(pos) { + return deserializeTSSatisfiesExpression(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAssertion(pos) { + return deserializeTSTypeAssertion(int32[pos >> 2]); +} + +function deserializeBoxTSNonNullExpression(pos) { + return deserializeTSNonNullExpression(int32[pos >> 2]); +} + +function deserializeBoxTSInstantiationExpression(pos) { + return deserializeTSInstantiationExpression(int32[pos >> 2]); +} + +function deserializeBoxV8IntrinsicExpression(pos) { + return deserializeV8IntrinsicExpression(int32[pos >> 2]); +} + +function deserializeVecArrayExpressionElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeArrayExpressionElement(pos)); + pos += 24; + } + return arr; +} + +function deserializeBoxSpreadElement(pos) { + return deserializeSpreadElement(int32[pos >> 2]); +} + +function deserializeVecObjectPropertyKind(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeObjectPropertyKind(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxObjectProperty(pos) { + return deserializeObjectProperty(int32[pos >> 2]); +} + +function deserializeBool(pos) { + return uint8[pos] === 1; +} + +function deserializeBoxIdentifierName(pos) { + return deserializeIdentifierName(int32[pos >> 2]); +} + +function deserializeBoxPrivateIdentifier(pos) { + return deserializePrivateIdentifier(int32[pos >> 2]); +} + +function deserializeVecTemplateElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTemplateElement(pos)); + pos += 48; + } + return arr; +} + +function deserializeVecExpression(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeExpression(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSTypeParameterInstantiation(pos) { + return deserializeTSTypeParameterInstantiation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterInstantiation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterInstantiation(pos); +} + +function deserializeOptionStr(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 ? null : deserializeStr(pos); +} + +function deserializeBoxComputedMemberExpression(pos) { + return deserializeComputedMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxStaticMemberExpression(pos) { + return deserializeStaticMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateFieldExpression(pos) { + return deserializePrivateFieldExpression(int32[pos >> 2]); +} + +function deserializeVecArgument(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeArgument(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxArrayAssignmentTarget(pos) { + return deserializeArrayAssignmentTarget(int32[pos >> 2]); +} + +function deserializeBoxObjectAssignmentTarget(pos) { + return deserializeObjectAssignmentTarget(int32[pos >> 2]); +} + +function deserializeOptionAssignmentTargetMaybeDefault(pos) { + return uint8[pos] === 51 ? null : deserializeAssignmentTargetMaybeDefault(pos); +} + +function deserializeVecOptionAssignmentTargetMaybeDefault(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionAssignmentTargetMaybeDefault(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetRest(pos) { + return deserializeAssignmentTargetRest(int32[pos >> 2]); +} + +function deserializeOptionBoxAssignmentTargetRest(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxAssignmentTargetRest(pos); +} + +function deserializeVecAssignmentTargetProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeAssignmentTargetProperty(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetWithDefault(pos) { + return deserializeAssignmentTargetWithDefault(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyIdentifier(pos) { + return deserializeAssignmentTargetPropertyIdentifier(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyProperty(pos) { + return deserializeAssignmentTargetPropertyProperty(int32[pos >> 2]); +} + +function deserializeOptionExpression(pos) { + return uint8[pos] === 51 ? null : deserializeExpression(pos); +} + +function deserializeBoxBlockStatement(pos) { + return deserializeBlockStatement(int32[pos >> 2]); +} + +function deserializeBoxBreakStatement(pos) { + return deserializeBreakStatement(int32[pos >> 2]); +} + +function deserializeBoxContinueStatement(pos) { + return deserializeContinueStatement(int32[pos >> 2]); +} + +function deserializeBoxDebuggerStatement(pos) { + return deserializeDebuggerStatement(int32[pos >> 2]); +} + +function deserializeBoxDoWhileStatement(pos) { + return deserializeDoWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxEmptyStatement(pos) { + return deserializeEmptyStatement(int32[pos >> 2]); +} + +function deserializeBoxExpressionStatement(pos) { + return deserializeExpressionStatement(int32[pos >> 2]); +} + +function deserializeBoxForInStatement(pos) { + return deserializeForInStatement(int32[pos >> 2]); +} + +function deserializeBoxForOfStatement(pos) { + return deserializeForOfStatement(int32[pos >> 2]); +} + +function deserializeBoxForStatement(pos) { + return deserializeForStatement(int32[pos >> 2]); +} + +function deserializeBoxIfStatement(pos) { + return deserializeIfStatement(int32[pos >> 2]); +} + +function deserializeBoxLabeledStatement(pos) { + return deserializeLabeledStatement(int32[pos >> 2]); +} + +function deserializeBoxReturnStatement(pos) { + return deserializeReturnStatement(int32[pos >> 2]); +} + +function deserializeBoxSwitchStatement(pos) { + return deserializeSwitchStatement(int32[pos >> 2]); +} + +function deserializeBoxThrowStatement(pos) { + return deserializeThrowStatement(int32[pos >> 2]); +} + +function deserializeBoxTryStatement(pos) { + return deserializeTryStatement(int32[pos >> 2]); +} + +function deserializeBoxWhileStatement(pos) { + return deserializeWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxWithStatement(pos) { + return deserializeWithStatement(int32[pos >> 2]); +} + +function deserializeBoxVariableDeclaration(pos) { + return deserializeVariableDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAliasDeclaration(pos) { + return deserializeTSTypeAliasDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSInterfaceDeclaration(pos) { + return deserializeTSInterfaceDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSEnumDeclaration(pos) { + return deserializeTSEnumDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSModuleDeclaration(pos) { + return deserializeTSModuleDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSGlobalDeclaration(pos) { + return deserializeTSGlobalDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSImportEqualsDeclaration(pos) { + return deserializeTSImportEqualsDeclaration(int32[pos >> 2]); +} + +function deserializeVecVariableDeclarator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeVariableDeclarator(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxTSTypeAnnotation(pos) { + return deserializeTSTypeAnnotation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeAnnotation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeAnnotation(pos); +} + +function deserializeOptionStatement(pos) { + return uint8[pos] === 70 ? null : deserializeStatement(pos); +} + +function deserializeOptionForStatementInit(pos) { + return uint8[pos] === 65 ? null : deserializeForStatementInit(pos); +} + +function deserializeOptionLabelIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeLabelIdentifier(pos); +} + +function deserializeVecSwitchCase(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeSwitchCase(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxCatchClause(pos) { + return deserializeCatchClause(int32[pos >> 2]); +} + +function deserializeOptionBoxCatchClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxCatchClause(pos); +} + +function deserializeOptionBoxBlockStatement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBlockStatement(pos); +} + +function deserializeOptionCatchParameter(pos) { + return uint8[pos + 16] === 4 ? null : deserializeCatchParameter(pos); +} + +function deserializeBoxBindingIdentifier(pos) { + return deserializeBindingIdentifier(int32[pos >> 2]); +} + +function deserializeBoxObjectPattern(pos) { + return deserializeObjectPattern(int32[pos >> 2]); +} + +function deserializeBoxArrayPattern(pos) { + return deserializeArrayPattern(int32[pos >> 2]); +} + +function deserializeBoxAssignmentPattern(pos) { + return deserializeAssignmentPattern(int32[pos >> 2]); +} + +function deserializeVecBindingProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeBindingProperty(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxBindingRestElement(pos) { + return deserializeBindingRestElement(int32[pos >> 2]); +} + +function deserializeOptionBoxBindingRestElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBindingRestElement(pos); +} + +function deserializeOptionBindingPattern(pos) { + return uint8[pos] === 4 ? null : deserializeBindingPattern(pos); +} + +function deserializeVecOptionBindingPattern(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionBindingPattern(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionBindingIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeBindingIdentifier(pos); +} + +function deserializeBoxTSTypeParameterDeclaration(pos) { + return deserializeTSTypeParameterDeclaration(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterDeclaration(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterDeclaration(pos); +} + +function deserializeBoxTSThisParameter(pos) { + return deserializeTSThisParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxTSThisParameter(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSThisParameter(pos); +} + +function deserializeBoxFormalParameters(pos) { + return deserializeFormalParameters(int32[pos >> 2]); +} + +function deserializeBoxFunctionBody(pos) { + return deserializeFunctionBody(int32[pos >> 2]); +} + +function deserializeOptionBoxFunctionBody(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxFunctionBody(pos); +} + +function deserializeVecFormalParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 72; + for (; pos !== endPos; ) { + arr.push(deserializeFormalParameter(pos)); + pos += 72; + } + return arr; +} + +function deserializeVecDecorator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeDecorator(pos)); + pos += 32; + } + return arr; +} + +function deserializeBoxExpression(pos) { + return deserializeExpression(int32[pos >> 2]); +} + +function deserializeOptionBoxExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxExpression(pos); +} + +function deserializeBoxClassBody(pos) { + return deserializeClassBody(int32[pos >> 2]); +} + +function deserializeVecClassElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeClassElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxStaticBlock(pos) { + return deserializeStaticBlock(int32[pos >> 2]); +} + +function deserializeBoxMethodDefinition(pos) { + return deserializeMethodDefinition(int32[pos >> 2]); +} + +function deserializeBoxPropertyDefinition(pos) { + return deserializePropertyDefinition(int32[pos >> 2]); +} + +function deserializeBoxAccessorProperty(pos) { + return deserializeAccessorProperty(int32[pos >> 2]); +} + +function deserializeBoxTSIndexSignature(pos) { + return deserializeTSIndexSignature(int32[pos >> 2]); +} + +function deserializeBoxImportDeclaration(pos) { + return deserializeImportDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportAllDeclaration(pos) { + return deserializeExportAllDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportDefaultDeclaration(pos) { + return deserializeExportDefaultDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportNamedDeclaration(pos) { + return deserializeExportNamedDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSExportAssignment(pos) { + return deserializeTSExportAssignment(int32[pos >> 2]); +} + +function deserializeBoxTSNamespaceExportDeclaration(pos) { + return deserializeTSNamespaceExportDeclaration(int32[pos >> 2]); +} + +function deserializeOptionImportPhase(pos) { + return uint8[pos] === 2 ? null : deserializeImportPhase(pos); +} + +function deserializeVecImportDeclarationSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeImportDeclarationSpecifier(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionVecImportDeclarationSpecifier(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeVecImportDeclarationSpecifier(pos); +} + +function deserializeBoxWithClause(pos) { + return deserializeWithClause(int32[pos >> 2]); +} + +function deserializeOptionBoxWithClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxWithClause(pos); +} + +function deserializeBoxImportSpecifier(pos) { + return deserializeImportSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportDefaultSpecifier(pos) { + return deserializeImportDefaultSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportNamespaceSpecifier(pos) { + return deserializeImportNamespaceSpecifier(int32[pos >> 2]); +} + +function deserializeVecImportAttribute(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 120; + for (; pos !== endPos; ) { + arr.push(deserializeImportAttribute(pos)); + pos += 120; + } + return arr; +} + +function deserializeOptionDeclaration(pos) { + return uint8[pos] === 31 ? null : deserializeDeclaration(pos); +} + +function deserializeVecExportSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 7); + for (; pos !== endPos; ) { + arr.push(deserializeExportSpecifier(pos)); + pos += 128; + } + return arr; +} + +function deserializeOptionStringLiteral(pos) { + return uint8[pos + 12] === 2 ? null : deserializeStringLiteral(pos); +} + +function deserializeOptionModuleExportName(pos) { + return uint8[pos] === 3 ? null : deserializeModuleExportName(pos); +} + +function deserializeF64(pos) { + return float64[pos >> 3]; +} + +function deserializeU8(pos) { + return uint8[pos]; +} + +function deserializeBoxJSXOpeningElement(pos) { + return deserializeJSXOpeningElement(int32[pos >> 2]); +} + +function deserializeVecJSXChild(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXChild(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXClosingElement(pos) { + return deserializeJSXClosingElement(int32[pos >> 2]); +} + +function deserializeOptionBoxJSXClosingElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxJSXClosingElement(pos); +} + +function deserializeVecJSXAttributeItem(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXAttributeItem(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXIdentifier(pos) { + return deserializeJSXIdentifier(int32[pos >> 2]); +} + +function deserializeBoxJSXNamespacedName(pos) { + return deserializeJSXNamespacedName(int32[pos >> 2]); +} + +function deserializeBoxJSXMemberExpression(pos) { + return deserializeJSXMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXAttribute(pos) { + return deserializeJSXAttribute(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadAttribute(pos) { + return deserializeJSXSpreadAttribute(int32[pos >> 2]); +} + +function deserializeOptionJSXAttributeValue(pos) { + return uint8[pos] === 4 ? null : deserializeJSXAttributeValue(pos); +} + +function deserializeBoxJSXExpressionContainer(pos) { + return deserializeJSXExpressionContainer(int32[pos >> 2]); +} + +function deserializeBoxJSXText(pos) { + return deserializeJSXText(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadChild(pos) { + return deserializeJSXSpreadChild(int32[pos >> 2]); +} + +function deserializeVecTSEnumMember(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTSEnumMember(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxTSAnyKeyword(pos) { + return deserializeTSAnyKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBigIntKeyword(pos) { + return deserializeTSBigIntKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBooleanKeyword(pos) { + return deserializeTSBooleanKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSIntrinsicKeyword(pos) { + return deserializeTSIntrinsicKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNeverKeyword(pos) { + return deserializeTSNeverKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNullKeyword(pos) { + return deserializeTSNullKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNumberKeyword(pos) { + return deserializeTSNumberKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSObjectKeyword(pos) { + return deserializeTSObjectKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSStringKeyword(pos) { + return deserializeTSStringKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSSymbolKeyword(pos) { + return deserializeTSSymbolKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUndefinedKeyword(pos) { + return deserializeTSUndefinedKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUnknownKeyword(pos) { + return deserializeTSUnknownKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSVoidKeyword(pos) { + return deserializeTSVoidKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSArrayType(pos) { + return deserializeTSArrayType(int32[pos >> 2]); +} + +function deserializeBoxTSConditionalType(pos) { + return deserializeTSConditionalType(int32[pos >> 2]); +} + +function deserializeBoxTSConstructorType(pos) { + return deserializeTSConstructorType(int32[pos >> 2]); +} + +function deserializeBoxTSFunctionType(pos) { + return deserializeTSFunctionType(int32[pos >> 2]); +} + +function deserializeBoxTSImportType(pos) { + return deserializeTSImportType(int32[pos >> 2]); +} + +function deserializeBoxTSIndexedAccessType(pos) { + return deserializeTSIndexedAccessType(int32[pos >> 2]); +} + +function deserializeBoxTSInferType(pos) { + return deserializeTSInferType(int32[pos >> 2]); +} + +function deserializeBoxTSIntersectionType(pos) { + return deserializeTSIntersectionType(int32[pos >> 2]); +} + +function deserializeBoxTSLiteralType(pos) { + return deserializeTSLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSMappedType(pos) { + return deserializeTSMappedType(int32[pos >> 2]); +} + +function deserializeBoxTSNamedTupleMember(pos) { + return deserializeTSNamedTupleMember(int32[pos >> 2]); +} + +function deserializeBoxTSTemplateLiteralType(pos) { + return deserializeTSTemplateLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSThisType(pos) { + return deserializeTSThisType(int32[pos >> 2]); +} + +function deserializeBoxTSTupleType(pos) { + return deserializeTSTupleType(int32[pos >> 2]); +} + +function deserializeBoxTSTypeLiteral(pos) { + return deserializeTSTypeLiteral(int32[pos >> 2]); +} + +function deserializeBoxTSTypeOperator(pos) { + return deserializeTSTypeOperator(int32[pos >> 2]); +} + +function deserializeBoxTSTypePredicate(pos) { + return deserializeTSTypePredicate(int32[pos >> 2]); +} + +function deserializeBoxTSTypeQuery(pos) { + return deserializeTSTypeQuery(int32[pos >> 2]); +} + +function deserializeBoxTSTypeReference(pos) { + return deserializeTSTypeReference(int32[pos >> 2]); +} + +function deserializeBoxTSUnionType(pos) { + return deserializeTSUnionType(int32[pos >> 2]); +} + +function deserializeBoxTSParenthesizedType(pos) { + return deserializeTSParenthesizedType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNullableType(pos) { + return deserializeJSDocNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNonNullableType(pos) { + return deserializeJSDocNonNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocUnknownType(pos) { + return deserializeJSDocUnknownType(int32[pos >> 2]); +} + +function deserializeVecTSType(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSType(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecTSTupleElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSTupleElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSOptionalType(pos) { + return deserializeTSOptionalType(int32[pos >> 2]); +} + +function deserializeBoxTSRestType(pos) { + return deserializeTSRestType(int32[pos >> 2]); +} + +function deserializeBoxTSQualifiedName(pos) { + return deserializeTSQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSType(pos) { + return uint8[pos] === 38 ? null : deserializeTSType(pos); +} + +function deserializeVecTSTypeParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeTSTypeParameter(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecTSInterfaceHeritage(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSInterfaceHeritage(pos)); + pos += 40; + } + return arr; +} + +function deserializeBoxTSInterfaceBody(pos) { + return deserializeTSInterfaceBody(int32[pos >> 2]); +} + +function deserializeVecTSSignature(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSSignature(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSPropertySignature(pos) { + return deserializeTSPropertySignature(int32[pos >> 2]); +} + +function deserializeBoxTSCallSignatureDeclaration(pos) { + return deserializeTSCallSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSConstructSignatureDeclaration(pos) { + return deserializeTSConstructSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSMethodSignature(pos) { + return deserializeTSMethodSignature(int32[pos >> 2]); +} + +function deserializeVecTSIndexSignatureName(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSIndexSignatureName(pos)); + pos += 40; + } + return arr; +} + +function deserializeOptionTSModuleDeclarationBody(pos) { + return uint8[pos] === 2 ? null : deserializeTSModuleDeclarationBody(pos); +} + +function deserializeBoxTSModuleBlock(pos) { + return deserializeTSModuleBlock(int32[pos >> 2]); +} + +function deserializeBoxTSTypeParameter(pos) { + return deserializeTSTypeParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxObjectExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxObjectExpression(pos); +} + +function deserializeOptionTSImportTypeQualifier(pos) { + return uint8[pos] === 2 ? null : deserializeTSImportTypeQualifier(pos); +} + +function deserializeBoxTSImportTypeQualifiedName(pos) { + return deserializeTSImportTypeQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSMappedTypeModifierOperator(pos) { + return uint8[pos] === 3 ? null : deserializeTSMappedTypeModifierOperator(pos); +} + +function deserializeBoxTSExternalModuleReference(pos) { + return deserializeTSExternalModuleReference(int32[pos >> 2]); +} + +function deserializeI32(pos) { + return int32[pos >> 2]; +} + +function deserializeOptionNameSpan(pos) { + return int32[(pos >> 2) + 2] === 0 && int32[(pos >> 2) + 3] === 0 + ? null + : deserializeNameSpan(pos); +} + +function deserializeVecError(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeError(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecErrorLabel(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeErrorLabel(pos)); + pos += 24; + } + return arr; +} + +function deserializeVecStaticImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeStaticImport(pos)); + pos += 56; + } + return arr; +} + +function deserializeVecStaticExport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeStaticExport(pos)); + pos += 32; + } + return arr; +} + +function deserializeVecDynamicImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeDynamicImport(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecSpan(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 3); + for (; pos !== endPos; ) { + arr.push(deserializeSpan(pos)); + pos += 8; + } + return arr; +} + +function deserializeVecImportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 96; + for (; pos !== endPos; ) { + arr.push(deserializeImportEntry(pos)); + pos += 96; + } + return arr; +} + +function deserializeVecExportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 144; + for (; pos !== endPos; ) { + arr.push(deserializeExportEntry(pos)); + pos += 144; + } + return arr; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/ts.js b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/ts.js new file mode 100644 index 0000000000000000000000000000000000000000..89e943459c7e75ebe43da19e511df86ad72317b7 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/ts.js @@ -0,0 +1,6132 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer.rs`. + +let uint8, + int32, + float64, + sourceText, + sourceTextLatin, + sourceEndPos = 0, + firstNonAsciiPos = 0; + +const { fromCharCode } = String, + { utf8Slice, latin1Slice } = Buffer.prototype, + stringDecodeArrays = Array(65).fill(null); +for (let i = 0; i <= 64; i++) stringDecodeArrays[i] = Array(i).fill(0); + +export function deserialize(buffer, sourceText, sourceByteLen) { + sourceEndPos = sourceByteLen; + return deserializeWith(buffer, sourceText, sourceByteLen, deserializeRawTransferData); +} + +function deserializeWith(buffer, sourceTextInput, sourceByteLen, deserialize) { + uint8 = buffer; + int32 = buffer.int32; + float64 = buffer.float64; + sourceText = sourceTextInput; + if (sourceText.length === sourceByteLen) { + firstNonAsciiPos = sourceByteLen; + sourceTextLatin = sourceText; + } else { + let i = 0; + for (; i < sourceByteLen && uint8[i] < 128; i++); + firstNonAsciiPos = i; + sourceTextLatin = latin1Slice.call(uint8, 0, sourceByteLen); + } + let data = deserialize(int32[536870900]); + resetBuffer(); + return data; +} + +export function resetBuffer() { + // Clear buffer and source text strings to allow them to be garbage collected + uint8 = int32 = float64 = sourceText = sourceTextLatin = void 0; +} + +function deserializeProgram(pos) { + let end = deserializeI32(pos + 4), + program = { + type: "Program", + body: null, + sourceType: deserializeModuleKind(pos + 137), + hashbang: null, + start: 0, + end, + }; + program.hashbang = deserializeOptionHashbang(pos + 56); + let body = (program.body = deserializeVecDirective(pos + 88)); + body.push(...deserializeVecStatement(pos + 112)); + { + let start; + if (body.length > 0) { + let first = body[0]; + start = first.start; + if (first.type === "ExportNamedDeclaration" || first.type === "ExportDefaultDeclaration") { + let { declaration } = first; + if ( + declaration !== null && + declaration.type === "ClassDeclaration" && + declaration.decorators.length > 0 + ) { + let decoratorStart = declaration.decorators[0].start; + decoratorStart < start && (start = decoratorStart); + } + } + } else start = end; + program.start = start; + } + return program; +} + +function deserializeExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Expression`); + } +} + +function deserializeIdentifierName(pos) { + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeIdentifierReference(pos) { + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeBindingIdentifier(pos) { + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeLabelIdentifier(pos) { + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeThisExpression(pos) { + return { + type: "ThisExpression", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeArrayExpression(pos) { + let node = { + type: "ArrayExpression", + elements: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.elements = deserializeVecArrayExpressionElement(pos + 16); + return node; +} + +function deserializeArrayExpressionElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + case 65: + return deserializeElision(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ArrayExpressionElement`); + } +} + +function deserializeElision(pos) { + return null; +} + +function deserializeObjectExpression(pos) { + let node = { + type: "ObjectExpression", + properties: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.properties = deserializeVecObjectPropertyKind(pos + 16); + return node; +} + +function deserializeObjectPropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxObjectProperty(pos + 8); + case 1: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ObjectPropertyKind`); + } +} + +function deserializeObjectProperty(pos) { + let node = { + type: "Property", + kind: deserializePropertyKind(pos + 12), + key: null, + value: null, + method: deserializeBool(pos + 13), + shorthand: deserializeBool(pos + 14), + computed: deserializeBool(pos + 15), + optional: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeExpression(pos + 32); + return node; +} + +function deserializePropertyKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxIdentifierName(pos + 8); + case 65: + return deserializeBoxPrivateIdentifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKey`); + } +} + +function deserializePropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return "init"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKind`); + } +} + +function deserializeTemplateLiteral(pos) { + let node = { + type: "TemplateLiteral", + quasis: null, + expressions: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.expressions = deserializeVecExpression(pos + 40); + return node; +} + +function deserializeTaggedTemplateExpression(pos) { + let node = { + type: "TaggedTemplateExpression", + tag: null, + typeArguments: null, + quasi: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.tag = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.quasi = deserializeTemplateLiteral(pos + 40); + return node; +} + +function deserializeTemplateElement(pos) { + let tail = deserializeBool(pos + 12), + start = deserializeI32(pos) - 1, + end = deserializeI32(pos + 4) + 2 - tail, + value = deserializeTemplateElementValue(pos + 16); + value.cooked !== null && + deserializeBool(pos + 13) && + (value.cooked = value.cooked.replace(/\uFFFD(.{4})/g, (_, hex) => + String.fromCodePoint(parseInt(hex, 16)), + )); + return { + type: "TemplateElement", + value, + tail, + start, + end, + }; +} + +function deserializeTemplateElementValue(pos) { + return { + raw: deserializeStr(pos), + cooked: deserializeOptionStr(pos + 16), + }; +} + +function deserializeComputedMemberExpression(pos) { + let node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: true, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeExpression(pos + 32); + return node; +} + +function deserializeStaticMemberExpression(pos) { + let node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializePrivateFieldExpression(pos) { + let node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializePrivateIdentifier(pos + 32); + return node; +} + +function deserializeCallExpression(pos) { + let node = { + type: "CallExpression", + callee: null, + typeArguments: null, + arguments: null, + optional: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.callee = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeNewExpression(pos) { + let node = { + type: "NewExpression", + callee: null, + typeArguments: null, + arguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.callee = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeMetaProperty(pos) { + let node = { + type: "MetaProperty", + meta: null, + property: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.meta = deserializeIdentifierName(pos + 16); + node.property = deserializeIdentifierName(pos + 48); + return node; +} + +function deserializeSpreadElement(pos) { + let node = { + type: "SpreadElement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeArgument(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Argument`); + } +} + +function deserializeUpdateExpression(pos) { + let node = { + type: "UpdateExpression", + operator: deserializeUpdateOperator(pos + 12), + prefix: deserializeBool(pos + 13), + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeSimpleAssignmentTarget(pos + 16); + return node; +} + +function deserializeUnaryExpression(pos) { + let node = { + type: "UnaryExpression", + operator: deserializeUnaryOperator(pos + 12), + argument: null, + prefix: true, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeBinaryExpression(pos) { + let node = { + type: "BinaryExpression", + left: null, + operator: deserializeBinaryOperator(pos + 12), + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializePrivateInExpression(pos) { + let node = { + type: "BinaryExpression", + left: null, + operator: "in", + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializePrivateIdentifier(pos + 16); + node.right = deserializeExpression(pos + 48); + return node; +} + +function deserializeLogicalExpression(pos) { + let node = { + type: "LogicalExpression", + left: null, + operator: deserializeLogicalOperator(pos + 12), + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeConditionalExpression(pos) { + let node = { + type: "ConditionalExpression", + test: null, + consequent: null, + alternate: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeExpression(pos + 32); + node.alternate = deserializeExpression(pos + 48); + return node; +} + +function deserializeAssignmentExpression(pos) { + let node = { + type: "AssignmentExpression", + operator: deserializeAssignmentOperator(pos + 12), + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTarget`); + } +} + +function deserializeSimpleAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for SimpleAssignmentTarget`); + } +} + +function deserializeArrayAssignmentTarget(pos) { + let node = { + type: "ArrayPattern", + decorators: [], + elements: null, + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + elements = deserializeVecOptionAssignmentTargetMaybeDefault(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeObjectAssignmentTarget(pos) { + let node = { + type: "ObjectPattern", + decorators: [], + properties: null, + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + properties = deserializeVecAssignmentTargetProperty(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeAssignmentTargetRest(pos) { + let node = { + type: "RestElement", + decorators: [], + argument: null, + optional: false, + typeAnnotation: null, + value: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeAssignmentTarget(pos + 16); + return node; +} + +function deserializeAssignmentTargetMaybeDefault(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxAssignmentTargetWithDefault(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetMaybeDefault`); + } +} + +function deserializeAssignmentTargetWithDefault(pos) { + let node = { + type: "AssignmentPattern", + decorators: [], + left: null, + right: null, + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTargetProperty(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxAssignmentTargetPropertyIdentifier(pos + 8); + case 1: + return deserializeBoxAssignmentTargetPropertyProperty(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetProperty`); + } +} + +function deserializeAssignmentTargetPropertyIdentifier(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: true, + computed: false, + optional: false, + start, + end, + }, + key = deserializeIdentifierReference(pos + 16), + value = { + type: "Identifier", + decorators: [], + name: key.name, + optional: false, + typeAnnotation: null, + start: key.start, + end: key.end, + }, + init = deserializeOptionExpression(pos + 48); + init !== null && + (value = { + type: "AssignmentPattern", + decorators: [], + left: value, + right: init, + optional: false, + typeAnnotation: null, + start, + end, + }); + node.key = key; + node.value = value; + return node; +} + +function deserializeAssignmentTargetPropertyProperty(pos) { + let node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: false, + computed: deserializeBool(pos + 12), + optional: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeAssignmentTargetMaybeDefault(pos + 32); + return node; +} + +function deserializeSequenceExpression(pos) { + let node = { + type: "SequenceExpression", + expressions: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expressions = deserializeVecExpression(pos + 16); + return node; +} + +function deserializeSuper(pos) { + return { + type: "Super", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeAwaitExpression(pos) { + let node = { + type: "AwaitExpression", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeChainExpression(pos) { + let node = { + type: "ChainExpression", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeChainElement(pos + 16); + return node; +} + +function deserializeChainElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxCallExpression(pos + 8); + case 1: + return deserializeBoxTSNonNullExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ChainElement`); + } +} + +function deserializeParenthesizedExpression(pos) { + let node; + node = { + type: "ParenthesizedExpression", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeStatement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBlockStatement(pos + 8); + case 1: + return deserializeBoxBreakStatement(pos + 8); + case 2: + return deserializeBoxContinueStatement(pos + 8); + case 3: + return deserializeBoxDebuggerStatement(pos + 8); + case 4: + return deserializeBoxDoWhileStatement(pos + 8); + case 5: + return deserializeBoxEmptyStatement(pos + 8); + case 6: + return deserializeBoxExpressionStatement(pos + 8); + case 7: + return deserializeBoxForInStatement(pos + 8); + case 8: + return deserializeBoxForOfStatement(pos + 8); + case 9: + return deserializeBoxForStatement(pos + 8); + case 10: + return deserializeBoxIfStatement(pos + 8); + case 11: + return deserializeBoxLabeledStatement(pos + 8); + case 12: + return deserializeBoxReturnStatement(pos + 8); + case 13: + return deserializeBoxSwitchStatement(pos + 8); + case 14: + return deserializeBoxThrowStatement(pos + 8); + case 15: + return deserializeBoxTryStatement(pos + 8); + case 16: + return deserializeBoxWhileStatement(pos + 8); + case 17: + return deserializeBoxWithStatement(pos + 8); + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + case 64: + return deserializeBoxImportDeclaration(pos + 8); + case 65: + return deserializeBoxExportAllDeclaration(pos + 8); + case 66: + return deserializeBoxExportDefaultDeclaration(pos + 8); + case 67: + return deserializeBoxExportNamedDeclaration(pos + 8); + case 68: + return deserializeBoxTSExportAssignment(pos + 8); + case 69: + return deserializeBoxTSNamespaceExportDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Statement`); + } +} + +function deserializeDirective(pos) { + let node = { + type: "ExpressionStatement", + expression: null, + directive: deserializeStr(pos + 64), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeHashbang(pos) { + return { + type: "Hashbang", + value: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeBlockStatement(pos) { + let node = { + type: "BlockStatement", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeDeclaration(pos) { + switch (uint8[pos]) { + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Declaration`); + } +} + +function deserializeVariableDeclaration(pos) { + let node = { + type: "VariableDeclaration", + kind: deserializeVariableDeclarationKind(pos + 12), + declarations: null, + declare: deserializeBool(pos + 13), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.declarations = deserializeVecVariableDeclarator(pos + 16); + return node; +} + +function deserializeVariableDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "var"; + case 1: + return "let"; + case 2: + return "const"; + case 3: + return "using"; + case 4: + return "await using"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for VariableDeclarationKind`); + } +} + +function deserializeVariableDeclarator(pos) { + let node = { + type: "VariableDeclarator", + id: null, + init: null, + definite: deserializeBool(pos + 13), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + pattern = deserializeBindingPattern(pos + 16); + { + let typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + if (typeAnnotation !== null) { + pattern.typeAnnotation = typeAnnotation; + pattern.end = typeAnnotation.end; + } + } + node.id = pattern; + node.init = deserializeOptionExpression(pos + 40); + return node; +} + +function deserializeEmptyStatement(pos) { + return { + type: "EmptyStatement", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeExpressionStatement(pos) { + let node = { + type: "ExpressionStatement", + expression: null, + directive: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeIfStatement(pos) { + let node = { + type: "IfStatement", + test: null, + consequent: null, + alternate: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeStatement(pos + 32); + node.alternate = deserializeOptionStatement(pos + 48); + return node; +} + +function deserializeDoWhileStatement(pos) { + let node = { + type: "DoWhileStatement", + body: null, + test: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeStatement(pos + 16); + node.test = deserializeExpression(pos + 32); + return node; +} + +function deserializeWhileStatement(pos) { + let node = { + type: "WhileStatement", + test: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeForStatement(pos) { + let node = { + type: "ForStatement", + init: null, + test: null, + update: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.init = deserializeOptionForStatementInit(pos + 16); + node.test = deserializeOptionExpression(pos + 32); + node.update = deserializeOptionExpression(pos + 48); + node.body = deserializeStatement(pos + 64); + return node; +} + +function deserializeForStatementInit(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxVariableDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementInit`); + } +} + +function deserializeForInStatement(pos) { + let node = { + type: "ForInStatement", + left: null, + right: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeForStatementLeft(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxVariableDeclaration(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementLeft`); + } +} + +function deserializeForOfStatement(pos) { + let node = { + type: "ForOfStatement", + await: deserializeBool(pos + 64), + left: null, + right: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeContinueStatement(pos) { + let node = { + type: "ContinueStatement", + label: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeBreakStatement(pos) { + let node = { + type: "BreakStatement", + label: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeReturnStatement(pos) { + let node = { + type: "ReturnStatement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeWithStatement(pos) { + let node = { + type: "WithStatement", + object: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeSwitchStatement(pos) { + let node = { + type: "SwitchStatement", + discriminant: null, + cases: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.discriminant = deserializeExpression(pos + 16); + node.cases = deserializeVecSwitchCase(pos + 32); + return node; +} + +function deserializeSwitchCase(pos) { + let node = { + type: "SwitchCase", + test: null, + consequent: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.test = deserializeOptionExpression(pos + 16); + node.consequent = deserializeVecStatement(pos + 32); + return node; +} + +function deserializeLabeledStatement(pos) { + let node = { + type: "LabeledStatement", + label: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeLabelIdentifier(pos + 16); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeThrowStatement(pos) { + let node = { + type: "ThrowStatement", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeTryStatement(pos) { + let node = { + type: "TryStatement", + block: null, + handler: null, + finalizer: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.block = deserializeBoxBlockStatement(pos + 16); + node.handler = deserializeOptionBoxCatchClause(pos + 24); + node.finalizer = deserializeOptionBoxBlockStatement(pos + 32); + return node; +} + +function deserializeCatchClause(pos) { + let node = { + type: "CatchClause", + param: null, + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.param = deserializeOptionCatchParameter(pos + 16); + node.body = deserializeBoxBlockStatement(pos + 56); + return node; +} + +function deserializeCatchParameter(pos) { + let pattern = deserializeBindingPattern(pos + 16); + { + let typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + pattern.typeAnnotation = typeAnnotation; + typeAnnotation !== null && (pattern.end = typeAnnotation.end); + } + return pattern; +} + +function deserializeDebuggerStatement(pos) { + return { + type: "DebuggerStatement", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeBindingPattern(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBindingIdentifier(pos + 8); + case 1: + return deserializeBoxObjectPattern(pos + 8); + case 2: + return deserializeBoxArrayPattern(pos + 8); + case 3: + return deserializeBoxAssignmentPattern(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BindingPattern`); + } +} + +function deserializeAssignmentPattern(pos) { + let node = { + type: "AssignmentPattern", + decorators: [], + left: null, + right: null, + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeBindingPattern(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeObjectPattern(pos) { + let node = { + type: "ObjectPattern", + decorators: [], + properties: null, + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + properties = deserializeVecBindingProperty(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeBindingProperty(pos) { + let node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: deserializeBool(pos + 12), + computed: deserializeBool(pos + 13), + optional: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeBindingPattern(pos + 32); + return node; +} + +function deserializeArrayPattern(pos) { + let node = { + type: "ArrayPattern", + decorators: [], + elements: null, + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + elements = deserializeVecOptionBindingPattern(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeBindingRestElement(pos) { + let node = { + type: "RestElement", + decorators: [], + argument: null, + optional: false, + typeAnnotation: null, + value: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeBindingPattern(pos + 16); + return node; +} + +function deserializeFunction(pos) { + let node = { + type: deserializeFunctionType(pos + 88), + id: null, + generator: deserializeBool(pos + 89), + async: deserializeBool(pos + 90), + declare: deserializeBool(pos + 91), + typeParameters: null, + params: null, + returnType: null, + body: null, + expression: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 64); + { + let thisParam = deserializeOptionBoxTSThisParameter(pos + 56); + thisParam !== null && params.unshift(thisParam); + } + node.id = deserializeOptionBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 72); + node.body = deserializeOptionBoxFunctionBody(pos + 80); + return node; +} + +function deserializeFunctionType(pos) { + switch (uint8[pos]) { + case 0: + return "FunctionDeclaration"; + case 1: + return "FunctionExpression"; + case 2: + return "TSDeclareFunction"; + case 3: + return "TSEmptyBodyFunctionExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for FunctionType`); + } +} + +function deserializeFormalParameters(pos) { + let params = deserializeVecFormalParameter(pos + 16), + restFieldPos32 = (pos >> 2) + 10; + if (int32[restFieldPos32] !== 0 && int32[restFieldPos32 + 1] !== 0) { + pos = int32[restFieldPos32]; + let end, + rest = { + type: "RestElement", + decorators: [], + argument: null, + optional: false, + typeAnnotation: null, + value: null, + start: deserializeI32(pos + 40), + end: (end = deserializeI32(pos + 44)), + }; + rest.argument = deserializeBindingPattern(pos + 56); + rest.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 72); + if (rest.typeAnnotation !== null) { + end = rest.typeAnnotation.end; + rest.end = end; + } + params.push(rest); + } + return params; +} + +function deserializeFormalParameter(pos) { + let param, + initializerFieldPos32 = (pos >> 2) + 16, + hasInitializer = int32[initializerFieldPos32] !== 0 && int32[initializerFieldPos32 + 1] !== 0; + { + let accessibility = deserializeOptionTSAccessibility(pos + 13), + readonly = deserializeBool(pos + 14), + override = deserializeBool(pos + 15); + if (accessibility === null && !readonly && !override) { + let optional = deserializeBool(pos + 12); + if (hasInitializer) { + param = { + type: "AssignmentPattern", + decorators: null, + left: null, + right: null, + optional, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + param.decorators = deserializeVecDecorator(pos + 16); + param.left = deserializeBindingPattern(pos + 40); + param.left.decorators = []; + param.left.optional = false; + let leftTypeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + param.left.typeAnnotation = leftTypeAnnotation; + leftTypeAnnotation !== null && (param.left.end = leftTypeAnnotation.end); + param.right = deserializeOptionBoxExpression(pos + 64); + } else { + param = deserializeBindingPattern(pos + 40); + param.decorators = deserializeVecDecorator(pos + 16); + param.optional = optional; + let typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + param.typeAnnotation = typeAnnotation; + typeAnnotation === null + ? optional && (param.end = deserializeI32(pos + 4)) + : (param.end = typeAnnotation.end); + } + } else { + param = { + type: "TSParameterProperty", + accessibility, + decorators: null, + override, + parameter: null, + readonly, + static: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + param.decorators = deserializeVecDecorator(pos + 16); + if (hasInitializer) { + let pattern = deserializeBindingPattern(pos + 40), + initializer = deserializeOptionBoxExpression(pos + 64), + assignParam = { + type: "AssignmentPattern", + decorators: [], + left: null, + right: null, + optional: false, + typeAnnotation: null, + start: pattern.start, + end: initializer.end, + }; + assignParam.left = pattern; + pattern.decorators = []; + pattern.optional = false; + let patternTypeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + pattern.typeAnnotation = patternTypeAnnotation; + patternTypeAnnotation !== null && (pattern.end = patternTypeAnnotation.end); + assignParam.right = initializer; + param.parameter = assignParam; + } else { + param.parameter = deserializeBindingPattern(pos + 40); + param.parameter.decorators = []; + let paramOptional = deserializeBool(pos + 12); + param.parameter.optional = paramOptional; + let paramTypeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + param.parameter.typeAnnotation = paramTypeAnnotation; + if (paramTypeAnnotation !== null) param.parameter.end = paramTypeAnnotation.end; + else if (paramOptional) { + let paramEnd = deserializeI32(pos + 4); + param.parameter.end = paramEnd; + } + } + } + } + return param; +} + +function deserializeFunctionBody(pos) { + let node = { + type: "BlockStatement", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeArrowFunctionExpression(pos) { + let expression = deserializeBool(pos + 48), + node = { + type: "ArrowFunctionExpression", + expression, + async: deserializeBool(pos + 49), + typeParameters: null, + params: null, + returnType: null, + body: null, + id: null, + generator: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + body = deserializeBoxFunctionBody(pos + 40); + expression === true && (body = body.body[0].expression); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 32); + node.body = body; + return node; +} + +function deserializeYieldExpression(pos) { + let node = { + type: "YieldExpression", + delegate: deserializeBool(pos + 12), + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeClass(pos) { + let node = { + type: deserializeClassType(pos + 136), + decorators: null, + id: null, + typeParameters: null, + superClass: null, + superTypeArguments: null, + implements: null, + body: null, + abstract: deserializeBool(pos + 137), + declare: deserializeBool(pos + 138), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.id = deserializeOptionBindingIdentifier(pos + 40); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 72); + node.superClass = deserializeOptionExpression(pos + 80); + node.superTypeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 96); + node.implements = deserializeVecTSClassImplements(pos + 104); + node.body = deserializeBoxClassBody(pos + 128); + return node; +} + +function deserializeClassType(pos) { + switch (uint8[pos]) { + case 0: + return "ClassDeclaration"; + case 1: + return "ClassExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassType`); + } +} + +function deserializeClassBody(pos) { + let node = { + type: "ClassBody", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecClassElement(pos + 16); + return node; +} + +function deserializeClassElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStaticBlock(pos + 8); + case 1: + return deserializeBoxMethodDefinition(pos + 8); + case 2: + return deserializeBoxPropertyDefinition(pos + 8); + case 3: + return deserializeBoxAccessorProperty(pos + 8); + case 4: + return deserializeBoxTSIndexSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassElement`); + } +} + +function deserializeMethodDefinition(pos) { + let node = { + type: deserializeMethodDefinitionType(pos + 12), + decorators: null, + key: null, + value: null, + kind: deserializeMethodDefinitionKind(pos + 13), + computed: deserializeBool(pos + 14), + static: deserializeBool(pos + 15), + override: deserializeBool(pos + 64), + optional: deserializeBool(pos + 65), + accessibility: deserializeOptionTSAccessibility(pos + 66), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeBoxFunction(pos + 56); + return node; +} + +function deserializeMethodDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "MethodDefinition"; + case 1: + return "TSAbstractMethodDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionType`); + } +} + +function deserializePropertyDefinition(pos) { + let node = { + type: deserializePropertyDefinitionType(pos + 12), + decorators: null, + key: null, + typeAnnotation: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + declare: deserializeBool(pos + 15), + override: deserializeBool(pos + 80), + optional: deserializeBool(pos + 81), + definite: deserializeBool(pos + 82), + readonly: deserializeBool(pos + 83), + accessibility: deserializeOptionTSAccessibility(pos + 84), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializePropertyDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "PropertyDefinition"; + case 1: + return "TSAbstractPropertyDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyDefinitionType`); + } +} + +function deserializeMethodDefinitionKind(pos) { + switch (uint8[pos]) { + case 0: + return "constructor"; + case 1: + return "method"; + case 2: + return "get"; + case 3: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionKind`); + } +} + +function deserializePrivateIdentifier(pos) { + return { + type: "PrivateIdentifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeStaticBlock(pos) { + let node = { + type: "StaticBlock", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeAccessorPropertyType(pos) { + switch (uint8[pos]) { + case 0: + return "AccessorProperty"; + case 1: + return "TSAbstractAccessorProperty"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AccessorPropertyType`); + } +} + +function deserializeAccessorProperty(pos) { + let node = { + type: deserializeAccessorPropertyType(pos + 12), + decorators: null, + key: null, + typeAnnotation: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + override: deserializeBool(pos + 15), + definite: deserializeBool(pos + 80), + accessibility: deserializeOptionTSAccessibility(pos + 81), + declare: false, + optional: false, + readonly: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializeImportExpression(pos) { + let node = { + type: "ImportExpression", + source: null, + options: null, + phase: deserializeOptionImportPhase(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.source = deserializeExpression(pos + 16); + node.options = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeImportDeclaration(pos) { + let node = { + type: "ImportDeclaration", + specifiers: null, + source: null, + phase: deserializeOptionImportPhase(pos + 12), + attributes: null, + importKind: deserializeImportOrExportKind(pos + 13), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + specifiers = deserializeOptionVecImportDeclarationSpecifier(pos + 16); + specifiers === null && (specifiers = []); + let withClause = deserializeOptionBoxWithClause(pos + 88); + node.specifiers = specifiers; + node.source = deserializeStringLiteral(pos + 40); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeImportPhase(pos) { + switch (uint8[pos]) { + case 0: + return "source"; + case 1: + return "defer"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportPhase`); + } +} + +function deserializeImportDeclarationSpecifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxImportSpecifier(pos + 8); + case 1: + return deserializeBoxImportDefaultSpecifier(pos + 8); + case 2: + return deserializeBoxImportNamespaceSpecifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportDeclarationSpecifier`); + } +} + +function deserializeImportSpecifier(pos) { + let node = { + type: "ImportSpecifier", + imported: null, + local: null, + importKind: deserializeImportOrExportKind(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.imported = deserializeModuleExportName(pos + 16); + node.local = deserializeBindingIdentifier(pos + 72); + return node; +} + +function deserializeImportDefaultSpecifier(pos) { + let node = { + type: "ImportDefaultSpecifier", + local: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeImportNamespaceSpecifier(pos) { + let node = { + type: "ImportNamespaceSpecifier", + local: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeWithClause(pos) { + return { attributes: deserializeVecImportAttribute(pos + 16) }; +} + +function deserializeImportAttribute(pos) { + let node = { + type: "ImportAttribute", + key: null, + value: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializeImportAttributeKey(pos + 16); + node.value = deserializeStringLiteral(pos + 72); + return node; +} + +function deserializeImportAttributeKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportAttributeKey`); + } +} + +function deserializeExportNamedDeclaration(pos) { + let node = { + type: "ExportNamedDeclaration", + declaration: null, + specifiers: null, + source: null, + exportKind: deserializeImportOrExportKind(pos + 12), + attributes: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + withClause = deserializeOptionBoxWithClause(pos + 104); + node.declaration = deserializeOptionDeclaration(pos + 16); + node.specifiers = deserializeVecExportSpecifier(pos + 32); + node.source = deserializeOptionStringLiteral(pos + 56); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportDefaultDeclaration(pos) { + let node = { + type: "ExportDefaultDeclaration", + declaration: null, + exportKind: "value", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.declaration = deserializeExportDefaultDeclarationKind(pos + 16); + return node; +} + +function deserializeExportAllDeclaration(pos) { + let node = { + type: "ExportAllDeclaration", + exported: null, + source: null, + attributes: null, + exportKind: deserializeImportOrExportKind(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + withClause = deserializeOptionBoxWithClause(pos + 120); + node.exported = deserializeOptionModuleExportName(pos + 16); + node.source = deserializeStringLiteral(pos + 72); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportSpecifier(pos) { + let node = { + type: "ExportSpecifier", + local: null, + exported: null, + exportKind: deserializeImportOrExportKind(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.local = deserializeModuleExportName(pos + 16); + node.exported = deserializeModuleExportName(pos + 72); + return node; +} + +function deserializeExportDefaultDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxFunction(pos + 8); + case 65: + return deserializeBoxClass(pos + 8); + case 66: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportDefaultDeclarationKind`); + } +} + +function deserializeModuleExportName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeIdentifierReference(pos + 8); + case 2: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleExportName`); + } +} + +function deserializeV8IntrinsicExpression(pos) { + let node = { + type: "V8IntrinsicExpression", + name: null, + arguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeIdentifierName(pos + 16); + node.arguments = deserializeVecArgument(pos + 48); + return node; +} + +function deserializeBooleanLiteral(pos) { + let value = deserializeBool(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value, + raw: null, + start, + end, + }; + node.raw = start === 0 && end === 0 ? null : value + ""; + return node; +} + +function deserializeNullLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: null, + raw: start === 0 && end === 0 ? null : "null", + start, + end, + }; +} + +function deserializeNumericLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: deserializeF64(pos + 32), + raw: + int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + }; +} + +function deserializeStringLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + }, + value = deserializeStr(pos + 16); + deserializeBool(pos + 12) && + (value = value.replace(/\uFFFD(.{4})/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))); + node.value = value; + return node; +} + +function deserializeBigIntLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + bigint = deserializeStr(pos + 16); + return { + type: "Literal", + value: BigInt(bigint), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + bigint, + start, + end, + }; +} + +function deserializeRegExpLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 12] === 0 && int32[(pos >> 2) + 13] === 0 + ? null + : sourceText.slice(start, end), + regex: null, + start, + end, + }, + regex = deserializeRegExp(pos + 16), + value = null; + try { + value = new RegExp(regex.pattern, regex.flags); + } catch {} + node.value = value; + node.regex = regex; + return node; +} + +function deserializeRegExp(pos) { + return { + pattern: deserializeStr(pos), + flags: deserializeRegExpFlags(pos + 24), + }; +} + +function deserializeRegExpFlags(pos) { + let flagBits = deserializeU8(pos), + flags = ""; + // Alphabetical order + flagBits & 64 && (flags += "d"); + flagBits & 1 && (flags += "g"); + flagBits & 2 && (flags += "i"); + flagBits & 4 && (flags += "m"); + flagBits & 8 && (flags += "s"); + flagBits & 16 && (flags += "u"); + flagBits & 128 && (flags += "v"); + flagBits & 32 && (flags += "y"); + return flags; +} + +function deserializeJSXElement(pos) { + let node = { + type: "JSXElement", + openingElement: null, + children: null, + closingElement: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + closingElement = deserializeOptionBoxJSXClosingElement(pos + 48), + openingElement = deserializeBoxJSXOpeningElement(pos + 16); + closingElement === null && (openingElement.selfClosing = true); + node.openingElement = openingElement; + node.children = deserializeVecJSXChild(pos + 24); + node.closingElement = closingElement; + return node; +} + +function deserializeJSXOpeningElement(pos) { + let node = { + type: "JSXOpeningElement", + name: null, + typeArguments: null, + attributes: null, + selfClosing: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeJSXElementName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.attributes = deserializeVecJSXAttributeItem(pos + 40); + return node; +} + +function deserializeJSXClosingElement(pos) { + let node = { + type: "JSXClosingElement", + name: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeJSXElementName(pos + 16); + return node; +} + +function deserializeJSXFragment(pos) { + let node = { + type: "JSXFragment", + openingFragment: null, + children: null, + closingFragment: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.openingFragment = deserializeJSXOpeningFragment(pos + 16); + node.children = deserializeVecJSXChild(pos + 32); + node.closingFragment = deserializeJSXClosingFragment(pos + 56); + return node; +} + +function deserializeJSXOpeningFragment(pos) { + return { + type: "JSXOpeningFragment", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXClosingFragment(pos) { + return { + type: "JSXClosingFragment", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXElementName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + }; + case 2: + return deserializeBoxJSXNamespacedName(pos + 8); + case 3: + return deserializeBoxJSXMemberExpression(pos + 8); + case 4: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXElementName`); + } +} + +function deserializeJSXNamespacedName(pos) { + let node = { + type: "JSXNamespacedName", + namespace: null, + name: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.namespace = deserializeJSXIdentifier(pos + 16); + node.name = deserializeJSXIdentifier(pos + 48); + return node; +} + +function deserializeJSXMemberExpression(pos) { + let node = { + type: "JSXMemberExpression", + object: null, + property: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.object = deserializeJSXMemberExpressionObject(pos + 16); + node.property = deserializeJSXIdentifier(pos + 32); + return node; +} + +function deserializeJSXMemberExpressionObject(pos) { + switch (uint8[pos]) { + case 0: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + }; + case 1: + return deserializeBoxJSXMemberExpression(pos + 8); + case 2: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXMemberExpressionObject`); + } +} + +function deserializeJSXExpressionContainer(pos) { + let node = { + type: "JSXExpressionContainer", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeJSXExpression(pos + 16); + return node; +} + +function deserializeJSXExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeJSXEmptyExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXExpression`); + } +} + +function deserializeJSXEmptyExpression(pos) { + return { + type: "JSXEmptyExpression", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXAttributeItem(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXAttribute(pos + 8); + case 1: + return deserializeBoxJSXSpreadAttribute(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeItem`); + } +} + +function deserializeJSXAttribute(pos) { + let node = { + type: "JSXAttribute", + name: null, + value: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeJSXAttributeName(pos + 16); + node.value = deserializeOptionJSXAttributeValue(pos + 32); + return node; +} + +function deserializeJSXSpreadAttribute(pos) { + let node = { + type: "JSXSpreadAttribute", + argument: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXAttributeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + return deserializeBoxJSXNamespacedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeName`); + } +} + +function deserializeJSXAttributeValue(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStringLiteral(pos + 8); + case 1: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 2: + return deserializeBoxJSXElement(pos + 8); + case 3: + return deserializeBoxJSXFragment(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeValue`); + } +} + +function deserializeJSXIdentifier(pos) { + return { + type: "JSXIdentifier", + name: deserializeStr(pos + 16), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeJSXChild(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXText(pos + 8); + case 1: + return deserializeBoxJSXElement(pos + 8); + case 2: + return deserializeBoxJSXFragment(pos + 8); + case 3: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 4: + return deserializeBoxJSXSpreadChild(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXChild`); + } +} + +function deserializeJSXSpreadChild(pos) { + let node = { + type: "JSXSpreadChild", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXText(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "JSXText", + value: deserializeStr(pos + 16), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + }; +} + +function deserializeTSThisParameter(pos) { + let node = { + type: "Identifier", + decorators: [], + name: "this", + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 24); + return node; +} + +function deserializeTSEnumDeclaration(pos) { + let node = { + type: "TSEnumDeclaration", + id: null, + body: null, + const: deserializeBool(pos + 12), + declare: deserializeBool(pos + 13), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.body = deserializeTSEnumBody(pos + 48); + return node; +} + +function deserializeTSEnumBody(pos) { + let node = { + type: "TSEnumBody", + members: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.members = deserializeVecTSEnumMember(pos + 16); + return node; +} + +function deserializeTSEnumMember(pos) { + let node = { + type: "TSEnumMember", + id: null, + initializer: null, + computed: deserializeU8(pos + 16) > 1, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeTSEnumMemberName(pos + 16); + node.initializer = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeTSEnumMemberName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxStringLiteral(pos + 8); + case 2: + return deserializeBoxStringLiteral(pos + 8); + case 3: + return deserializeBoxTemplateLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSEnumMemberName`); + } +} + +function deserializeTSTypeAnnotation(pos) { + let node = { + type: "TSTypeAnnotation", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSLiteralType(pos) { + let node = { + type: "TSLiteralType", + literal: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.literal = deserializeTSLiteral(pos + 16); + return node; +} + +function deserializeTSLiteral(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNumericLiteral(pos + 8); + case 2: + return deserializeBoxBigIntLiteral(pos + 8); + case 3: + return deserializeBoxStringLiteral(pos + 8); + case 4: + return deserializeBoxTemplateLiteral(pos + 8); + case 5: + return deserializeBoxUnaryExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSLiteral`); + } +} + +function deserializeTSType(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSType`); + } +} + +function deserializeTSConditionalType(pos) { + let node = { + type: "TSConditionalType", + checkType: null, + extendsType: null, + trueType: null, + falseType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.checkType = deserializeTSType(pos + 16); + node.extendsType = deserializeTSType(pos + 32); + node.trueType = deserializeTSType(pos + 48); + node.falseType = deserializeTSType(pos + 64); + return node; +} + +function deserializeTSUnionType(pos) { + let node = { + type: "TSUnionType", + types: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSIntersectionType(pos) { + let node = { + type: "TSIntersectionType", + types: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSParenthesizedType(pos) { + let node; + node = { + type: "TSParenthesizedType", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTypeOperator(pos) { + let node = { + type: "TSTypeOperator", + operator: deserializeTSTypeOperatorOperator(pos + 12), + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTypeOperatorOperator(pos) { + switch (uint8[pos]) { + case 0: + return "keyof"; + case 1: + return "unique"; + case 2: + return "readonly"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeOperatorOperator`); + } +} + +function deserializeTSArrayType(pos) { + let node = { + type: "TSArrayType", + elementType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.elementType = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSIndexedAccessType(pos) { + let node = { + type: "TSIndexedAccessType", + objectType: null, + indexType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.objectType = deserializeTSType(pos + 16); + node.indexType = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTupleType(pos) { + let node = { + type: "TSTupleType", + elementTypes: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.elementTypes = deserializeVecTSTupleElement(pos + 16); + return node; +} + +function deserializeTSNamedTupleMember(pos) { + let node = { + type: "TSNamedTupleMember", + label: null, + elementType: null, + optional: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.label = deserializeIdentifierName(pos + 16); + node.elementType = deserializeTSTupleElement(pos + 48); + return node; +} + +function deserializeTSOptionalType(pos) { + let node = { + type: "TSOptionalType", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSRestType(pos) { + let node = { + type: "TSRestType", + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTupleElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + case 64: + return deserializeBoxTSOptionalType(pos + 8); + case 65: + return deserializeBoxTSRestType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTupleElement`); + } +} + +function deserializeTSAnyKeyword(pos) { + return { + type: "TSAnyKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSStringKeyword(pos) { + return { + type: "TSStringKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSBooleanKeyword(pos) { + return { + type: "TSBooleanKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSNumberKeyword(pos) { + return { + type: "TSNumberKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSNeverKeyword(pos) { + return { + type: "TSNeverKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSIntrinsicKeyword(pos) { + return { + type: "TSIntrinsicKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSUnknownKeyword(pos) { + return { + type: "TSUnknownKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSNullKeyword(pos) { + return { + type: "TSNullKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSUndefinedKeyword(pos) { + return { + type: "TSUndefinedKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSVoidKeyword(pos) { + return { + type: "TSVoidKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSSymbolKeyword(pos) { + return { + type: "TSSymbolKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSThisType(pos) { + return { + type: "TSThisType", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSObjectKeyword(pos) { + return { + type: "TSObjectKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSBigIntKeyword(pos) { + return { + type: "TSBigIntKeyword", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeTSTypeReference(pos) { + let node = { + type: "TSTypeReference", + typeName: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeName = deserializeTSTypeName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeName`); + } +} + +function deserializeTSQualifiedName(pos) { + let node = { + type: "TSQualifiedName", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeTSTypeName(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSTypeParameterInstantiation(pos) { + let node = { + type: "TSTypeParameterInstantiation", + params: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.params = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSTypeParameter(pos) { + let node = { + type: "TSTypeParameter", + name: null, + constraint: null, + default: null, + in: deserializeBool(pos + 12), + out: deserializeBool(pos + 13), + const: deserializeBool(pos + 14), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.name = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeOptionTSType(pos + 48); + node.default = deserializeOptionTSType(pos + 64); + return node; +} + +function deserializeTSTypeParameterDeclaration(pos) { + let node = { + type: "TSTypeParameterDeclaration", + params: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.params = deserializeVecTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeAliasDeclaration(pos) { + let node = { + type: "TSTypeAliasDeclaration", + id: null, + typeParameters: null, + typeAnnotation: null, + declare: deserializeBool(pos + 72), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.typeAnnotation = deserializeTSType(pos + 56); + return node; +} + +function deserializeTSAccessibility(pos) { + switch (uint8[pos]) { + case 0: + return "private"; + case 1: + return "protected"; + case 2: + return "public"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSAccessibility`); + } +} + +function deserializeTSClassImplements(pos) { + let node = { + type: "TSClassImplements", + expression: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + expression = deserializeTSTypeName(pos + 16); + if (expression.type === "TSQualifiedName") { + let object = expression.left, + { right } = expression, + previous = (expression = { + type: "MemberExpression", + object, + property: right, + optional: false, + computed: false, + start: expression.start, + end: expression.end, + }); + for (; object.type === "TSQualifiedName"; ) { + let { left, right } = object; + previous = previous.object = { + type: "MemberExpression", + object: left, + property: right, + optional: false, + computed: false, + start: object.start, + end: object.end, + }; + object = left; + } + } + node.expression = expression; + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSInterfaceDeclaration(pos) { + let node = { + type: "TSInterfaceDeclaration", + id: null, + typeParameters: null, + extends: null, + body: null, + declare: deserializeBool(pos + 88), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.extends = deserializeVecTSInterfaceHeritage(pos + 56); + node.body = deserializeBoxTSInterfaceBody(pos + 80); + return node; +} + +function deserializeTSInterfaceBody(pos) { + let node = { + type: "TSInterfaceBody", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.body = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSPropertySignature(pos) { + let node = { + type: "TSPropertySignature", + computed: deserializeBool(pos + 12), + optional: deserializeBool(pos + 13), + readonly: deserializeBool(pos + 14), + key: null, + typeAnnotation: null, + accessibility: null, + static: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.key = deserializePropertyKey(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSSignature(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSIndexSignature(pos + 8); + case 1: + return deserializeBoxTSPropertySignature(pos + 8); + case 2: + return deserializeBoxTSCallSignatureDeclaration(pos + 8); + case 3: + return deserializeBoxTSConstructSignatureDeclaration(pos + 8); + case 4: + return deserializeBoxTSMethodSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSSignature`); + } +} + +function deserializeTSIndexSignature(pos) { + let node = { + type: "TSIndexSignature", + parameters: null, + typeAnnotation: null, + readonly: deserializeBool(pos + 12), + static: deserializeBool(pos + 13), + accessibility: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.parameters = deserializeVecTSIndexSignatureName(pos + 16); + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSCallSignatureDeclaration(pos) { + let node = { + type: "TSCallSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSMethodSignatureKind(pos) { + switch (uint8[pos]) { + case 0: + return "method"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMethodSignatureKind`); + } +} + +function deserializeTSMethodSignature(pos) { + let node = { + type: "TSMethodSignature", + key: null, + computed: deserializeBool(pos + 64), + optional: deserializeBool(pos + 65), + kind: deserializeTSMethodSignatureKind(pos + 66), + typeParameters: null, + params: null, + returnType: null, + accessibility: null, + readonly: false, + static: false, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 48), + thisParam = deserializeOptionBoxTSThisParameter(pos + 40); + thisParam !== null && params.unshift(thisParam); + node.key = deserializePropertyKey(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 32); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 56); + return node; +} + +function deserializeTSConstructSignatureDeclaration(pos) { + let node = { + type: "TSConstructSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSIndexSignatureName(pos) { + let node = { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSInterfaceHeritage(pos) { + let node = { + type: "TSInterfaceHeritage", + expression: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypePredicate(pos) { + let node = { + type: "TSTypePredicate", + parameterName: null, + asserts: deserializeBool(pos + 12), + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.parameterName = deserializeTSTypePredicateName(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSTypePredicateName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeTSThisType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypePredicateName`); + } +} + +function deserializeTSModuleDeclaration(pos) { + let kind = deserializeTSModuleDeclarationKind(pos + 88), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + declare = deserializeBool(pos + 89), + node, + body = deserializeOptionTSModuleDeclarationBody(pos + 72); + if (body === null) { + node = { + type: "TSModuleDeclaration", + id: null, + // No `body` field + kind, + declare, + global: false, + start, + end, + }; + node.id = deserializeTSModuleDeclarationName(pos + 16); + } else { + node = { + type: "TSModuleDeclaration", + id: null, + body, + kind, + declare, + global: false, + start, + end, + }; + let id = deserializeTSModuleDeclarationName(pos + 16); + if (body.type === "TSModuleBlock") node.id = id; + else { + let innerId = body.id; + if (innerId.type === "Identifier") + node.id = { + type: "TSQualifiedName", + left: id, + right: innerId, + start: id.start, + end: innerId.end, + }; + else { + // Replace `left` of innermost `TSQualifiedName` with a nested `TSQualifiedName` with `id` of + // this module on left, and previous `left` of innermost `TSQualifiedName` on right + node.id = innerId; + let { start } = id; + for (;;) { + innerId.start = start; + if (innerId.left.type === "Identifier") break; + innerId = innerId.left; + } + let right = innerId.left; + innerId.left = { + type: "TSQualifiedName", + left: id, + right, + start, + end: right.end, + }; + } + if (Object.hasOwn(body, "body")) { + body = body.body; + node.body = body; + } else body = null; + } + } + return node; +} + +function deserializeTSModuleDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "module"; + case 1: + return "namespace"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationKind`); + } +} + +function deserializeTSModuleDeclarationName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBindingIdentifier(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationName`); + } +} + +function deserializeTSModuleDeclarationBody(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 1: + return deserializeBoxTSModuleBlock(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationBody`); + } +} + +function deserializeTSGlobalDeclaration(pos) { + let node = { + type: "TSModuleDeclaration", + id: null, + body: null, + kind: "global", + declare: deserializeBool(pos + 88), + global: true, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = { + type: "Identifier", + decorators: [], + name: "global", + optional: false, + typeAnnotation: null, + start: deserializeI32(pos + 16), + end: deserializeI32(pos + 20), + }; + node.body = deserializeTSModuleBlock(pos + 24); + return node; +} + +function deserializeTSModuleBlock(pos) { + let node = { + type: "TSModuleBlock", + body: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeTSTypeLiteral(pos) { + let node = { + type: "TSTypeLiteral", + members: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.members = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSInferType(pos) { + let node = { + type: "TSInferType", + typeParameter: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeParameter = deserializeBoxTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeQuery(pos) { + let node = { + type: "TSTypeQuery", + exprName: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.exprName = deserializeTSTypeQueryExprName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeQueryExprName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + case 3: + return deserializeBoxTSImportType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeQueryExprName`); + } +} + +function deserializeTSImportType(pos) { + let node = { + type: "TSImportType", + source: null, + options: null, + qualifier: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.source = deserializeStringLiteral(pos + 16); + node.options = deserializeOptionBoxObjectExpression(pos + 64); + node.qualifier = deserializeOptionTSImportTypeQualifier(pos + 72); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 88); + return node; +} + +function deserializeTSImportTypeQualifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxTSImportTypeQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSImportTypeQualifier`); + } +} + +function deserializeTSImportTypeQualifiedName(pos) { + let node = { + type: "TSQualifiedName", + left: null, + right: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.left = deserializeTSImportTypeQualifier(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSFunctionType(pos) { + let node = { + type: "TSFunctionType", + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSConstructorType(pos) { + let node = { + type: "TSConstructorType", + abstract: deserializeBool(pos + 40), + typeParameters: null, + params: null, + returnType: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSMappedType(pos) { + let node = { + type: "TSMappedType", + key: null, + constraint: null, + nameType: null, + typeAnnotation: null, + optional: null, + readonly: deserializeOptionTSMappedTypeModifierOperator(pos + 97), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }, + optional = deserializeOptionTSMappedTypeModifierOperator(pos + 96); + optional === null && (optional = false); + node.key = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeTSType(pos + 48); + node.nameType = deserializeOptionTSType(pos + 64); + node.typeAnnotation = deserializeOptionTSType(pos + 80); + node.optional = optional; + return node; +} + +function deserializeTSMappedTypeModifierOperator(pos) { + switch (uint8[pos]) { + case 0: + return true; + case 1: + return "+"; + case 2: + return "-"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMappedTypeModifierOperator`); + } +} + +function deserializeTSTemplateLiteralType(pos) { + let node = { + type: "TSTemplateLiteralType", + quasis: null, + types: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.types = deserializeVecTSType(pos + 40); + return node; +} + +function deserializeTSAsExpression(pos) { + let node = { + type: "TSAsExpression", + expression: null, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSSatisfiesExpression(pos) { + let node = { + type: "TSSatisfiesExpression", + expression: null, + typeAnnotation: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTypeAssertion(pos) { + let node = { + type: "TSTypeAssertion", + typeAnnotation: null, + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + node.expression = deserializeExpression(pos + 32); + return node; +} + +function deserializeTSImportEqualsDeclaration(pos) { + let node = { + type: "TSImportEqualsDeclaration", + id: null, + moduleReference: null, + importKind: deserializeImportOrExportKind(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.moduleReference = deserializeTSModuleReference(pos + 48); + return node; +} + +function deserializeTSModuleReference(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSExternalModuleReference(pos + 8); + case 1: + return deserializeBoxIdentifierReference(pos + 8); + case 2: + return deserializeBoxTSQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleReference`); + } +} + +function deserializeTSExternalModuleReference(pos) { + let node = { + type: "TSExternalModuleReference", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeTSNonNullExpression(pos) { + let node = { + type: "TSNonNullExpression", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeDecorator(pos) { + let node = { + type: "Decorator", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSExportAssignment(pos) { + let node = { + type: "TSExportAssignment", + expression: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSNamespaceExportDeclaration(pos) { + let node = { + type: "TSNamespaceExportDeclaration", + id: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.id = deserializeIdentifierName(pos + 16); + return node; +} + +function deserializeTSInstantiationExpression(pos) { + let node = { + type: "TSInstantiationExpression", + expression: null, + typeArguments: null, + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeImportOrExportKind(pos) { + switch (uint8[pos]) { + case 0: + return "value"; + case 1: + return "type"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportOrExportKind`); + } +} + +function deserializeJSDocNullableType(pos) { + let node = { + type: "TSJSDocNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocNonNullableType(pos) { + let node = { + type: "TSJSDocNonNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocUnknownType(pos) { + return { + type: "TSJSDocUnknownType", + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeCommentKind(pos) { + switch (uint8[pos]) { + case 0: + return "Line"; + case 1: + return "Block"; + case 2: + return "Block"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for CommentKind`); + } +} + +function deserializeComment(pos) { + let type = deserializeCommentKind(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type, + value: sourceText.slice(start + 2, end - (type === "Line" ? 0 : 2)), + start, + end, + }; +} + +function deserializeModuleKind(pos) { + switch (uint8[pos]) { + case 0: + return "script"; + case 1: + return "module"; + case 3: + return "commonjs"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleKind`); + } +} + +function deserializeSpan(pos) { + return { + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeNameSpan(pos) { + return { + value: deserializeStr(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeImportEntry(pos) { + return { + importName: deserializeImportImportName(pos + 32), + localName: deserializeNameSpan(pos + 64), + isType: deserializeBool(pos + 88), + }; +} + +function deserializeImportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + return { + kind: "NamespaceObject", + name: null, + start: null, + end: null, + }; + case 2: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportImportName`); + } +} + +function deserializeExportEntry(pos) { + return { + moduleRequest: deserializeOptionNameSpan(pos + 16), + importName: deserializeExportImportName(pos + 40), + exportName: deserializeExportExportName(pos + 72), + localName: deserializeExportLocalName(pos + 104), + isType: deserializeBool(pos + 136), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeExportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + return { + kind: "All", + name: null, + start: null, + end: null, + }; + case 2: + return { + kind: "AllButDefault", + name: null, + start: null, + end: null, + }; + case 3: + return { + kind: "None", + name: null, + start: null, + end: null, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportImportName`); + } +} + +function deserializeExportExportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportExportName`); + } +} + +function deserializeExportLocalName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 1: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Default", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportLocalName`); + } +} + +function deserializeDynamicImport(pos) { + return { + moduleRequest: deserializeSpan(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeAssignmentOperator(pos) { + switch (uint8[pos]) { + case 0: + return "="; + case 1: + return "+="; + case 2: + return "-="; + case 3: + return "*="; + case 4: + return "/="; + case 5: + return "%="; + case 6: + return "**="; + case 7: + return "<<="; + case 8: + return ">>="; + case 9: + return ">>>="; + case 10: + return "|="; + case 11: + return "^="; + case 12: + return "&="; + case 13: + return "||="; + case 14: + return "&&="; + case 15: + return "??="; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentOperator`); + } +} + +function deserializeBinaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "=="; + case 1: + return "!="; + case 2: + return "==="; + case 3: + return "!=="; + case 4: + return "<"; + case 5: + return "<="; + case 6: + return ">"; + case 7: + return ">="; + case 8: + return "+"; + case 9: + return "-"; + case 10: + return "*"; + case 11: + return "/"; + case 12: + return "%"; + case 13: + return "**"; + case 14: + return "<<"; + case 15: + return ">>"; + case 16: + return ">>>"; + case 17: + return "|"; + case 18: + return "^"; + case 19: + return "&"; + case 20: + return "in"; + case 21: + return "instanceof"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BinaryOperator`); + } +} + +function deserializeLogicalOperator(pos) { + switch (uint8[pos]) { + case 0: + return "||"; + case 1: + return "&&"; + case 2: + return "??"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for LogicalOperator`); + } +} + +function deserializeUnaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "+"; + case 1: + return "-"; + case 2: + return "!"; + case 3: + return "~"; + case 4: + return "typeof"; + case 5: + return "void"; + case 6: + return "delete"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UnaryOperator`); + } +} + +function deserializeUpdateOperator(pos) { + switch (uint8[pos]) { + case 0: + return "++"; + case 1: + return "--"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UpdateOperator`); + } +} + +function deserializeRawTransferData(pos) { + return { + program: deserializeProgram(pos), + comments: deserializeVecComment(pos + 144), + module: deserializeEcmaScriptModule(pos + 168), + errors: deserializeVecError(pos + 272), + }; +} + +function deserializeError(pos) { + return { + severity: deserializeErrorSeverity(pos + 72), + message: deserializeStr(pos), + labels: deserializeVecErrorLabel(pos + 16), + helpMessage: deserializeOptionStr(pos + 40), + codeframe: deserializeStr(pos + 56), + }; +} + +function deserializeErrorSeverity(pos) { + switch (uint8[pos]) { + case 0: + return "Error"; + case 1: + return "Warning"; + case 2: + return "Advice"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ErrorSeverity`); + } +} + +function deserializeErrorLabel(pos) { + return { + message: deserializeOptionStr(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeEcmaScriptModule(pos) { + return { + hasModuleSyntax: deserializeBool(pos + 96), + staticImports: deserializeVecStaticImport(pos), + staticExports: deserializeVecStaticExport(pos + 24), + dynamicImports: deserializeVecDynamicImport(pos + 48), + importMetas: deserializeVecSpan(pos + 72), + }; +} + +function deserializeStaticImport(pos) { + return { + moduleRequest: deserializeNameSpan(pos + 8), + entries: deserializeVecImportEntry(pos + 32), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeStaticExport(pos) { + return { + entries: deserializeVecExportEntry(pos + 8), + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeStr(pos) { + let pos32 = pos >> 2, + len = int32[pos32 + 2]; + if (len === 0) return ""; + pos = int32[pos32]; + let end = pos + len; + if (end <= firstNonAsciiPos) return sourceTextLatin.substr(pos, len); + // Use `utf8Slice` for strings longer than 64 bytes + if (len > 64) return utf8Slice.call(uint8, pos, end); + if (pos < sourceEndPos) { + // Check if all bytes are ASCII, use `utf8Slice` if not + for (let i = pos; i < end; i++) if (uint8[i] >= 128) return utf8Slice.call(uint8, pos, end); + // String is all ASCII, so slice from `sourceTextLatin` + return sourceTextLatin.substr(pos, len); + } + // String is not in source region - use `fromCharCode.apply` with a temp array of correct length. + // Copy bytes into temp array. + // If any byte is non-ASCII, use `utf8Slice`. + let arr = stringDecodeArrays[len]; + for (let i = 0; i < len; i++) { + let b = uint8[pos + i]; + if (b >= 128) return utf8Slice.call(uint8, pos, end); + arr[i] = b; + } + // Call `fromCharCode` with temp array + return fromCharCode.apply(null, arr); +} + +function deserializeVecComment(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeComment(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionHashbang(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeHashbang(pos); +} + +function deserializeVecDirective(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeDirective(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecStatement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeStatement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxBooleanLiteral(pos) { + return deserializeBooleanLiteral(int32[pos >> 2]); +} + +function deserializeBoxNullLiteral(pos) { + return deserializeNullLiteral(int32[pos >> 2]); +} + +function deserializeBoxNumericLiteral(pos) { + return deserializeNumericLiteral(int32[pos >> 2]); +} + +function deserializeBoxBigIntLiteral(pos) { + return deserializeBigIntLiteral(int32[pos >> 2]); +} + +function deserializeBoxRegExpLiteral(pos) { + return deserializeRegExpLiteral(int32[pos >> 2]); +} + +function deserializeBoxStringLiteral(pos) { + return deserializeStringLiteral(int32[pos >> 2]); +} + +function deserializeBoxTemplateLiteral(pos) { + return deserializeTemplateLiteral(int32[pos >> 2]); +} + +function deserializeBoxIdentifierReference(pos) { + return deserializeIdentifierReference(int32[pos >> 2]); +} + +function deserializeBoxMetaProperty(pos) { + return deserializeMetaProperty(int32[pos >> 2]); +} + +function deserializeBoxSuper(pos) { + return deserializeSuper(int32[pos >> 2]); +} + +function deserializeBoxArrayExpression(pos) { + return deserializeArrayExpression(int32[pos >> 2]); +} + +function deserializeBoxArrowFunctionExpression(pos) { + return deserializeArrowFunctionExpression(int32[pos >> 2]); +} + +function deserializeBoxAssignmentExpression(pos) { + return deserializeAssignmentExpression(int32[pos >> 2]); +} + +function deserializeBoxAwaitExpression(pos) { + return deserializeAwaitExpression(int32[pos >> 2]); +} + +function deserializeBoxBinaryExpression(pos) { + return deserializeBinaryExpression(int32[pos >> 2]); +} + +function deserializeBoxCallExpression(pos) { + return deserializeCallExpression(int32[pos >> 2]); +} + +function deserializeBoxChainExpression(pos) { + return deserializeChainExpression(int32[pos >> 2]); +} + +function deserializeBoxClass(pos) { + return deserializeClass(int32[pos >> 2]); +} + +function deserializeBoxConditionalExpression(pos) { + return deserializeConditionalExpression(int32[pos >> 2]); +} + +function deserializeBoxFunction(pos) { + return deserializeFunction(int32[pos >> 2]); +} + +function deserializeBoxImportExpression(pos) { + return deserializeImportExpression(int32[pos >> 2]); +} + +function deserializeBoxLogicalExpression(pos) { + return deserializeLogicalExpression(int32[pos >> 2]); +} + +function deserializeBoxNewExpression(pos) { + return deserializeNewExpression(int32[pos >> 2]); +} + +function deserializeBoxObjectExpression(pos) { + return deserializeObjectExpression(int32[pos >> 2]); +} + +function deserializeBoxParenthesizedExpression(pos) { + return deserializeParenthesizedExpression(int32[pos >> 2]); +} + +function deserializeBoxSequenceExpression(pos) { + return deserializeSequenceExpression(int32[pos >> 2]); +} + +function deserializeBoxTaggedTemplateExpression(pos) { + return deserializeTaggedTemplateExpression(int32[pos >> 2]); +} + +function deserializeBoxThisExpression(pos) { + return deserializeThisExpression(int32[pos >> 2]); +} + +function deserializeBoxUnaryExpression(pos) { + return deserializeUnaryExpression(int32[pos >> 2]); +} + +function deserializeBoxUpdateExpression(pos) { + return deserializeUpdateExpression(int32[pos >> 2]); +} + +function deserializeBoxYieldExpression(pos) { + return deserializeYieldExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateInExpression(pos) { + return deserializePrivateInExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXElement(pos) { + return deserializeJSXElement(int32[pos >> 2]); +} + +function deserializeBoxJSXFragment(pos) { + return deserializeJSXFragment(int32[pos >> 2]); +} + +function deserializeBoxTSAsExpression(pos) { + return deserializeTSAsExpression(int32[pos >> 2]); +} + +function deserializeBoxTSSatisfiesExpression(pos) { + return deserializeTSSatisfiesExpression(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAssertion(pos) { + return deserializeTSTypeAssertion(int32[pos >> 2]); +} + +function deserializeBoxTSNonNullExpression(pos) { + return deserializeTSNonNullExpression(int32[pos >> 2]); +} + +function deserializeBoxTSInstantiationExpression(pos) { + return deserializeTSInstantiationExpression(int32[pos >> 2]); +} + +function deserializeBoxV8IntrinsicExpression(pos) { + return deserializeV8IntrinsicExpression(int32[pos >> 2]); +} + +function deserializeVecArrayExpressionElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeArrayExpressionElement(pos)); + pos += 24; + } + return arr; +} + +function deserializeBoxSpreadElement(pos) { + return deserializeSpreadElement(int32[pos >> 2]); +} + +function deserializeVecObjectPropertyKind(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeObjectPropertyKind(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxObjectProperty(pos) { + return deserializeObjectProperty(int32[pos >> 2]); +} + +function deserializeBool(pos) { + return uint8[pos] === 1; +} + +function deserializeBoxIdentifierName(pos) { + return deserializeIdentifierName(int32[pos >> 2]); +} + +function deserializeBoxPrivateIdentifier(pos) { + return deserializePrivateIdentifier(int32[pos >> 2]); +} + +function deserializeVecTemplateElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTemplateElement(pos)); + pos += 48; + } + return arr; +} + +function deserializeVecExpression(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeExpression(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSTypeParameterInstantiation(pos) { + return deserializeTSTypeParameterInstantiation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterInstantiation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterInstantiation(pos); +} + +function deserializeOptionStr(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 ? null : deserializeStr(pos); +} + +function deserializeBoxComputedMemberExpression(pos) { + return deserializeComputedMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxStaticMemberExpression(pos) { + return deserializeStaticMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateFieldExpression(pos) { + return deserializePrivateFieldExpression(int32[pos >> 2]); +} + +function deserializeVecArgument(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeArgument(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxArrayAssignmentTarget(pos) { + return deserializeArrayAssignmentTarget(int32[pos >> 2]); +} + +function deserializeBoxObjectAssignmentTarget(pos) { + return deserializeObjectAssignmentTarget(int32[pos >> 2]); +} + +function deserializeOptionAssignmentTargetMaybeDefault(pos) { + return uint8[pos] === 51 ? null : deserializeAssignmentTargetMaybeDefault(pos); +} + +function deserializeVecOptionAssignmentTargetMaybeDefault(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionAssignmentTargetMaybeDefault(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetRest(pos) { + return deserializeAssignmentTargetRest(int32[pos >> 2]); +} + +function deserializeOptionBoxAssignmentTargetRest(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxAssignmentTargetRest(pos); +} + +function deserializeVecAssignmentTargetProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeAssignmentTargetProperty(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetWithDefault(pos) { + return deserializeAssignmentTargetWithDefault(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyIdentifier(pos) { + return deserializeAssignmentTargetPropertyIdentifier(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyProperty(pos) { + return deserializeAssignmentTargetPropertyProperty(int32[pos >> 2]); +} + +function deserializeOptionExpression(pos) { + return uint8[pos] === 51 ? null : deserializeExpression(pos); +} + +function deserializeBoxBlockStatement(pos) { + return deserializeBlockStatement(int32[pos >> 2]); +} + +function deserializeBoxBreakStatement(pos) { + return deserializeBreakStatement(int32[pos >> 2]); +} + +function deserializeBoxContinueStatement(pos) { + return deserializeContinueStatement(int32[pos >> 2]); +} + +function deserializeBoxDebuggerStatement(pos) { + return deserializeDebuggerStatement(int32[pos >> 2]); +} + +function deserializeBoxDoWhileStatement(pos) { + return deserializeDoWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxEmptyStatement(pos) { + return deserializeEmptyStatement(int32[pos >> 2]); +} + +function deserializeBoxExpressionStatement(pos) { + return deserializeExpressionStatement(int32[pos >> 2]); +} + +function deserializeBoxForInStatement(pos) { + return deserializeForInStatement(int32[pos >> 2]); +} + +function deserializeBoxForOfStatement(pos) { + return deserializeForOfStatement(int32[pos >> 2]); +} + +function deserializeBoxForStatement(pos) { + return deserializeForStatement(int32[pos >> 2]); +} + +function deserializeBoxIfStatement(pos) { + return deserializeIfStatement(int32[pos >> 2]); +} + +function deserializeBoxLabeledStatement(pos) { + return deserializeLabeledStatement(int32[pos >> 2]); +} + +function deserializeBoxReturnStatement(pos) { + return deserializeReturnStatement(int32[pos >> 2]); +} + +function deserializeBoxSwitchStatement(pos) { + return deserializeSwitchStatement(int32[pos >> 2]); +} + +function deserializeBoxThrowStatement(pos) { + return deserializeThrowStatement(int32[pos >> 2]); +} + +function deserializeBoxTryStatement(pos) { + return deserializeTryStatement(int32[pos >> 2]); +} + +function deserializeBoxWhileStatement(pos) { + return deserializeWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxWithStatement(pos) { + return deserializeWithStatement(int32[pos >> 2]); +} + +function deserializeBoxVariableDeclaration(pos) { + return deserializeVariableDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAliasDeclaration(pos) { + return deserializeTSTypeAliasDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSInterfaceDeclaration(pos) { + return deserializeTSInterfaceDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSEnumDeclaration(pos) { + return deserializeTSEnumDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSModuleDeclaration(pos) { + return deserializeTSModuleDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSGlobalDeclaration(pos) { + return deserializeTSGlobalDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSImportEqualsDeclaration(pos) { + return deserializeTSImportEqualsDeclaration(int32[pos >> 2]); +} + +function deserializeVecVariableDeclarator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeVariableDeclarator(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxTSTypeAnnotation(pos) { + return deserializeTSTypeAnnotation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeAnnotation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeAnnotation(pos); +} + +function deserializeOptionStatement(pos) { + return uint8[pos] === 70 ? null : deserializeStatement(pos); +} + +function deserializeOptionForStatementInit(pos) { + return uint8[pos] === 65 ? null : deserializeForStatementInit(pos); +} + +function deserializeOptionLabelIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeLabelIdentifier(pos); +} + +function deserializeVecSwitchCase(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeSwitchCase(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxCatchClause(pos) { + return deserializeCatchClause(int32[pos >> 2]); +} + +function deserializeOptionBoxCatchClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxCatchClause(pos); +} + +function deserializeOptionBoxBlockStatement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBlockStatement(pos); +} + +function deserializeOptionCatchParameter(pos) { + return uint8[pos + 16] === 4 ? null : deserializeCatchParameter(pos); +} + +function deserializeBoxBindingIdentifier(pos) { + return deserializeBindingIdentifier(int32[pos >> 2]); +} + +function deserializeBoxObjectPattern(pos) { + return deserializeObjectPattern(int32[pos >> 2]); +} + +function deserializeBoxArrayPattern(pos) { + return deserializeArrayPattern(int32[pos >> 2]); +} + +function deserializeBoxAssignmentPattern(pos) { + return deserializeAssignmentPattern(int32[pos >> 2]); +} + +function deserializeVecBindingProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeBindingProperty(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxBindingRestElement(pos) { + return deserializeBindingRestElement(int32[pos >> 2]); +} + +function deserializeOptionBoxBindingRestElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBindingRestElement(pos); +} + +function deserializeOptionBindingPattern(pos) { + return uint8[pos] === 4 ? null : deserializeBindingPattern(pos); +} + +function deserializeVecOptionBindingPattern(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionBindingPattern(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionBindingIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeBindingIdentifier(pos); +} + +function deserializeBoxTSTypeParameterDeclaration(pos) { + return deserializeTSTypeParameterDeclaration(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterDeclaration(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterDeclaration(pos); +} + +function deserializeBoxTSThisParameter(pos) { + return deserializeTSThisParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxTSThisParameter(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSThisParameter(pos); +} + +function deserializeBoxFormalParameters(pos) { + return deserializeFormalParameters(int32[pos >> 2]); +} + +function deserializeBoxFunctionBody(pos) { + return deserializeFunctionBody(int32[pos >> 2]); +} + +function deserializeOptionBoxFunctionBody(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxFunctionBody(pos); +} + +function deserializeVecFormalParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 72; + for (; pos !== endPos; ) { + arr.push(deserializeFormalParameter(pos)); + pos += 72; + } + return arr; +} + +function deserializeVecDecorator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeDecorator(pos)); + pos += 32; + } + return arr; +} + +function deserializeBoxExpression(pos) { + return deserializeExpression(int32[pos >> 2]); +} + +function deserializeOptionBoxExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxExpression(pos); +} + +function deserializeOptionTSAccessibility(pos) { + return uint8[pos] === 3 ? null : deserializeTSAccessibility(pos); +} + +function deserializeVecTSClassImplements(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSClassImplements(pos)); + pos += 40; + } + return arr; +} + +function deserializeBoxClassBody(pos) { + return deserializeClassBody(int32[pos >> 2]); +} + +function deserializeVecClassElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeClassElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxStaticBlock(pos) { + return deserializeStaticBlock(int32[pos >> 2]); +} + +function deserializeBoxMethodDefinition(pos) { + return deserializeMethodDefinition(int32[pos >> 2]); +} + +function deserializeBoxPropertyDefinition(pos) { + return deserializePropertyDefinition(int32[pos >> 2]); +} + +function deserializeBoxAccessorProperty(pos) { + return deserializeAccessorProperty(int32[pos >> 2]); +} + +function deserializeBoxTSIndexSignature(pos) { + return deserializeTSIndexSignature(int32[pos >> 2]); +} + +function deserializeBoxImportDeclaration(pos) { + return deserializeImportDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportAllDeclaration(pos) { + return deserializeExportAllDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportDefaultDeclaration(pos) { + return deserializeExportDefaultDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportNamedDeclaration(pos) { + return deserializeExportNamedDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSExportAssignment(pos) { + return deserializeTSExportAssignment(int32[pos >> 2]); +} + +function deserializeBoxTSNamespaceExportDeclaration(pos) { + return deserializeTSNamespaceExportDeclaration(int32[pos >> 2]); +} + +function deserializeOptionImportPhase(pos) { + return uint8[pos] === 2 ? null : deserializeImportPhase(pos); +} + +function deserializeVecImportDeclarationSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeImportDeclarationSpecifier(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionVecImportDeclarationSpecifier(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeVecImportDeclarationSpecifier(pos); +} + +function deserializeBoxWithClause(pos) { + return deserializeWithClause(int32[pos >> 2]); +} + +function deserializeOptionBoxWithClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxWithClause(pos); +} + +function deserializeBoxImportSpecifier(pos) { + return deserializeImportSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportDefaultSpecifier(pos) { + return deserializeImportDefaultSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportNamespaceSpecifier(pos) { + return deserializeImportNamespaceSpecifier(int32[pos >> 2]); +} + +function deserializeVecImportAttribute(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 120; + for (; pos !== endPos; ) { + arr.push(deserializeImportAttribute(pos)); + pos += 120; + } + return arr; +} + +function deserializeOptionDeclaration(pos) { + return uint8[pos] === 31 ? null : deserializeDeclaration(pos); +} + +function deserializeVecExportSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 7); + for (; pos !== endPos; ) { + arr.push(deserializeExportSpecifier(pos)); + pos += 128; + } + return arr; +} + +function deserializeOptionStringLiteral(pos) { + return uint8[pos + 12] === 2 ? null : deserializeStringLiteral(pos); +} + +function deserializeOptionModuleExportName(pos) { + return uint8[pos] === 3 ? null : deserializeModuleExportName(pos); +} + +function deserializeF64(pos) { + return float64[pos >> 3]; +} + +function deserializeU8(pos) { + return uint8[pos]; +} + +function deserializeBoxJSXOpeningElement(pos) { + return deserializeJSXOpeningElement(int32[pos >> 2]); +} + +function deserializeVecJSXChild(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXChild(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXClosingElement(pos) { + return deserializeJSXClosingElement(int32[pos >> 2]); +} + +function deserializeOptionBoxJSXClosingElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxJSXClosingElement(pos); +} + +function deserializeVecJSXAttributeItem(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXAttributeItem(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXIdentifier(pos) { + return deserializeJSXIdentifier(int32[pos >> 2]); +} + +function deserializeBoxJSXNamespacedName(pos) { + return deserializeJSXNamespacedName(int32[pos >> 2]); +} + +function deserializeBoxJSXMemberExpression(pos) { + return deserializeJSXMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXAttribute(pos) { + return deserializeJSXAttribute(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadAttribute(pos) { + return deserializeJSXSpreadAttribute(int32[pos >> 2]); +} + +function deserializeOptionJSXAttributeValue(pos) { + return uint8[pos] === 4 ? null : deserializeJSXAttributeValue(pos); +} + +function deserializeBoxJSXExpressionContainer(pos) { + return deserializeJSXExpressionContainer(int32[pos >> 2]); +} + +function deserializeBoxJSXText(pos) { + return deserializeJSXText(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadChild(pos) { + return deserializeJSXSpreadChild(int32[pos >> 2]); +} + +function deserializeVecTSEnumMember(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTSEnumMember(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxTSAnyKeyword(pos) { + return deserializeTSAnyKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBigIntKeyword(pos) { + return deserializeTSBigIntKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBooleanKeyword(pos) { + return deserializeTSBooleanKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSIntrinsicKeyword(pos) { + return deserializeTSIntrinsicKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNeverKeyword(pos) { + return deserializeTSNeverKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNullKeyword(pos) { + return deserializeTSNullKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNumberKeyword(pos) { + return deserializeTSNumberKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSObjectKeyword(pos) { + return deserializeTSObjectKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSStringKeyword(pos) { + return deserializeTSStringKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSSymbolKeyword(pos) { + return deserializeTSSymbolKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUndefinedKeyword(pos) { + return deserializeTSUndefinedKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUnknownKeyword(pos) { + return deserializeTSUnknownKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSVoidKeyword(pos) { + return deserializeTSVoidKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSArrayType(pos) { + return deserializeTSArrayType(int32[pos >> 2]); +} + +function deserializeBoxTSConditionalType(pos) { + return deserializeTSConditionalType(int32[pos >> 2]); +} + +function deserializeBoxTSConstructorType(pos) { + return deserializeTSConstructorType(int32[pos >> 2]); +} + +function deserializeBoxTSFunctionType(pos) { + return deserializeTSFunctionType(int32[pos >> 2]); +} + +function deserializeBoxTSImportType(pos) { + return deserializeTSImportType(int32[pos >> 2]); +} + +function deserializeBoxTSIndexedAccessType(pos) { + return deserializeTSIndexedAccessType(int32[pos >> 2]); +} + +function deserializeBoxTSInferType(pos) { + return deserializeTSInferType(int32[pos >> 2]); +} + +function deserializeBoxTSIntersectionType(pos) { + return deserializeTSIntersectionType(int32[pos >> 2]); +} + +function deserializeBoxTSLiteralType(pos) { + return deserializeTSLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSMappedType(pos) { + return deserializeTSMappedType(int32[pos >> 2]); +} + +function deserializeBoxTSNamedTupleMember(pos) { + return deserializeTSNamedTupleMember(int32[pos >> 2]); +} + +function deserializeBoxTSTemplateLiteralType(pos) { + return deserializeTSTemplateLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSThisType(pos) { + return deserializeTSThisType(int32[pos >> 2]); +} + +function deserializeBoxTSTupleType(pos) { + return deserializeTSTupleType(int32[pos >> 2]); +} + +function deserializeBoxTSTypeLiteral(pos) { + return deserializeTSTypeLiteral(int32[pos >> 2]); +} + +function deserializeBoxTSTypeOperator(pos) { + return deserializeTSTypeOperator(int32[pos >> 2]); +} + +function deserializeBoxTSTypePredicate(pos) { + return deserializeTSTypePredicate(int32[pos >> 2]); +} + +function deserializeBoxTSTypeQuery(pos) { + return deserializeTSTypeQuery(int32[pos >> 2]); +} + +function deserializeBoxTSTypeReference(pos) { + return deserializeTSTypeReference(int32[pos >> 2]); +} + +function deserializeBoxTSUnionType(pos) { + return deserializeTSUnionType(int32[pos >> 2]); +} + +function deserializeBoxTSParenthesizedType(pos) { + return deserializeTSParenthesizedType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNullableType(pos) { + return deserializeJSDocNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNonNullableType(pos) { + return deserializeJSDocNonNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocUnknownType(pos) { + return deserializeJSDocUnknownType(int32[pos >> 2]); +} + +function deserializeVecTSType(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSType(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecTSTupleElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSTupleElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSOptionalType(pos) { + return deserializeTSOptionalType(int32[pos >> 2]); +} + +function deserializeBoxTSRestType(pos) { + return deserializeTSRestType(int32[pos >> 2]); +} + +function deserializeBoxTSQualifiedName(pos) { + return deserializeTSQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSType(pos) { + return uint8[pos] === 38 ? null : deserializeTSType(pos); +} + +function deserializeVecTSTypeParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeTSTypeParameter(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecTSInterfaceHeritage(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSInterfaceHeritage(pos)); + pos += 40; + } + return arr; +} + +function deserializeBoxTSInterfaceBody(pos) { + return deserializeTSInterfaceBody(int32[pos >> 2]); +} + +function deserializeVecTSSignature(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSSignature(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSPropertySignature(pos) { + return deserializeTSPropertySignature(int32[pos >> 2]); +} + +function deserializeBoxTSCallSignatureDeclaration(pos) { + return deserializeTSCallSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSConstructSignatureDeclaration(pos) { + return deserializeTSConstructSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSMethodSignature(pos) { + return deserializeTSMethodSignature(int32[pos >> 2]); +} + +function deserializeVecTSIndexSignatureName(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSIndexSignatureName(pos)); + pos += 40; + } + return arr; +} + +function deserializeOptionTSModuleDeclarationBody(pos) { + return uint8[pos] === 2 ? null : deserializeTSModuleDeclarationBody(pos); +} + +function deserializeBoxTSModuleBlock(pos) { + return deserializeTSModuleBlock(int32[pos >> 2]); +} + +function deserializeBoxTSTypeParameter(pos) { + return deserializeTSTypeParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxObjectExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxObjectExpression(pos); +} + +function deserializeOptionTSImportTypeQualifier(pos) { + return uint8[pos] === 2 ? null : deserializeTSImportTypeQualifier(pos); +} + +function deserializeBoxTSImportTypeQualifiedName(pos) { + return deserializeTSImportTypeQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSMappedTypeModifierOperator(pos) { + return uint8[pos] === 3 ? null : deserializeTSMappedTypeModifierOperator(pos); +} + +function deserializeBoxTSExternalModuleReference(pos) { + return deserializeTSExternalModuleReference(int32[pos >> 2]); +} + +function deserializeI32(pos) { + return int32[pos >> 2]; +} + +function deserializeOptionNameSpan(pos) { + return int32[(pos >> 2) + 2] === 0 && int32[(pos >> 2) + 3] === 0 + ? null + : deserializeNameSpan(pos); +} + +function deserializeVecError(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeError(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecErrorLabel(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeErrorLabel(pos)); + pos += 24; + } + return arr; +} + +function deserializeVecStaticImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeStaticImport(pos)); + pos += 56; + } + return arr; +} + +function deserializeVecStaticExport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeStaticExport(pos)); + pos += 32; + } + return arr; +} + +function deserializeVecDynamicImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeDynamicImport(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecSpan(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 3); + for (; pos !== endPos; ) { + arr.push(deserializeSpan(pos)); + pos += 8; + } + return arr; +} + +function deserializeVecImportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 96; + for (; pos !== endPos; ) { + arr.push(deserializeImportEntry(pos)); + pos += 96; + } + return arr; +} + +function deserializeVecExportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 144; + for (; pos !== endPos; ) { + arr.push(deserializeExportEntry(pos)); + pos += 144; + } + return arr; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/ts_range.js b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/ts_range.js new file mode 100644 index 0000000000000000000000000000000000000000..3ba94c96840b266647a8a05e10f1fc66a1a956d3 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/deserialize/ts_range.js @@ -0,0 +1,6701 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer.rs`. + +let uint8, + int32, + float64, + sourceText, + sourceTextLatin, + sourceEndPos = 0, + firstNonAsciiPos = 0; + +const { fromCharCode } = String, + { utf8Slice, latin1Slice } = Buffer.prototype, + stringDecodeArrays = Array(65).fill(null); +for (let i = 0; i <= 64; i++) stringDecodeArrays[i] = Array(i).fill(0); + +export function deserialize(buffer, sourceText, sourceByteLen) { + sourceEndPos = sourceByteLen; + return deserializeWith(buffer, sourceText, sourceByteLen, deserializeRawTransferData); +} + +function deserializeWith(buffer, sourceTextInput, sourceByteLen, deserialize) { + uint8 = buffer; + int32 = buffer.int32; + float64 = buffer.float64; + sourceText = sourceTextInput; + if (sourceText.length === sourceByteLen) { + firstNonAsciiPos = sourceByteLen; + sourceTextLatin = sourceText; + } else { + let i = 0; + for (; i < sourceByteLen && uint8[i] < 128; i++); + firstNonAsciiPos = i; + sourceTextLatin = latin1Slice.call(uint8, 0, sourceByteLen); + } + let data = deserialize(int32[536870900]); + resetBuffer(); + return data; +} + +export function resetBuffer() { + // Clear buffer and source text strings to allow them to be garbage collected + uint8 = int32 = float64 = sourceText = sourceTextLatin = void 0; +} + +function deserializeProgram(pos) { + let end = deserializeI32(pos + 4), + program = { + type: "Program", + body: null, + sourceType: deserializeModuleKind(pos + 137), + hashbang: null, + start: 0, + end, + range: [0, end], + }; + program.hashbang = deserializeOptionHashbang(pos + 56); + let body = (program.body = deserializeVecDirective(pos + 88)); + body.push(...deserializeVecStatement(pos + 112)); + { + let start; + if (body.length > 0) { + let first = body[0]; + start = first.start; + if (first.type === "ExportNamedDeclaration" || first.type === "ExportDefaultDeclaration") { + let { declaration } = first; + if ( + declaration !== null && + declaration.type === "ClassDeclaration" && + declaration.decorators.length > 0 + ) { + let decoratorStart = declaration.decorators[0].start; + decoratorStart < start && (start = decoratorStart); + } + } + } else start = end; + program.start = program.range[0] = start; + } + return program; +} + +function deserializeExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Expression`); + } +} + +function deserializeIdentifierName(pos) { + let start, end; + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeIdentifierReference(pos) { + let start, end; + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeBindingIdentifier(pos) { + let start, end; + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeLabelIdentifier(pos) { + let start, end; + return { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeThisExpression(pos) { + let start, end; + return { + type: "ThisExpression", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeArrayExpression(pos) { + let start, + end, + node = { + type: "ArrayExpression", + elements: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.elements = deserializeVecArrayExpressionElement(pos + 16); + return node; +} + +function deserializeArrayExpressionElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + case 65: + return deserializeElision(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ArrayExpressionElement`); + } +} + +function deserializeElision(pos) { + return null; +} + +function deserializeObjectExpression(pos) { + let start, + end, + node = { + type: "ObjectExpression", + properties: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.properties = deserializeVecObjectPropertyKind(pos + 16); + return node; +} + +function deserializeObjectPropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxObjectProperty(pos + 8); + case 1: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ObjectPropertyKind`); + } +} + +function deserializeObjectProperty(pos) { + let start, + end, + node = { + type: "Property", + kind: deserializePropertyKind(pos + 12), + key: null, + value: null, + method: deserializeBool(pos + 13), + shorthand: deserializeBool(pos + 14), + computed: deserializeBool(pos + 15), + optional: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeExpression(pos + 32); + return node; +} + +function deserializePropertyKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxIdentifierName(pos + 8); + case 65: + return deserializeBoxPrivateIdentifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKey`); + } +} + +function deserializePropertyKind(pos) { + switch (uint8[pos]) { + case 0: + return "init"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyKind`); + } +} + +function deserializeTemplateLiteral(pos) { + let start, + end, + node = { + type: "TemplateLiteral", + quasis: null, + expressions: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.expressions = deserializeVecExpression(pos + 40); + return node; +} + +function deserializeTaggedTemplateExpression(pos) { + let start, + end, + node = { + type: "TaggedTemplateExpression", + tag: null, + typeArguments: null, + quasi: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.tag = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.quasi = deserializeTemplateLiteral(pos + 40); + return node; +} + +function deserializeTemplateElement(pos) { + let tail = deserializeBool(pos + 12), + start = deserializeI32(pos) - 1, + end = deserializeI32(pos + 4) + 2 - tail, + value = deserializeTemplateElementValue(pos + 16); + value.cooked !== null && + deserializeBool(pos + 13) && + (value.cooked = value.cooked.replace(/\uFFFD(.{4})/g, (_, hex) => + String.fromCodePoint(parseInt(hex, 16)), + )); + return { + type: "TemplateElement", + value, + tail, + start, + end, + range: [start, end], + }; +} + +function deserializeTemplateElementValue(pos) { + return { + raw: deserializeStr(pos), + cooked: deserializeOptionStr(pos + 16), + }; +} + +function deserializeComputedMemberExpression(pos) { + let start, + end, + node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: true, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeExpression(pos + 32); + return node; +} + +function deserializeStaticMemberExpression(pos) { + let start, + end, + node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializePrivateFieldExpression(pos) { + let start, + end, + node = { + type: "MemberExpression", + object: null, + property: null, + optional: deserializeBool(pos + 12), + computed: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.property = deserializePrivateIdentifier(pos + 32); + return node; +} + +function deserializeCallExpression(pos) { + let start, + end, + node = { + type: "CallExpression", + callee: null, + typeArguments: null, + arguments: null, + optional: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.callee = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeNewExpression(pos) { + let start, + end, + node = { + type: "NewExpression", + callee: null, + typeArguments: null, + arguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.callee = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.arguments = deserializeVecArgument(pos + 40); + return node; +} + +function deserializeMetaProperty(pos) { + let start, + end, + node = { + type: "MetaProperty", + meta: null, + property: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.meta = deserializeIdentifierName(pos + 16); + node.property = deserializeIdentifierName(pos + 48); + return node; +} + +function deserializeSpreadElement(pos) { + let start, + end, + node = { + type: "SpreadElement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeArgument(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxSpreadElement(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Argument`); + } +} + +function deserializeUpdateExpression(pos) { + let start, + end, + node = { + type: "UpdateExpression", + operator: deserializeUpdateOperator(pos + 12), + prefix: deserializeBool(pos + 13), + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeSimpleAssignmentTarget(pos + 16); + return node; +} + +function deserializeUnaryExpression(pos) { + let start, + end, + node = { + type: "UnaryExpression", + operator: deserializeUnaryOperator(pos + 12), + argument: null, + prefix: true, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeBinaryExpression(pos) { + let start, + end, + node = { + type: "BinaryExpression", + left: null, + operator: deserializeBinaryOperator(pos + 12), + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializePrivateInExpression(pos) { + let start, + end, + node = { + type: "BinaryExpression", + left: null, + operator: "in", + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializePrivateIdentifier(pos + 16); + node.right = deserializeExpression(pos + 48); + return node; +} + +function deserializeLogicalExpression(pos) { + let start, + end, + node = { + type: "LogicalExpression", + left: null, + operator: deserializeLogicalOperator(pos + 12), + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeExpression(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeConditionalExpression(pos) { + let start, + end, + node = { + type: "ConditionalExpression", + test: null, + consequent: null, + alternate: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeExpression(pos + 32); + node.alternate = deserializeExpression(pos + 48); + return node; +} + +function deserializeAssignmentExpression(pos) { + let start, + end, + node = { + type: "AssignmentExpression", + operator: deserializeAssignmentOperator(pos + 12), + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTarget`); + } +} + +function deserializeSimpleAssignmentTarget(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for SimpleAssignmentTarget`); + } +} + +function deserializeArrayAssignmentTarget(pos) { + let start, + end, + node = { + type: "ArrayPattern", + decorators: [], + elements: null, + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + elements = deserializeVecOptionAssignmentTargetMaybeDefault(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeObjectAssignmentTarget(pos) { + let start, + end, + node = { + type: "ObjectPattern", + decorators: [], + properties: null, + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + properties = deserializeVecAssignmentTargetProperty(pos + 16), + rest = deserializeOptionBoxAssignmentTargetRest(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeAssignmentTargetRest(pos) { + let start, + end, + node = { + type: "RestElement", + decorators: [], + argument: null, + optional: false, + typeAnnotation: null, + value: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeAssignmentTarget(pos + 16); + return node; +} + +function deserializeAssignmentTargetMaybeDefault(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxAssignmentTargetWithDefault(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetMaybeDefault`); + } +} + +function deserializeAssignmentTargetWithDefault(pos) { + let start, + end, + node = { + type: "AssignmentPattern", + decorators: [], + left: null, + right: null, + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeAssignmentTarget(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeAssignmentTargetProperty(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxAssignmentTargetPropertyIdentifier(pos + 8); + case 1: + return deserializeBoxAssignmentTargetPropertyProperty(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentTargetProperty`); + } +} + +function deserializeAssignmentTargetPropertyIdentifier(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: true, + computed: false, + optional: false, + start, + end, + range: [start, end], + }, + key = deserializeIdentifierReference(pos + 16), + keyStart, + keyEnd, + value = { + type: "Identifier", + decorators: [], + name: key.name, + optional: false, + typeAnnotation: null, + start: (keyStart = key.start), + end: (keyEnd = key.end), + range: [keyStart, keyEnd], + }, + init = deserializeOptionExpression(pos + 48); + init !== null && + (value = { + type: "AssignmentPattern", + decorators: [], + left: value, + right: init, + optional: false, + typeAnnotation: null, + start, + end, + range: [start, end], + }); + node.key = key; + node.value = value; + return node; +} + +function deserializeAssignmentTargetPropertyProperty(pos) { + let start, + end, + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: false, + computed: deserializeBool(pos + 12), + optional: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeAssignmentTargetMaybeDefault(pos + 32); + return node; +} + +function deserializeSequenceExpression(pos) { + let start, + end, + node = { + type: "SequenceExpression", + expressions: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expressions = deserializeVecExpression(pos + 16); + return node; +} + +function deserializeSuper(pos) { + let start, end; + return { + type: "Super", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeAwaitExpression(pos) { + let start, + end, + node = { + type: "AwaitExpression", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeChainExpression(pos) { + let start, + end, + node = { + type: "ChainExpression", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeChainElement(pos + 16); + return node; +} + +function deserializeChainElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxCallExpression(pos + 8); + case 1: + return deserializeBoxTSNonNullExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ChainElement`); + } +} + +function deserializeParenthesizedExpression(pos) { + let node; + { + let start, end; + node = { + type: "ParenthesizedExpression", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + } + return node; +} + +function deserializeStatement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBlockStatement(pos + 8); + case 1: + return deserializeBoxBreakStatement(pos + 8); + case 2: + return deserializeBoxContinueStatement(pos + 8); + case 3: + return deserializeBoxDebuggerStatement(pos + 8); + case 4: + return deserializeBoxDoWhileStatement(pos + 8); + case 5: + return deserializeBoxEmptyStatement(pos + 8); + case 6: + return deserializeBoxExpressionStatement(pos + 8); + case 7: + return deserializeBoxForInStatement(pos + 8); + case 8: + return deserializeBoxForOfStatement(pos + 8); + case 9: + return deserializeBoxForStatement(pos + 8); + case 10: + return deserializeBoxIfStatement(pos + 8); + case 11: + return deserializeBoxLabeledStatement(pos + 8); + case 12: + return deserializeBoxReturnStatement(pos + 8); + case 13: + return deserializeBoxSwitchStatement(pos + 8); + case 14: + return deserializeBoxThrowStatement(pos + 8); + case 15: + return deserializeBoxTryStatement(pos + 8); + case 16: + return deserializeBoxWhileStatement(pos + 8); + case 17: + return deserializeBoxWithStatement(pos + 8); + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + case 64: + return deserializeBoxImportDeclaration(pos + 8); + case 65: + return deserializeBoxExportAllDeclaration(pos + 8); + case 66: + return deserializeBoxExportDefaultDeclaration(pos + 8); + case 67: + return deserializeBoxExportNamedDeclaration(pos + 8); + case 68: + return deserializeBoxTSExportAssignment(pos + 8); + case 69: + return deserializeBoxTSNamespaceExportDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Statement`); + } +} + +function deserializeDirective(pos) { + let start, + end, + node = { + type: "ExpressionStatement", + expression: null, + directive: deserializeStr(pos + 64), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeHashbang(pos) { + let start, end; + return { + type: "Hashbang", + value: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeBlockStatement(pos) { + let start, + end, + node = { + type: "BlockStatement", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeDeclaration(pos) { + switch (uint8[pos]) { + case 32: + return deserializeBoxVariableDeclaration(pos + 8); + case 33: + return deserializeBoxFunction(pos + 8); + case 34: + return deserializeBoxClass(pos + 8); + case 35: + return deserializeBoxTSTypeAliasDeclaration(pos + 8); + case 36: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + case 37: + return deserializeBoxTSEnumDeclaration(pos + 8); + case 38: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 39: + return deserializeBoxTSGlobalDeclaration(pos + 8); + case 40: + return deserializeBoxTSImportEqualsDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for Declaration`); + } +} + +function deserializeVariableDeclaration(pos) { + let start, + end, + node = { + type: "VariableDeclaration", + kind: deserializeVariableDeclarationKind(pos + 12), + declarations: null, + declare: deserializeBool(pos + 13), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.declarations = deserializeVecVariableDeclarator(pos + 16); + return node; +} + +function deserializeVariableDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "var"; + case 1: + return "let"; + case 2: + return "const"; + case 3: + return "using"; + case 4: + return "await using"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for VariableDeclarationKind`); + } +} + +function deserializeVariableDeclarator(pos) { + let start, + end, + node = { + type: "VariableDeclarator", + id: null, + init: null, + definite: deserializeBool(pos + 13), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + pattern = deserializeBindingPattern(pos + 16); + { + let typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + if (typeAnnotation !== null) { + pattern.typeAnnotation = typeAnnotation; + pattern.range[1] = pattern.end = typeAnnotation.end; + } + } + node.id = pattern; + node.init = deserializeOptionExpression(pos + 40); + return node; +} + +function deserializeEmptyStatement(pos) { + let start, end; + return { + type: "EmptyStatement", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeExpressionStatement(pos) { + let start, + end, + node = { + type: "ExpressionStatement", + expression: null, + directive: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeIfStatement(pos) { + let start, + end, + node = { + type: "IfStatement", + test: null, + consequent: null, + alternate: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeExpression(pos + 16); + node.consequent = deserializeStatement(pos + 32); + node.alternate = deserializeOptionStatement(pos + 48); + return node; +} + +function deserializeDoWhileStatement(pos) { + let start, + end, + node = { + type: "DoWhileStatement", + body: null, + test: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeStatement(pos + 16); + node.test = deserializeExpression(pos + 32); + return node; +} + +function deserializeWhileStatement(pos) { + let start, + end, + node = { + type: "WhileStatement", + test: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeForStatement(pos) { + let start, + end, + node = { + type: "ForStatement", + init: null, + test: null, + update: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.init = deserializeOptionForStatementInit(pos + 16); + node.test = deserializeOptionExpression(pos + 32); + node.update = deserializeOptionExpression(pos + 48); + node.body = deserializeStatement(pos + 64); + return node; +} + +function deserializeForStatementInit(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxVariableDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementInit`); + } +} + +function deserializeForInStatement(pos) { + let start, + end, + node = { + type: "ForInStatement", + left: null, + right: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeForStatementLeft(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSAsExpression(pos + 8); + case 2: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 3: + return deserializeBoxTSNonNullExpression(pos + 8); + case 4: + return deserializeBoxTSTypeAssertion(pos + 8); + case 8: + return deserializeBoxArrayAssignmentTarget(pos + 8); + case 9: + return deserializeBoxObjectAssignmentTarget(pos + 8); + case 16: + return deserializeBoxVariableDeclaration(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ForStatementLeft`); + } +} + +function deserializeForOfStatement(pos) { + let start, + end, + node = { + type: "ForOfStatement", + await: deserializeBool(pos + 64), + left: null, + right: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeForStatementLeft(pos + 16); + node.right = deserializeExpression(pos + 32); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeContinueStatement(pos) { + let start, + end, + node = { + type: "ContinueStatement", + label: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeBreakStatement(pos) { + let start, + end, + node = { + type: "BreakStatement", + label: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeOptionLabelIdentifier(pos + 16); + return node; +} + +function deserializeReturnStatement(pos) { + let start, + end, + node = { + type: "ReturnStatement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeWithStatement(pos) { + let start, + end, + node = { + type: "WithStatement", + object: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeExpression(pos + 16); + node.body = deserializeStatement(pos + 32); + return node; +} + +function deserializeSwitchStatement(pos) { + let start, + end, + node = { + type: "SwitchStatement", + discriminant: null, + cases: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.discriminant = deserializeExpression(pos + 16); + node.cases = deserializeVecSwitchCase(pos + 32); + return node; +} + +function deserializeSwitchCase(pos) { + let start, + end, + node = { + type: "SwitchCase", + test: null, + consequent: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.test = deserializeOptionExpression(pos + 16); + node.consequent = deserializeVecStatement(pos + 32); + return node; +} + +function deserializeLabeledStatement(pos) { + let start, + end, + node = { + type: "LabeledStatement", + label: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeLabelIdentifier(pos + 16); + node.body = deserializeStatement(pos + 48); + return node; +} + +function deserializeThrowStatement(pos) { + let start, + end, + node = { + type: "ThrowStatement", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeTryStatement(pos) { + let start, + end, + node = { + type: "TryStatement", + block: null, + handler: null, + finalizer: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.block = deserializeBoxBlockStatement(pos + 16); + node.handler = deserializeOptionBoxCatchClause(pos + 24); + node.finalizer = deserializeOptionBoxBlockStatement(pos + 32); + return node; +} + +function deserializeCatchClause(pos) { + let start, + end, + node = { + type: "CatchClause", + param: null, + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.param = deserializeOptionCatchParameter(pos + 16); + node.body = deserializeBoxBlockStatement(pos + 56); + return node; +} + +function deserializeCatchParameter(pos) { + let pattern = deserializeBindingPattern(pos + 16); + { + let typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + pattern.typeAnnotation = typeAnnotation; + if (typeAnnotation !== null) { + pattern.end = typeAnnotation.end; + pattern.range[1] = typeAnnotation.end; + } + } + return pattern; +} + +function deserializeDebuggerStatement(pos) { + let start, end; + return { + type: "DebuggerStatement", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeBindingPattern(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBindingIdentifier(pos + 8); + case 1: + return deserializeBoxObjectPattern(pos + 8); + case 2: + return deserializeBoxArrayPattern(pos + 8); + case 3: + return deserializeBoxAssignmentPattern(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BindingPattern`); + } +} + +function deserializeAssignmentPattern(pos) { + let start, + end, + node = { + type: "AssignmentPattern", + decorators: [], + left: null, + right: null, + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeBindingPattern(pos + 16); + node.right = deserializeExpression(pos + 32); + return node; +} + +function deserializeObjectPattern(pos) { + let start, + end, + node = { + type: "ObjectPattern", + decorators: [], + properties: null, + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + properties = deserializeVecBindingProperty(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && properties.push(rest); + node.properties = properties; + return node; +} + +function deserializeBindingProperty(pos) { + let start, + end, + node = { + type: "Property", + kind: "init", + key: null, + value: null, + method: false, + shorthand: deserializeBool(pos + 12), + computed: deserializeBool(pos + 13), + optional: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.value = deserializeBindingPattern(pos + 32); + return node; +} + +function deserializeArrayPattern(pos) { + let start, + end, + node = { + type: "ArrayPattern", + decorators: [], + elements: null, + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + elements = deserializeVecOptionBindingPattern(pos + 16), + rest = deserializeOptionBoxBindingRestElement(pos + 40); + rest !== null && elements.push(rest); + node.elements = elements; + return node; +} + +function deserializeBindingRestElement(pos) { + let start, + end, + node = { + type: "RestElement", + decorators: [], + argument: null, + optional: false, + typeAnnotation: null, + value: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeBindingPattern(pos + 16); + return node; +} + +function deserializeFunction(pos) { + let start, + end, + node = { + type: deserializeFunctionType(pos + 88), + id: null, + generator: deserializeBool(pos + 89), + async: deserializeBool(pos + 90), + declare: deserializeBool(pos + 91), + typeParameters: null, + params: null, + returnType: null, + body: null, + expression: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 64); + { + let thisParam = deserializeOptionBoxTSThisParameter(pos + 56); + thisParam !== null && params.unshift(thisParam); + } + node.id = deserializeOptionBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 72); + node.body = deserializeOptionBoxFunctionBody(pos + 80); + return node; +} + +function deserializeFunctionType(pos) { + switch (uint8[pos]) { + case 0: + return "FunctionDeclaration"; + case 1: + return "FunctionExpression"; + case 2: + return "TSDeclareFunction"; + case 3: + return "TSEmptyBodyFunctionExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for FunctionType`); + } +} + +function deserializeFormalParameters(pos) { + let params = deserializeVecFormalParameter(pos + 16), + restFieldPos32 = (pos >> 2) + 10; + if (int32[restFieldPos32] !== 0 && int32[restFieldPos32 + 1] !== 0) { + pos = int32[restFieldPos32]; + let start, + end, + rest = { + type: "RestElement", + decorators: [], + argument: null, + optional: false, + typeAnnotation: null, + value: null, + start: (start = deserializeI32(pos + 40)), + end: (end = deserializeI32(pos + 44)), + range: [start, end], + }; + rest.argument = deserializeBindingPattern(pos + 56); + rest.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 72); + if (rest.typeAnnotation !== null) { + end = rest.typeAnnotation.end; + rest.end = end; + rest.range[1] = end; + } + params.push(rest); + } + return params; +} + +function deserializeFormalParameter(pos) { + let param, + initializerFieldPos32 = (pos >> 2) + 16, + hasInitializer = int32[initializerFieldPos32] !== 0 && int32[initializerFieldPos32 + 1] !== 0; + { + let accessibility = deserializeOptionTSAccessibility(pos + 13), + readonly = deserializeBool(pos + 14), + override = deserializeBool(pos + 15); + if (accessibility === null && !readonly && !override) { + let optional = deserializeBool(pos + 12); + if (hasInitializer) { + let start, end; + param = { + type: "AssignmentPattern", + decorators: null, + left: null, + right: null, + optional, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + param.decorators = deserializeVecDecorator(pos + 16); + param.left = deserializeBindingPattern(pos + 40); + param.left.decorators = []; + param.left.optional = false; + let leftTypeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + param.left.typeAnnotation = leftTypeAnnotation; + if (leftTypeAnnotation !== null) { + param.left.end = leftTypeAnnotation.end; + param.left.range[1] = leftTypeAnnotation.end; + } + param.right = deserializeOptionBoxExpression(pos + 64); + } else { + param = deserializeBindingPattern(pos + 40); + param.decorators = deserializeVecDecorator(pos + 16); + param.optional = optional; + let typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + param.typeAnnotation = typeAnnotation; + if (typeAnnotation !== null) { + param.end = typeAnnotation.end; + param.range[1] = typeAnnotation.end; + } else if (optional) { + param.end = deserializeI32(pos + 4); + param.range[1] = deserializeI32(pos + 4); + } + } + } else { + let start, end; + param = { + type: "TSParameterProperty", + accessibility, + decorators: null, + override, + parameter: null, + readonly, + static: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + param.decorators = deserializeVecDecorator(pos + 16); + if (hasInitializer) { + let pattern = deserializeBindingPattern(pos + 40), + initializer = deserializeOptionBoxExpression(pos + 64), + assignStart, + assignEnd, + assignParam = { + type: "AssignmentPattern", + decorators: [], + left: null, + right: null, + optional: false, + typeAnnotation: null, + start: (assignStart = pattern.start), + end: (assignEnd = initializer.end), + range: [assignStart, assignEnd], + }; + assignParam.left = pattern; + pattern.decorators = []; + pattern.optional = false; + let patternTypeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + pattern.typeAnnotation = patternTypeAnnotation; + if (patternTypeAnnotation !== null) { + pattern.end = patternTypeAnnotation.end; + pattern.range[1] = patternTypeAnnotation.end; + } + assignParam.right = initializer; + param.parameter = assignParam; + } else { + param.parameter = deserializeBindingPattern(pos + 40); + param.parameter.decorators = []; + let paramOptional = deserializeBool(pos + 12); + param.parameter.optional = paramOptional; + let paramTypeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + param.parameter.typeAnnotation = paramTypeAnnotation; + if (paramTypeAnnotation !== null) { + param.parameter.end = paramTypeAnnotation.end; + param.parameter.range[1] = paramTypeAnnotation.end; + } else if (paramOptional) { + let paramEnd = deserializeI32(pos + 4); + param.parameter.end = paramEnd; + param.parameter.range[1] = paramEnd; + } + } + } + } + return param; +} + +function deserializeFunctionBody(pos) { + let start, + end, + node = { + type: "BlockStatement", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeArrowFunctionExpression(pos) { + let expression = deserializeBool(pos + 48), + start, + end, + node = { + type: "ArrowFunctionExpression", + expression, + async: deserializeBool(pos + 49), + typeParameters: null, + params: null, + returnType: null, + body: null, + id: null, + generator: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + body = deserializeBoxFunctionBody(pos + 40); + expression === true && (body = body.body[0].expression); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 32); + node.body = body; + return node; +} + +function deserializeYieldExpression(pos) { + let start, + end, + node = { + type: "YieldExpression", + delegate: deserializeBool(pos + 12), + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeOptionExpression(pos + 16); + return node; +} + +function deserializeClass(pos) { + let start, + end, + node = { + type: deserializeClassType(pos + 136), + decorators: null, + id: null, + typeParameters: null, + superClass: null, + superTypeArguments: null, + implements: null, + body: null, + abstract: deserializeBool(pos + 137), + declare: deserializeBool(pos + 138), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.id = deserializeOptionBindingIdentifier(pos + 40); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 72); + node.superClass = deserializeOptionExpression(pos + 80); + node.superTypeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 96); + node.implements = deserializeVecTSClassImplements(pos + 104); + node.body = deserializeBoxClassBody(pos + 128); + return node; +} + +function deserializeClassType(pos) { + switch (uint8[pos]) { + case 0: + return "ClassDeclaration"; + case 1: + return "ClassExpression"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassType`); + } +} + +function deserializeClassBody(pos) { + let start, + end, + node = { + type: "ClassBody", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecClassElement(pos + 16); + return node; +} + +function deserializeClassElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStaticBlock(pos + 8); + case 1: + return deserializeBoxMethodDefinition(pos + 8); + case 2: + return deserializeBoxPropertyDefinition(pos + 8); + case 3: + return deserializeBoxAccessorProperty(pos + 8); + case 4: + return deserializeBoxTSIndexSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ClassElement`); + } +} + +function deserializeMethodDefinition(pos) { + let start, + end, + node = { + type: deserializeMethodDefinitionType(pos + 12), + decorators: null, + key: null, + value: null, + kind: deserializeMethodDefinitionKind(pos + 13), + computed: deserializeBool(pos + 14), + static: deserializeBool(pos + 15), + override: deserializeBool(pos + 64), + optional: deserializeBool(pos + 65), + accessibility: deserializeOptionTSAccessibility(pos + 66), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.value = deserializeBoxFunction(pos + 56); + return node; +} + +function deserializeMethodDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "MethodDefinition"; + case 1: + return "TSAbstractMethodDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionType`); + } +} + +function deserializePropertyDefinition(pos) { + let start, + end, + node = { + type: deserializePropertyDefinitionType(pos + 12), + decorators: null, + key: null, + typeAnnotation: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + declare: deserializeBool(pos + 15), + override: deserializeBool(pos + 80), + optional: deserializeBool(pos + 81), + definite: deserializeBool(pos + 82), + readonly: deserializeBool(pos + 83), + accessibility: deserializeOptionTSAccessibility(pos + 84), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializePropertyDefinitionType(pos) { + switch (uint8[pos]) { + case 0: + return "PropertyDefinition"; + case 1: + return "TSAbstractPropertyDefinition"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for PropertyDefinitionType`); + } +} + +function deserializeMethodDefinitionKind(pos) { + switch (uint8[pos]) { + case 0: + return "constructor"; + case 1: + return "method"; + case 2: + return "get"; + case 3: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for MethodDefinitionKind`); + } +} + +function deserializePrivateIdentifier(pos) { + let start, end; + return { + type: "PrivateIdentifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeStaticBlock(pos) { + let start, + end, + node = { + type: "StaticBlock", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecStatement(pos + 16); + return node; +} + +function deserializeAccessorPropertyType(pos) { + switch (uint8[pos]) { + case 0: + return "AccessorProperty"; + case 1: + return "TSAbstractAccessorProperty"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AccessorPropertyType`); + } +} + +function deserializeAccessorProperty(pos) { + let start, + end, + node = { + type: deserializeAccessorPropertyType(pos + 12), + decorators: null, + key: null, + typeAnnotation: null, + value: null, + computed: deserializeBool(pos + 13), + static: deserializeBool(pos + 14), + override: deserializeBool(pos + 15), + definite: deserializeBool(pos + 80), + accessibility: deserializeOptionTSAccessibility(pos + 81), + declare: false, + optional: false, + readonly: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.decorators = deserializeVecDecorator(pos + 16); + node.key = deserializePropertyKey(pos + 40); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 56); + node.value = deserializeOptionExpression(pos + 64); + return node; +} + +function deserializeImportExpression(pos) { + let start, + end, + node = { + type: "ImportExpression", + source: null, + options: null, + phase: deserializeOptionImportPhase(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.source = deserializeExpression(pos + 16); + node.options = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeImportDeclaration(pos) { + let start, + end, + node = { + type: "ImportDeclaration", + specifiers: null, + source: null, + phase: deserializeOptionImportPhase(pos + 12), + attributes: null, + importKind: deserializeImportOrExportKind(pos + 13), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + specifiers = deserializeOptionVecImportDeclarationSpecifier(pos + 16); + specifiers === null && (specifiers = []); + let withClause = deserializeOptionBoxWithClause(pos + 88); + node.specifiers = specifiers; + node.source = deserializeStringLiteral(pos + 40); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeImportPhase(pos) { + switch (uint8[pos]) { + case 0: + return "source"; + case 1: + return "defer"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportPhase`); + } +} + +function deserializeImportDeclarationSpecifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxImportSpecifier(pos + 8); + case 1: + return deserializeBoxImportDefaultSpecifier(pos + 8); + case 2: + return deserializeBoxImportNamespaceSpecifier(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportDeclarationSpecifier`); + } +} + +function deserializeImportSpecifier(pos) { + let start, + end, + node = { + type: "ImportSpecifier", + imported: null, + local: null, + importKind: deserializeImportOrExportKind(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.imported = deserializeModuleExportName(pos + 16); + node.local = deserializeBindingIdentifier(pos + 72); + return node; +} + +function deserializeImportDefaultSpecifier(pos) { + let start, + end, + node = { + type: "ImportDefaultSpecifier", + local: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeImportNamespaceSpecifier(pos) { + let start, + end, + node = { + type: "ImportNamespaceSpecifier", + local: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.local = deserializeBindingIdentifier(pos + 16); + return node; +} + +function deserializeWithClause(pos) { + return { attributes: deserializeVecImportAttribute(pos + 16) }; +} + +function deserializeImportAttribute(pos) { + let start, + end, + node = { + type: "ImportAttribute", + key: null, + value: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializeImportAttributeKey(pos + 16); + node.value = deserializeStringLiteral(pos + 72); + return node; +} + +function deserializeImportAttributeKey(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportAttributeKey`); + } +} + +function deserializeExportNamedDeclaration(pos) { + let start, + end, + node = { + type: "ExportNamedDeclaration", + declaration: null, + specifiers: null, + source: null, + exportKind: deserializeImportOrExportKind(pos + 12), + attributes: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + withClause = deserializeOptionBoxWithClause(pos + 104); + node.declaration = deserializeOptionDeclaration(pos + 16); + node.specifiers = deserializeVecExportSpecifier(pos + 32); + node.source = deserializeOptionStringLiteral(pos + 56); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportDefaultDeclaration(pos) { + let start, + end, + node = { + type: "ExportDefaultDeclaration", + declaration: null, + exportKind: "value", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.declaration = deserializeExportDefaultDeclarationKind(pos + 16); + return node; +} + +function deserializeExportAllDeclaration(pos) { + let start, + end, + node = { + type: "ExportAllDeclaration", + exported: null, + source: null, + attributes: null, + exportKind: deserializeImportOrExportKind(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + withClause = deserializeOptionBoxWithClause(pos + 120); + node.exported = deserializeOptionModuleExportName(pos + 16); + node.source = deserializeStringLiteral(pos + 72); + node.attributes = withClause === null ? [] : withClause.attributes; + return node; +} + +function deserializeExportSpecifier(pos) { + let start, + end, + node = { + type: "ExportSpecifier", + local: null, + exported: null, + exportKind: deserializeImportOrExportKind(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.local = deserializeModuleExportName(pos + 16); + node.exported = deserializeModuleExportName(pos + 72); + return node; +} + +function deserializeExportDefaultDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeBoxFunction(pos + 8); + case 65: + return deserializeBoxClass(pos + 8); + case 66: + return deserializeBoxTSInterfaceDeclaration(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportDefaultDeclarationKind`); + } +} + +function deserializeModuleExportName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeIdentifierName(pos + 8); + case 1: + return deserializeIdentifierReference(pos + 8); + case 2: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleExportName`); + } +} + +function deserializeV8IntrinsicExpression(pos) { + let start, + end, + node = { + type: "V8IntrinsicExpression", + name: null, + arguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeIdentifierName(pos + 16); + node.arguments = deserializeVecArgument(pos + 48); + return node; +} + +function deserializeBooleanLiteral(pos) { + let value = deserializeBool(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value, + raw: null, + start, + end, + range: [start, end], + }; + node.raw = start === 0 && end === 0 ? null : value + ""; + return node; +} + +function deserializeNullLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: null, + raw: start === 0 && end === 0 ? null : "null", + start, + end, + range: [start, end], + }; +} + +function deserializeNumericLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "Literal", + value: deserializeF64(pos + 32), + raw: + int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + range: [start, end], + }; +} + +function deserializeStringLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + range: [start, end], + }, + value = deserializeStr(pos + 16); + deserializeBool(pos + 12) && + (value = value.replace(/\uFFFD(.{4})/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))); + node.value = value; + return node; +} + +function deserializeBigIntLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + bigint = deserializeStr(pos + 16); + return { + type: "Literal", + value: BigInt(bigint), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + bigint, + start, + end, + range: [start, end], + }; +} + +function deserializeRegExpLiteral(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4), + node = { + type: "Literal", + value: null, + raw: + int32[(pos >> 2) + 12] === 0 && int32[(pos >> 2) + 13] === 0 + ? null + : sourceText.slice(start, end), + regex: null, + start, + end, + range: [start, end], + }, + regex = deserializeRegExp(pos + 16), + value = null; + try { + value = new RegExp(regex.pattern, regex.flags); + } catch {} + node.value = value; + node.regex = regex; + return node; +} + +function deserializeRegExp(pos) { + return { + pattern: deserializeStr(pos), + flags: deserializeRegExpFlags(pos + 24), + }; +} + +function deserializeRegExpFlags(pos) { + let flagBits = deserializeU8(pos), + flags = ""; + // Alphabetical order + flagBits & 64 && (flags += "d"); + flagBits & 1 && (flags += "g"); + flagBits & 2 && (flags += "i"); + flagBits & 4 && (flags += "m"); + flagBits & 8 && (flags += "s"); + flagBits & 16 && (flags += "u"); + flagBits & 128 && (flags += "v"); + flagBits & 32 && (flags += "y"); + return flags; +} + +function deserializeJSXElement(pos) { + let start, + end, + node = { + type: "JSXElement", + openingElement: null, + children: null, + closingElement: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + closingElement = deserializeOptionBoxJSXClosingElement(pos + 48), + openingElement = deserializeBoxJSXOpeningElement(pos + 16); + closingElement === null && (openingElement.selfClosing = true); + node.openingElement = openingElement; + node.children = deserializeVecJSXChild(pos + 24); + node.closingElement = closingElement; + return node; +} + +function deserializeJSXOpeningElement(pos) { + let start, + end, + node = { + type: "JSXOpeningElement", + name: null, + typeArguments: null, + attributes: null, + selfClosing: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeJSXElementName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + node.attributes = deserializeVecJSXAttributeItem(pos + 40); + return node; +} + +function deserializeJSXClosingElement(pos) { + let start, + end, + node = { + type: "JSXClosingElement", + name: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeJSXElementName(pos + 16); + return node; +} + +function deserializeJSXFragment(pos) { + let start, + end, + node = { + type: "JSXFragment", + openingFragment: null, + children: null, + closingFragment: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.openingFragment = deserializeJSXOpeningFragment(pos + 16); + node.children = deserializeVecJSXChild(pos + 32); + node.closingFragment = deserializeJSXClosingFragment(pos + 56); + return node; +} + +function deserializeJSXOpeningFragment(pos) { + let start, end; + return { + type: "JSXOpeningFragment", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXClosingFragment(pos) { + let start, end; + return { + type: "JSXClosingFragment", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXElementName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + range: ident.range, + }; + case 2: + return deserializeBoxJSXNamespacedName(pos + 8); + case 3: + return deserializeBoxJSXMemberExpression(pos + 8); + case 4: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + range: thisExpr.range, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXElementName`); + } +} + +function deserializeJSXNamespacedName(pos) { + let start, + end, + node = { + type: "JSXNamespacedName", + namespace: null, + name: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.namespace = deserializeJSXIdentifier(pos + 16); + node.name = deserializeJSXIdentifier(pos + 48); + return node; +} + +function deserializeJSXMemberExpression(pos) { + let start, + end, + node = { + type: "JSXMemberExpression", + object: null, + property: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.object = deserializeJSXMemberExpressionObject(pos + 16); + node.property = deserializeJSXIdentifier(pos + 32); + return node; +} + +function deserializeJSXMemberExpressionObject(pos) { + switch (uint8[pos]) { + case 0: + let ident = deserializeBoxIdentifierReference(pos + 8); + return { + type: "JSXIdentifier", + name: ident.name, + start: ident.start, + end: ident.end, + range: ident.range, + }; + case 1: + return deserializeBoxJSXMemberExpression(pos + 8); + case 2: + let thisExpr = deserializeBoxThisExpression(pos + 8); + return { + type: "JSXIdentifier", + name: "this", + start: thisExpr.start, + end: thisExpr.end, + range: thisExpr.range, + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXMemberExpressionObject`); + } +} + +function deserializeJSXExpressionContainer(pos) { + let start, + end, + node = { + type: "JSXExpressionContainer", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeJSXExpression(pos + 16); + return node; +} + +function deserializeJSXExpression(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNullLiteral(pos + 8); + case 2: + return deserializeBoxNumericLiteral(pos + 8); + case 3: + return deserializeBoxBigIntLiteral(pos + 8); + case 4: + return deserializeBoxRegExpLiteral(pos + 8); + case 5: + return deserializeBoxStringLiteral(pos + 8); + case 6: + return deserializeBoxTemplateLiteral(pos + 8); + case 7: + return deserializeBoxIdentifierReference(pos + 8); + case 8: + return deserializeBoxMetaProperty(pos + 8); + case 9: + return deserializeBoxSuper(pos + 8); + case 10: + return deserializeBoxArrayExpression(pos + 8); + case 11: + return deserializeBoxArrowFunctionExpression(pos + 8); + case 12: + return deserializeBoxAssignmentExpression(pos + 8); + case 13: + return deserializeBoxAwaitExpression(pos + 8); + case 14: + return deserializeBoxBinaryExpression(pos + 8); + case 15: + return deserializeBoxCallExpression(pos + 8); + case 16: + return deserializeBoxChainExpression(pos + 8); + case 17: + return deserializeBoxClass(pos + 8); + case 18: + return deserializeBoxConditionalExpression(pos + 8); + case 19: + return deserializeBoxFunction(pos + 8); + case 20: + return deserializeBoxImportExpression(pos + 8); + case 21: + return deserializeBoxLogicalExpression(pos + 8); + case 22: + return deserializeBoxNewExpression(pos + 8); + case 23: + return deserializeBoxObjectExpression(pos + 8); + case 24: + return deserializeBoxParenthesizedExpression(pos + 8); + case 25: + return deserializeBoxSequenceExpression(pos + 8); + case 26: + return deserializeBoxTaggedTemplateExpression(pos + 8); + case 27: + return deserializeBoxThisExpression(pos + 8); + case 28: + return deserializeBoxUnaryExpression(pos + 8); + case 29: + return deserializeBoxUpdateExpression(pos + 8); + case 30: + return deserializeBoxYieldExpression(pos + 8); + case 31: + return deserializeBoxPrivateInExpression(pos + 8); + case 32: + return deserializeBoxJSXElement(pos + 8); + case 33: + return deserializeBoxJSXFragment(pos + 8); + case 34: + return deserializeBoxTSAsExpression(pos + 8); + case 35: + return deserializeBoxTSSatisfiesExpression(pos + 8); + case 36: + return deserializeBoxTSTypeAssertion(pos + 8); + case 37: + return deserializeBoxTSNonNullExpression(pos + 8); + case 38: + return deserializeBoxTSInstantiationExpression(pos + 8); + case 39: + return deserializeBoxV8IntrinsicExpression(pos + 8); + case 48: + return deserializeBoxComputedMemberExpression(pos + 8); + case 49: + return deserializeBoxStaticMemberExpression(pos + 8); + case 50: + return deserializeBoxPrivateFieldExpression(pos + 8); + case 64: + return deserializeJSXEmptyExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXExpression`); + } +} + +function deserializeJSXEmptyExpression(pos) { + let start, end; + return { + type: "JSXEmptyExpression", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXAttributeItem(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXAttribute(pos + 8); + case 1: + return deserializeBoxJSXSpreadAttribute(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeItem`); + } +} + +function deserializeJSXAttribute(pos) { + let start, + end, + node = { + type: "JSXAttribute", + name: null, + value: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeJSXAttributeName(pos + 16); + node.value = deserializeOptionJSXAttributeValue(pos + 32); + return node; +} + +function deserializeJSXSpreadAttribute(pos) { + let start, + end, + node = { + type: "JSXSpreadAttribute", + argument: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.argument = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXAttributeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXIdentifier(pos + 8); + case 1: + return deserializeBoxJSXNamespacedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeName`); + } +} + +function deserializeJSXAttributeValue(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxStringLiteral(pos + 8); + case 1: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 2: + return deserializeBoxJSXElement(pos + 8); + case 3: + return deserializeBoxJSXFragment(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXAttributeValue`); + } +} + +function deserializeJSXIdentifier(pos) { + let start, end; + return { + type: "JSXIdentifier", + name: deserializeStr(pos + 16), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeJSXChild(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxJSXText(pos + 8); + case 1: + return deserializeBoxJSXElement(pos + 8); + case 2: + return deserializeBoxJSXFragment(pos + 8); + case 3: + return deserializeBoxJSXExpressionContainer(pos + 8); + case 4: + return deserializeBoxJSXSpreadChild(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for JSXChild`); + } +} + +function deserializeJSXSpreadChild(pos) { + let start, + end, + node = { + type: "JSXSpreadChild", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeJSXText(pos) { + let start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type: "JSXText", + value: deserializeStr(pos + 16), + raw: + int32[(pos >> 2) + 8] === 0 && int32[(pos >> 2) + 9] === 0 + ? null + : sourceText.slice(start, end), + start, + end, + range: [start, end], + }; +} + +function deserializeTSThisParameter(pos) { + let start, + end, + node = { + type: "Identifier", + decorators: [], + name: "this", + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 24); + return node; +} + +function deserializeTSEnumDeclaration(pos) { + let start, + end, + node = { + type: "TSEnumDeclaration", + id: null, + body: null, + const: deserializeBool(pos + 12), + declare: deserializeBool(pos + 13), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.body = deserializeTSEnumBody(pos + 48); + return node; +} + +function deserializeTSEnumBody(pos) { + let start, + end, + node = { + type: "TSEnumBody", + members: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.members = deserializeVecTSEnumMember(pos + 16); + return node; +} + +function deserializeTSEnumMember(pos) { + let start, + end, + node = { + type: "TSEnumMember", + id: null, + initializer: null, + computed: deserializeU8(pos + 16) > 1, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeTSEnumMemberName(pos + 16); + node.initializer = deserializeOptionExpression(pos + 32); + return node; +} + +function deserializeTSEnumMemberName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxStringLiteral(pos + 8); + case 2: + return deserializeBoxStringLiteral(pos + 8); + case 3: + return deserializeBoxTemplateLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSEnumMemberName`); + } +} + +function deserializeTSTypeAnnotation(pos) { + let start, + end, + node = { + type: "TSTypeAnnotation", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSLiteralType(pos) { + let start, + end, + node = { + type: "TSLiteralType", + literal: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.literal = deserializeTSLiteral(pos + 16); + return node; +} + +function deserializeTSLiteral(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxBooleanLiteral(pos + 8); + case 1: + return deserializeBoxNumericLiteral(pos + 8); + case 2: + return deserializeBoxBigIntLiteral(pos + 8); + case 3: + return deserializeBoxStringLiteral(pos + 8); + case 4: + return deserializeBoxTemplateLiteral(pos + 8); + case 5: + return deserializeBoxUnaryExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSLiteral`); + } +} + +function deserializeTSType(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSType`); + } +} + +function deserializeTSConditionalType(pos) { + let start, + end, + node = { + type: "TSConditionalType", + checkType: null, + extendsType: null, + trueType: null, + falseType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.checkType = deserializeTSType(pos + 16); + node.extendsType = deserializeTSType(pos + 32); + node.trueType = deserializeTSType(pos + 48); + node.falseType = deserializeTSType(pos + 64); + return node; +} + +function deserializeTSUnionType(pos) { + let start, + end, + node = { + type: "TSUnionType", + types: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSIntersectionType(pos) { + let start, + end, + node = { + type: "TSIntersectionType", + types: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.types = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSParenthesizedType(pos) { + let node; + { + let start, end; + node = { + type: "TSParenthesizedType", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + } + return node; +} + +function deserializeTSTypeOperator(pos) { + let start, + end, + node = { + type: "TSTypeOperator", + operator: deserializeTSTypeOperatorOperator(pos + 12), + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTypeOperatorOperator(pos) { + switch (uint8[pos]) { + case 0: + return "keyof"; + case 1: + return "unique"; + case 2: + return "readonly"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeOperatorOperator`); + } +} + +function deserializeTSArrayType(pos) { + let start, + end, + node = { + type: "TSArrayType", + elementType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.elementType = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSIndexedAccessType(pos) { + let start, + end, + node = { + type: "TSIndexedAccessType", + objectType: null, + indexType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.objectType = deserializeTSType(pos + 16); + node.indexType = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTupleType(pos) { + let start, + end, + node = { + type: "TSTupleType", + elementTypes: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.elementTypes = deserializeVecTSTupleElement(pos + 16); + return node; +} + +function deserializeTSNamedTupleMember(pos) { + let start, + end, + node = { + type: "TSNamedTupleMember", + label: null, + elementType: null, + optional: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.label = deserializeIdentifierName(pos + 16); + node.elementType = deserializeTSTupleElement(pos + 48); + return node; +} + +function deserializeTSOptionalType(pos) { + let start, + end, + node = { + type: "TSOptionalType", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSRestType(pos) { + let start, + end, + node = { + type: "TSRestType", + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeTSTupleElement(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSAnyKeyword(pos + 8); + case 1: + return deserializeBoxTSBigIntKeyword(pos + 8); + case 2: + return deserializeBoxTSBooleanKeyword(pos + 8); + case 3: + return deserializeBoxTSIntrinsicKeyword(pos + 8); + case 4: + return deserializeBoxTSNeverKeyword(pos + 8); + case 5: + return deserializeBoxTSNullKeyword(pos + 8); + case 6: + return deserializeBoxTSNumberKeyword(pos + 8); + case 7: + return deserializeBoxTSObjectKeyword(pos + 8); + case 8: + return deserializeBoxTSStringKeyword(pos + 8); + case 9: + return deserializeBoxTSSymbolKeyword(pos + 8); + case 10: + return deserializeBoxTSThisType(pos + 8); + case 11: + return deserializeBoxTSUndefinedKeyword(pos + 8); + case 12: + return deserializeBoxTSUnknownKeyword(pos + 8); + case 13: + return deserializeBoxTSVoidKeyword(pos + 8); + case 14: + return deserializeBoxTSArrayType(pos + 8); + case 15: + return deserializeBoxTSConditionalType(pos + 8); + case 16: + return deserializeBoxTSConstructorType(pos + 8); + case 17: + return deserializeBoxTSFunctionType(pos + 8); + case 18: + return deserializeBoxTSImportType(pos + 8); + case 19: + return deserializeBoxTSIndexedAccessType(pos + 8); + case 20: + return deserializeBoxTSInferType(pos + 8); + case 21: + return deserializeBoxTSIntersectionType(pos + 8); + case 22: + return deserializeBoxTSLiteralType(pos + 8); + case 23: + return deserializeBoxTSMappedType(pos + 8); + case 24: + return deserializeBoxTSNamedTupleMember(pos + 8); + case 26: + return deserializeBoxTSTemplateLiteralType(pos + 8); + case 27: + return deserializeBoxTSTupleType(pos + 8); + case 28: + return deserializeBoxTSTypeLiteral(pos + 8); + case 29: + return deserializeBoxTSTypeOperator(pos + 8); + case 30: + return deserializeBoxTSTypePredicate(pos + 8); + case 31: + return deserializeBoxTSTypeQuery(pos + 8); + case 32: + return deserializeBoxTSTypeReference(pos + 8); + case 33: + return deserializeBoxTSUnionType(pos + 8); + case 34: + return deserializeBoxTSParenthesizedType(pos + 8); + case 35: + return deserializeBoxJSDocNullableType(pos + 8); + case 36: + return deserializeBoxJSDocNonNullableType(pos + 8); + case 37: + return deserializeBoxJSDocUnknownType(pos + 8); + case 64: + return deserializeBoxTSOptionalType(pos + 8); + case 65: + return deserializeBoxTSRestType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTupleElement`); + } +} + +function deserializeTSAnyKeyword(pos) { + let start, end; + return { + type: "TSAnyKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSStringKeyword(pos) { + let start, end; + return { + type: "TSStringKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSBooleanKeyword(pos) { + let start, end; + return { + type: "TSBooleanKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSNumberKeyword(pos) { + let start, end; + return { + type: "TSNumberKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSNeverKeyword(pos) { + let start, end; + return { + type: "TSNeverKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSIntrinsicKeyword(pos) { + let start, end; + return { + type: "TSIntrinsicKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSUnknownKeyword(pos) { + let start, end; + return { + type: "TSUnknownKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSNullKeyword(pos) { + let start, end; + return { + type: "TSNullKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSUndefinedKeyword(pos) { + let start, end; + return { + type: "TSUndefinedKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSVoidKeyword(pos) { + let start, end; + return { + type: "TSVoidKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSSymbolKeyword(pos) { + let start, end; + return { + type: "TSSymbolKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSThisType(pos) { + let start, end; + return { + type: "TSThisType", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSObjectKeyword(pos) { + let start, end; + return { + type: "TSObjectKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSBigIntKeyword(pos) { + let start, end; + return { + type: "TSBigIntKeyword", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeTSTypeReference(pos) { + let start, + end, + node = { + type: "TSTypeReference", + typeName: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeName = deserializeTSTypeName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeName`); + } +} + +function deserializeTSQualifiedName(pos) { + let start, + end, + node = { + type: "TSQualifiedName", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeTSTypeName(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSTypeParameterInstantiation(pos) { + let start, + end, + node = { + type: "TSTypeParameterInstantiation", + params: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.params = deserializeVecTSType(pos + 16); + return node; +} + +function deserializeTSTypeParameter(pos) { + let start, + end, + node = { + type: "TSTypeParameter", + name: null, + constraint: null, + default: null, + in: deserializeBool(pos + 12), + out: deserializeBool(pos + 13), + const: deserializeBool(pos + 14), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.name = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeOptionTSType(pos + 48); + node.default = deserializeOptionTSType(pos + 64); + return node; +} + +function deserializeTSTypeParameterDeclaration(pos) { + let start, + end, + node = { + type: "TSTypeParameterDeclaration", + params: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.params = deserializeVecTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeAliasDeclaration(pos) { + let start, + end, + node = { + type: "TSTypeAliasDeclaration", + id: null, + typeParameters: null, + typeAnnotation: null, + declare: deserializeBool(pos + 72), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.typeAnnotation = deserializeTSType(pos + 56); + return node; +} + +function deserializeTSAccessibility(pos) { + switch (uint8[pos]) { + case 0: + return "private"; + case 1: + return "protected"; + case 2: + return "public"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSAccessibility`); + } +} + +function deserializeTSClassImplements(pos) { + let start, + end, + node = { + type: "TSClassImplements", + expression: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + expression = deserializeTSTypeName(pos + 16); + if (expression.type === "TSQualifiedName") { + let object = expression.left, + { right } = expression, + start, + end, + previous = (expression = { + type: "MemberExpression", + object, + property: right, + optional: false, + computed: false, + start: (start = expression.start), + end: (end = expression.end), + range: [start, end], + }); + for (; object.type === "TSQualifiedName"; ) { + let { left, right } = object; + previous = previous.object = { + type: "MemberExpression", + object: left, + property: right, + optional: false, + computed: false, + start: (start = object.start), + end: (end = object.end), + range: [start, end], + }; + object = left; + } + } + node.expression = expression; + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSInterfaceDeclaration(pos) { + let start, + end, + node = { + type: "TSInterfaceDeclaration", + id: null, + typeParameters: null, + extends: null, + body: null, + declare: deserializeBool(pos + 88), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 48); + node.extends = deserializeVecTSInterfaceHeritage(pos + 56); + node.body = deserializeBoxTSInterfaceBody(pos + 80); + return node; +} + +function deserializeTSInterfaceBody(pos) { + let start, + end, + node = { + type: "TSInterfaceBody", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.body = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSPropertySignature(pos) { + let start, + end, + node = { + type: "TSPropertySignature", + computed: deserializeBool(pos + 12), + optional: deserializeBool(pos + 13), + readonly: deserializeBool(pos + 14), + key: null, + typeAnnotation: null, + accessibility: null, + static: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.key = deserializePropertyKey(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSSignature(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSIndexSignature(pos + 8); + case 1: + return deserializeBoxTSPropertySignature(pos + 8); + case 2: + return deserializeBoxTSCallSignatureDeclaration(pos + 8); + case 3: + return deserializeBoxTSConstructSignatureDeclaration(pos + 8); + case 4: + return deserializeBoxTSMethodSignature(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSSignature`); + } +} + +function deserializeTSIndexSignature(pos) { + let start, + end, + node = { + type: "TSIndexSignature", + parameters: null, + typeAnnotation: null, + readonly: deserializeBool(pos + 12), + static: deserializeBool(pos + 13), + accessibility: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.parameters = deserializeVecTSIndexSignatureName(pos + 16); + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSCallSignatureDeclaration(pos) { + let start, + end, + node = { + type: "TSCallSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSMethodSignatureKind(pos) { + switch (uint8[pos]) { + case 0: + return "method"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMethodSignatureKind`); + } +} + +function deserializeTSMethodSignature(pos) { + let start, + end, + node = { + type: "TSMethodSignature", + key: null, + computed: deserializeBool(pos + 64), + optional: deserializeBool(pos + 65), + kind: deserializeTSMethodSignatureKind(pos + 66), + typeParameters: null, + params: null, + returnType: null, + accessibility: null, + readonly: false, + static: false, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 48), + thisParam = deserializeOptionBoxTSThisParameter(pos + 40); + thisParam !== null && params.unshift(thisParam); + node.key = deserializePropertyKey(pos + 16); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 32); + node.params = params; + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 56); + return node; +} + +function deserializeTSConstructSignatureDeclaration(pos) { + let start, + end, + node = { + type: "TSConstructSignatureDeclaration", + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeOptionBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSIndexSignatureName(pos) { + let start, + end, + node = { + type: "Identifier", + decorators: [], + name: deserializeStr(pos + 16), + optional: false, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSInterfaceHeritage(pos) { + let start, + end, + node = { + type: "TSInterfaceHeritage", + expression: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypePredicate(pos) { + let start, + end, + node = { + type: "TSTypePredicate", + parameterName: null, + asserts: deserializeBool(pos + 12), + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.parameterName = deserializeTSTypePredicateName(pos + 16); + node.typeAnnotation = deserializeOptionBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSTypePredicateName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeTSThisType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypePredicateName`); + } +} + +function deserializeTSModuleDeclaration(pos) { + let kind = deserializeTSModuleDeclarationKind(pos + 88), + start = deserializeI32(pos), + end = deserializeI32(pos + 4), + declare = deserializeBool(pos + 89), + node, + body = deserializeOptionTSModuleDeclarationBody(pos + 72); + if (body === null) { + node = { + type: "TSModuleDeclaration", + id: null, + // No `body` field + kind, + declare, + global: false, + start, + end, + range: [start, end], + }; + node.id = deserializeTSModuleDeclarationName(pos + 16); + } else { + node = { + type: "TSModuleDeclaration", + id: null, + body, + kind, + declare, + global: false, + start, + end, + range: [start, end], + }; + let id = deserializeTSModuleDeclarationName(pos + 16); + if (body.type === "TSModuleBlock") node.id = id; + else { + let innerId = body.id; + if (innerId.type === "Identifier") { + let start, end; + node.id = { + type: "TSQualifiedName", + left: id, + right: innerId, + start: (start = id.start), + end: (end = innerId.end), + range: [start, end], + }; + } else { + // Replace `left` of innermost `TSQualifiedName` with a nested `TSQualifiedName` with `id` of + // this module on left, and previous `left` of innermost `TSQualifiedName` on right + node.id = innerId; + let { start } = id; + for (;;) { + innerId.start = innerId.range[0] = start; + if (innerId.left.type === "Identifier") break; + innerId = innerId.left; + } + let end, + right = innerId.left; + innerId.left = { + type: "TSQualifiedName", + left: id, + right, + start, + end: (end = right.end), + range: [start, end], + }; + } + if (Object.hasOwn(body, "body")) { + body = body.body; + node.body = body; + } else body = null; + } + } + return node; +} + +function deserializeTSModuleDeclarationKind(pos) { + switch (uint8[pos]) { + case 0: + return "module"; + case 1: + return "namespace"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationKind`); + } +} + +function deserializeTSModuleDeclarationName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBindingIdentifier(pos + 8); + case 1: + return deserializeStringLiteral(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationName`); + } +} + +function deserializeTSModuleDeclarationBody(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSModuleDeclaration(pos + 8); + case 1: + return deserializeBoxTSModuleBlock(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleDeclarationBody`); + } +} + +function deserializeTSGlobalDeclaration(pos) { + let start, + end, + node = { + type: "TSModuleDeclaration", + id: null, + body: null, + kind: "global", + declare: deserializeBool(pos + 88), + global: true, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + keywordStart, + keywordEnd; + node.id = { + type: "Identifier", + decorators: [], + name: "global", + optional: false, + typeAnnotation: null, + start: (keywordStart = deserializeI32(pos + 16)), + end: (keywordEnd = deserializeI32(pos + 20)), + range: [keywordStart, keywordEnd], + }; + node.body = deserializeTSModuleBlock(pos + 24); + return node; +} + +function deserializeTSModuleBlock(pos) { + let start, + end, + node = { + type: "TSModuleBlock", + body: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + body = deserializeVecDirective(pos + 16); + body.push(...deserializeVecStatement(pos + 40)); + node.body = body; + return node; +} + +function deserializeTSTypeLiteral(pos) { + let start, + end, + node = { + type: "TSTypeLiteral", + members: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.members = deserializeVecTSSignature(pos + 16); + return node; +} + +function deserializeTSInferType(pos) { + let start, + end, + node = { + type: "TSInferType", + typeParameter: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeParameter = deserializeBoxTSTypeParameter(pos + 16); + return node; +} + +function deserializeTSTypeQuery(pos) { + let start, + end, + node = { + type: "TSTypeQuery", + exprName: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.exprName = deserializeTSTypeQueryExprName(pos + 16); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeTSTypeQueryExprName(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierReference(pos + 8); + case 1: + return deserializeBoxTSQualifiedName(pos + 8); + case 2: + return deserializeBoxThisExpression(pos + 8); + case 3: + return deserializeBoxTSImportType(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSTypeQueryExprName`); + } +} + +function deserializeTSImportType(pos) { + let start, + end, + node = { + type: "TSImportType", + source: null, + options: null, + qualifier: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.source = deserializeStringLiteral(pos + 16); + node.options = deserializeOptionBoxObjectExpression(pos + 64); + node.qualifier = deserializeOptionTSImportTypeQualifier(pos + 72); + node.typeArguments = deserializeOptionBoxTSTypeParameterInstantiation(pos + 88); + return node; +} + +function deserializeTSImportTypeQualifier(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxIdentifierName(pos + 8); + case 1: + return deserializeBoxTSImportTypeQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSImportTypeQualifier`); + } +} + +function deserializeTSImportTypeQualifiedName(pos) { + let start, + end, + node = { + type: "TSQualifiedName", + left: null, + right: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.left = deserializeTSImportTypeQualifier(pos + 16); + node.right = deserializeIdentifierName(pos + 32); + return node; +} + +function deserializeTSFunctionType(pos) { + let start, + end, + node = { + type: "TSFunctionType", + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + params = deserializeBoxFormalParameters(pos + 32), + thisParam = deserializeOptionBoxTSThisParameter(pos + 24); + thisParam !== null && params.unshift(thisParam); + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = params; + node.returnType = deserializeBoxTSTypeAnnotation(pos + 40); + return node; +} + +function deserializeTSConstructorType(pos) { + let start, + end, + node = { + type: "TSConstructorType", + abstract: deserializeBool(pos + 40), + typeParameters: null, + params: null, + returnType: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeParameters = deserializeOptionBoxTSTypeParameterDeclaration(pos + 16); + node.params = deserializeBoxFormalParameters(pos + 24); + node.returnType = deserializeBoxTSTypeAnnotation(pos + 32); + return node; +} + +function deserializeTSMappedType(pos) { + let start, + end, + node = { + type: "TSMappedType", + key: null, + constraint: null, + nameType: null, + typeAnnotation: null, + optional: null, + readonly: deserializeOptionTSMappedTypeModifierOperator(pos + 97), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }, + optional = deserializeOptionTSMappedTypeModifierOperator(pos + 96); + optional === null && (optional = false); + node.key = deserializeBindingIdentifier(pos + 16); + node.constraint = deserializeTSType(pos + 48); + node.nameType = deserializeOptionTSType(pos + 64); + node.typeAnnotation = deserializeOptionTSType(pos + 80); + node.optional = optional; + return node; +} + +function deserializeTSMappedTypeModifierOperator(pos) { + switch (uint8[pos]) { + case 0: + return true; + case 1: + return "+"; + case 2: + return "-"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSMappedTypeModifierOperator`); + } +} + +function deserializeTSTemplateLiteralType(pos) { + let start, + end, + node = { + type: "TSTemplateLiteralType", + quasis: null, + types: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.quasis = deserializeVecTemplateElement(pos + 16); + node.types = deserializeVecTSType(pos + 40); + return node; +} + +function deserializeTSAsExpression(pos) { + let start, + end, + node = { + type: "TSAsExpression", + expression: null, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSSatisfiesExpression(pos) { + let start, + end, + node = { + type: "TSSatisfiesExpression", + expression: null, + typeAnnotation: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeAnnotation = deserializeTSType(pos + 32); + return node; +} + +function deserializeTSTypeAssertion(pos) { + let start, + end, + node = { + type: "TSTypeAssertion", + typeAnnotation: null, + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + node.expression = deserializeExpression(pos + 32); + return node; +} + +function deserializeTSImportEqualsDeclaration(pos) { + let start, + end, + node = { + type: "TSImportEqualsDeclaration", + id: null, + moduleReference: null, + importKind: deserializeImportOrExportKind(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeBindingIdentifier(pos + 16); + node.moduleReference = deserializeTSModuleReference(pos + 48); + return node; +} + +function deserializeTSModuleReference(pos) { + switch (uint8[pos]) { + case 0: + return deserializeBoxTSExternalModuleReference(pos + 8); + case 1: + return deserializeBoxIdentifierReference(pos + 8); + case 2: + return deserializeBoxTSQualifiedName(pos + 8); + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for TSModuleReference`); + } +} + +function deserializeTSExternalModuleReference(pos) { + let start, + end, + node = { + type: "TSExternalModuleReference", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeStringLiteral(pos + 16); + return node; +} + +function deserializeTSNonNullExpression(pos) { + let start, + end, + node = { + type: "TSNonNullExpression", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeDecorator(pos) { + let start, + end, + node = { + type: "Decorator", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSExportAssignment(pos) { + let start, + end, + node = { + type: "TSExportAssignment", + expression: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + return node; +} + +function deserializeTSNamespaceExportDeclaration(pos) { + let start, + end, + node = { + type: "TSNamespaceExportDeclaration", + id: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.id = deserializeIdentifierName(pos + 16); + return node; +} + +function deserializeTSInstantiationExpression(pos) { + let start, + end, + node = { + type: "TSInstantiationExpression", + expression: null, + typeArguments: null, + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.expression = deserializeExpression(pos + 16); + node.typeArguments = deserializeBoxTSTypeParameterInstantiation(pos + 32); + return node; +} + +function deserializeImportOrExportKind(pos) { + switch (uint8[pos]) { + case 0: + return "value"; + case 1: + return "type"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportOrExportKind`); + } +} + +function deserializeJSDocNullableType(pos) { + let start, + end, + node = { + type: "TSJSDocNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocNonNullableType(pos) { + let start, + end, + node = { + type: "TSJSDocNonNullableType", + typeAnnotation: null, + postfix: deserializeBool(pos + 12), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; + node.typeAnnotation = deserializeTSType(pos + 16); + return node; +} + +function deserializeJSDocUnknownType(pos) { + let start, end; + return { + type: "TSJSDocUnknownType", + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeCommentKind(pos) { + switch (uint8[pos]) { + case 0: + return "Line"; + case 1: + return "Block"; + case 2: + return "Block"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for CommentKind`); + } +} + +function deserializeComment(pos) { + let type = deserializeCommentKind(pos + 12), + start = deserializeI32(pos), + end = deserializeI32(pos + 4); + return { + type, + value: sourceText.slice(start + 2, end - (type === "Line" ? 0 : 2)), + start, + end, + range: [start, end], + }; +} + +function deserializeModuleKind(pos) { + switch (uint8[pos]) { + case 0: + return "script"; + case 1: + return "module"; + case 3: + return "commonjs"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ModuleKind`); + } +} + +function deserializeSpan(pos) { + return { + start: deserializeI32(pos), + end: deserializeI32(pos + 4), + }; +} + +function deserializeNameSpan(pos) { + let start, end; + return { + value: deserializeStr(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeImportEntry(pos) { + return { + importName: deserializeImportImportName(pos + 32), + localName: deserializeNameSpan(pos + 64), + isType: deserializeBool(pos + 88), + }; +} + +function deserializeImportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + return { + kind: "NamespaceObject", + name: null, + start: null, + end: null, + range: [null, null], + }; + case 2: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + range: [start, end], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ImportImportName`); + } +} + +function deserializeExportEntry(pos) { + let start, end; + return { + moduleRequest: deserializeOptionNameSpan(pos + 16), + importName: deserializeExportImportName(pos + 40), + exportName: deserializeExportExportName(pos + 72), + localName: deserializeExportLocalName(pos + 104), + isType: deserializeBool(pos + 136), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeExportImportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + return { + kind: "All", + name: null, + start: null, + end: null, + range: [null, null], + }; + case 2: + return { + kind: "AllButDefault", + name: null, + start: null, + end: null, + range: [null, null], + }; + case 3: + return { + kind: "None", + name: null, + start: null, + end: null, + range: [null, null], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportImportName`); + } +} + +function deserializeExportExportName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + var { start, end } = deserializeSpan(pos + 8); + return { + kind: "Default", + name: null, + start, + end, + range: [start, end], + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + range: [null, null], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportExportName`); + } +} + +function deserializeExportLocalName(pos) { + switch (uint8[pos]) { + case 0: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Name", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 1: + var nameSpan = deserializeNameSpan(pos + 8); + return { + kind: "Default", + name: nameSpan.value, + start: nameSpan.start, + end: nameSpan.end, + range: nameSpan.range, + }; + case 2: + return { + kind: "None", + name: null, + start: null, + end: null, + range: [null, null], + }; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ExportLocalName`); + } +} + +function deserializeDynamicImport(pos) { + let start, end; + return { + moduleRequest: deserializeSpan(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeAssignmentOperator(pos) { + switch (uint8[pos]) { + case 0: + return "="; + case 1: + return "+="; + case 2: + return "-="; + case 3: + return "*="; + case 4: + return "/="; + case 5: + return "%="; + case 6: + return "**="; + case 7: + return "<<="; + case 8: + return ">>="; + case 9: + return ">>>="; + case 10: + return "|="; + case 11: + return "^="; + case 12: + return "&="; + case 13: + return "||="; + case 14: + return "&&="; + case 15: + return "??="; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for AssignmentOperator`); + } +} + +function deserializeBinaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "=="; + case 1: + return "!="; + case 2: + return "==="; + case 3: + return "!=="; + case 4: + return "<"; + case 5: + return "<="; + case 6: + return ">"; + case 7: + return ">="; + case 8: + return "+"; + case 9: + return "-"; + case 10: + return "*"; + case 11: + return "/"; + case 12: + return "%"; + case 13: + return "**"; + case 14: + return "<<"; + case 15: + return ">>"; + case 16: + return ">>>"; + case 17: + return "|"; + case 18: + return "^"; + case 19: + return "&"; + case 20: + return "in"; + case 21: + return "instanceof"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for BinaryOperator`); + } +} + +function deserializeLogicalOperator(pos) { + switch (uint8[pos]) { + case 0: + return "||"; + case 1: + return "&&"; + case 2: + return "??"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for LogicalOperator`); + } +} + +function deserializeUnaryOperator(pos) { + switch (uint8[pos]) { + case 0: + return "+"; + case 1: + return "-"; + case 2: + return "!"; + case 3: + return "~"; + case 4: + return "typeof"; + case 5: + return "void"; + case 6: + return "delete"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UnaryOperator`); + } +} + +function deserializeUpdateOperator(pos) { + switch (uint8[pos]) { + case 0: + return "++"; + case 1: + return "--"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for UpdateOperator`); + } +} + +function deserializeRawTransferData(pos) { + return { + program: deserializeProgram(pos), + comments: deserializeVecComment(pos + 144), + module: deserializeEcmaScriptModule(pos + 168), + errors: deserializeVecError(pos + 272), + }; +} + +function deserializeError(pos) { + return { + severity: deserializeErrorSeverity(pos + 72), + message: deserializeStr(pos), + labels: deserializeVecErrorLabel(pos + 16), + helpMessage: deserializeOptionStr(pos + 40), + codeframe: deserializeStr(pos + 56), + }; +} + +function deserializeErrorSeverity(pos) { + switch (uint8[pos]) { + case 0: + return "Error"; + case 1: + return "Warning"; + case 2: + return "Advice"; + default: + throw Error(`Unexpected discriminant ${uint8[pos]} for ErrorSeverity`); + } +} + +function deserializeErrorLabel(pos) { + let start, end; + return { + message: deserializeOptionStr(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeEcmaScriptModule(pos) { + return { + hasModuleSyntax: deserializeBool(pos + 96), + staticImports: deserializeVecStaticImport(pos), + staticExports: deserializeVecStaticExport(pos + 24), + dynamicImports: deserializeVecDynamicImport(pos + 48), + importMetas: deserializeVecSpan(pos + 72), + }; +} + +function deserializeStaticImport(pos) { + let start, end; + return { + moduleRequest: deserializeNameSpan(pos + 8), + entries: deserializeVecImportEntry(pos + 32), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeStaticExport(pos) { + let start, end; + return { + entries: deserializeVecExportEntry(pos + 8), + start: (start = deserializeI32(pos)), + end: (end = deserializeI32(pos + 4)), + range: [start, end], + }; +} + +function deserializeStr(pos) { + let pos32 = pos >> 2, + len = int32[pos32 + 2]; + if (len === 0) return ""; + pos = int32[pos32]; + let end = pos + len; + if (end <= firstNonAsciiPos) return sourceTextLatin.substr(pos, len); + // Use `utf8Slice` for strings longer than 64 bytes + if (len > 64) return utf8Slice.call(uint8, pos, end); + if (pos < sourceEndPos) { + // Check if all bytes are ASCII, use `utf8Slice` if not + for (let i = pos; i < end; i++) if (uint8[i] >= 128) return utf8Slice.call(uint8, pos, end); + // String is all ASCII, so slice from `sourceTextLatin` + return sourceTextLatin.substr(pos, len); + } + // String is not in source region - use `fromCharCode.apply` with a temp array of correct length. + // Copy bytes into temp array. + // If any byte is non-ASCII, use `utf8Slice`. + let arr = stringDecodeArrays[len]; + for (let i = 0; i < len; i++) { + let b = uint8[pos + i]; + if (b >= 128) return utf8Slice.call(uint8, pos, end); + arr[i] = b; + } + // Call `fromCharCode` with temp array + return fromCharCode.apply(null, arr); +} + +function deserializeVecComment(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeComment(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionHashbang(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeHashbang(pos); +} + +function deserializeVecDirective(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeDirective(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecStatement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeStatement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxBooleanLiteral(pos) { + return deserializeBooleanLiteral(int32[pos >> 2]); +} + +function deserializeBoxNullLiteral(pos) { + return deserializeNullLiteral(int32[pos >> 2]); +} + +function deserializeBoxNumericLiteral(pos) { + return deserializeNumericLiteral(int32[pos >> 2]); +} + +function deserializeBoxBigIntLiteral(pos) { + return deserializeBigIntLiteral(int32[pos >> 2]); +} + +function deserializeBoxRegExpLiteral(pos) { + return deserializeRegExpLiteral(int32[pos >> 2]); +} + +function deserializeBoxStringLiteral(pos) { + return deserializeStringLiteral(int32[pos >> 2]); +} + +function deserializeBoxTemplateLiteral(pos) { + return deserializeTemplateLiteral(int32[pos >> 2]); +} + +function deserializeBoxIdentifierReference(pos) { + return deserializeIdentifierReference(int32[pos >> 2]); +} + +function deserializeBoxMetaProperty(pos) { + return deserializeMetaProperty(int32[pos >> 2]); +} + +function deserializeBoxSuper(pos) { + return deserializeSuper(int32[pos >> 2]); +} + +function deserializeBoxArrayExpression(pos) { + return deserializeArrayExpression(int32[pos >> 2]); +} + +function deserializeBoxArrowFunctionExpression(pos) { + return deserializeArrowFunctionExpression(int32[pos >> 2]); +} + +function deserializeBoxAssignmentExpression(pos) { + return deserializeAssignmentExpression(int32[pos >> 2]); +} + +function deserializeBoxAwaitExpression(pos) { + return deserializeAwaitExpression(int32[pos >> 2]); +} + +function deserializeBoxBinaryExpression(pos) { + return deserializeBinaryExpression(int32[pos >> 2]); +} + +function deserializeBoxCallExpression(pos) { + return deserializeCallExpression(int32[pos >> 2]); +} + +function deserializeBoxChainExpression(pos) { + return deserializeChainExpression(int32[pos >> 2]); +} + +function deserializeBoxClass(pos) { + return deserializeClass(int32[pos >> 2]); +} + +function deserializeBoxConditionalExpression(pos) { + return deserializeConditionalExpression(int32[pos >> 2]); +} + +function deserializeBoxFunction(pos) { + return deserializeFunction(int32[pos >> 2]); +} + +function deserializeBoxImportExpression(pos) { + return deserializeImportExpression(int32[pos >> 2]); +} + +function deserializeBoxLogicalExpression(pos) { + return deserializeLogicalExpression(int32[pos >> 2]); +} + +function deserializeBoxNewExpression(pos) { + return deserializeNewExpression(int32[pos >> 2]); +} + +function deserializeBoxObjectExpression(pos) { + return deserializeObjectExpression(int32[pos >> 2]); +} + +function deserializeBoxParenthesizedExpression(pos) { + return deserializeParenthesizedExpression(int32[pos >> 2]); +} + +function deserializeBoxSequenceExpression(pos) { + return deserializeSequenceExpression(int32[pos >> 2]); +} + +function deserializeBoxTaggedTemplateExpression(pos) { + return deserializeTaggedTemplateExpression(int32[pos >> 2]); +} + +function deserializeBoxThisExpression(pos) { + return deserializeThisExpression(int32[pos >> 2]); +} + +function deserializeBoxUnaryExpression(pos) { + return deserializeUnaryExpression(int32[pos >> 2]); +} + +function deserializeBoxUpdateExpression(pos) { + return deserializeUpdateExpression(int32[pos >> 2]); +} + +function deserializeBoxYieldExpression(pos) { + return deserializeYieldExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateInExpression(pos) { + return deserializePrivateInExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXElement(pos) { + return deserializeJSXElement(int32[pos >> 2]); +} + +function deserializeBoxJSXFragment(pos) { + return deserializeJSXFragment(int32[pos >> 2]); +} + +function deserializeBoxTSAsExpression(pos) { + return deserializeTSAsExpression(int32[pos >> 2]); +} + +function deserializeBoxTSSatisfiesExpression(pos) { + return deserializeTSSatisfiesExpression(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAssertion(pos) { + return deserializeTSTypeAssertion(int32[pos >> 2]); +} + +function deserializeBoxTSNonNullExpression(pos) { + return deserializeTSNonNullExpression(int32[pos >> 2]); +} + +function deserializeBoxTSInstantiationExpression(pos) { + return deserializeTSInstantiationExpression(int32[pos >> 2]); +} + +function deserializeBoxV8IntrinsicExpression(pos) { + return deserializeV8IntrinsicExpression(int32[pos >> 2]); +} + +function deserializeVecArrayExpressionElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeArrayExpressionElement(pos)); + pos += 24; + } + return arr; +} + +function deserializeBoxSpreadElement(pos) { + return deserializeSpreadElement(int32[pos >> 2]); +} + +function deserializeVecObjectPropertyKind(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeObjectPropertyKind(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxObjectProperty(pos) { + return deserializeObjectProperty(int32[pos >> 2]); +} + +function deserializeBool(pos) { + return uint8[pos] === 1; +} + +function deserializeBoxIdentifierName(pos) { + return deserializeIdentifierName(int32[pos >> 2]); +} + +function deserializeBoxPrivateIdentifier(pos) { + return deserializePrivateIdentifier(int32[pos >> 2]); +} + +function deserializeVecTemplateElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTemplateElement(pos)); + pos += 48; + } + return arr; +} + +function deserializeVecExpression(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeExpression(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSTypeParameterInstantiation(pos) { + return deserializeTSTypeParameterInstantiation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterInstantiation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterInstantiation(pos); +} + +function deserializeOptionStr(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 ? null : deserializeStr(pos); +} + +function deserializeBoxComputedMemberExpression(pos) { + return deserializeComputedMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxStaticMemberExpression(pos) { + return deserializeStaticMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxPrivateFieldExpression(pos) { + return deserializePrivateFieldExpression(int32[pos >> 2]); +} + +function deserializeVecArgument(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeArgument(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxArrayAssignmentTarget(pos) { + return deserializeArrayAssignmentTarget(int32[pos >> 2]); +} + +function deserializeBoxObjectAssignmentTarget(pos) { + return deserializeObjectAssignmentTarget(int32[pos >> 2]); +} + +function deserializeOptionAssignmentTargetMaybeDefault(pos) { + return uint8[pos] === 51 ? null : deserializeAssignmentTargetMaybeDefault(pos); +} + +function deserializeVecOptionAssignmentTargetMaybeDefault(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionAssignmentTargetMaybeDefault(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetRest(pos) { + return deserializeAssignmentTargetRest(int32[pos >> 2]); +} + +function deserializeOptionBoxAssignmentTargetRest(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxAssignmentTargetRest(pos); +} + +function deserializeVecAssignmentTargetProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeAssignmentTargetProperty(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxAssignmentTargetWithDefault(pos) { + return deserializeAssignmentTargetWithDefault(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyIdentifier(pos) { + return deserializeAssignmentTargetPropertyIdentifier(int32[pos >> 2]); +} + +function deserializeBoxAssignmentTargetPropertyProperty(pos) { + return deserializeAssignmentTargetPropertyProperty(int32[pos >> 2]); +} + +function deserializeOptionExpression(pos) { + return uint8[pos] === 51 ? null : deserializeExpression(pos); +} + +function deserializeBoxBlockStatement(pos) { + return deserializeBlockStatement(int32[pos >> 2]); +} + +function deserializeBoxBreakStatement(pos) { + return deserializeBreakStatement(int32[pos >> 2]); +} + +function deserializeBoxContinueStatement(pos) { + return deserializeContinueStatement(int32[pos >> 2]); +} + +function deserializeBoxDebuggerStatement(pos) { + return deserializeDebuggerStatement(int32[pos >> 2]); +} + +function deserializeBoxDoWhileStatement(pos) { + return deserializeDoWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxEmptyStatement(pos) { + return deserializeEmptyStatement(int32[pos >> 2]); +} + +function deserializeBoxExpressionStatement(pos) { + return deserializeExpressionStatement(int32[pos >> 2]); +} + +function deserializeBoxForInStatement(pos) { + return deserializeForInStatement(int32[pos >> 2]); +} + +function deserializeBoxForOfStatement(pos) { + return deserializeForOfStatement(int32[pos >> 2]); +} + +function deserializeBoxForStatement(pos) { + return deserializeForStatement(int32[pos >> 2]); +} + +function deserializeBoxIfStatement(pos) { + return deserializeIfStatement(int32[pos >> 2]); +} + +function deserializeBoxLabeledStatement(pos) { + return deserializeLabeledStatement(int32[pos >> 2]); +} + +function deserializeBoxReturnStatement(pos) { + return deserializeReturnStatement(int32[pos >> 2]); +} + +function deserializeBoxSwitchStatement(pos) { + return deserializeSwitchStatement(int32[pos >> 2]); +} + +function deserializeBoxThrowStatement(pos) { + return deserializeThrowStatement(int32[pos >> 2]); +} + +function deserializeBoxTryStatement(pos) { + return deserializeTryStatement(int32[pos >> 2]); +} + +function deserializeBoxWhileStatement(pos) { + return deserializeWhileStatement(int32[pos >> 2]); +} + +function deserializeBoxWithStatement(pos) { + return deserializeWithStatement(int32[pos >> 2]); +} + +function deserializeBoxVariableDeclaration(pos) { + return deserializeVariableDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSTypeAliasDeclaration(pos) { + return deserializeTSTypeAliasDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSInterfaceDeclaration(pos) { + return deserializeTSInterfaceDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSEnumDeclaration(pos) { + return deserializeTSEnumDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSModuleDeclaration(pos) { + return deserializeTSModuleDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSGlobalDeclaration(pos) { + return deserializeTSGlobalDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSImportEqualsDeclaration(pos) { + return deserializeTSImportEqualsDeclaration(int32[pos >> 2]); +} + +function deserializeVecVariableDeclarator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeVariableDeclarator(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxTSTypeAnnotation(pos) { + return deserializeTSTypeAnnotation(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeAnnotation(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeAnnotation(pos); +} + +function deserializeOptionStatement(pos) { + return uint8[pos] === 70 ? null : deserializeStatement(pos); +} + +function deserializeOptionForStatementInit(pos) { + return uint8[pos] === 65 ? null : deserializeForStatementInit(pos); +} + +function deserializeOptionLabelIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeLabelIdentifier(pos); +} + +function deserializeVecSwitchCase(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeSwitchCase(pos)); + pos += 56; + } + return arr; +} + +function deserializeBoxCatchClause(pos) { + return deserializeCatchClause(int32[pos >> 2]); +} + +function deserializeOptionBoxCatchClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxCatchClause(pos); +} + +function deserializeOptionBoxBlockStatement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBlockStatement(pos); +} + +function deserializeOptionCatchParameter(pos) { + return uint8[pos + 16] === 4 ? null : deserializeCatchParameter(pos); +} + +function deserializeBoxBindingIdentifier(pos) { + return deserializeBindingIdentifier(int32[pos >> 2]); +} + +function deserializeBoxObjectPattern(pos) { + return deserializeObjectPattern(int32[pos >> 2]); +} + +function deserializeBoxArrayPattern(pos) { + return deserializeArrayPattern(int32[pos >> 2]); +} + +function deserializeBoxAssignmentPattern(pos) { + return deserializeAssignmentPattern(int32[pos >> 2]); +} + +function deserializeVecBindingProperty(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeBindingProperty(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxBindingRestElement(pos) { + return deserializeBindingRestElement(int32[pos >> 2]); +} + +function deserializeOptionBoxBindingRestElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxBindingRestElement(pos); +} + +function deserializeOptionBindingPattern(pos) { + return uint8[pos] === 4 ? null : deserializeBindingPattern(pos); +} + +function deserializeVecOptionBindingPattern(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeOptionBindingPattern(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionBindingIdentifier(pos) { + return int32[(pos >> 2) + 4] === 0 && int32[(pos >> 2) + 5] === 0 + ? null + : deserializeBindingIdentifier(pos); +} + +function deserializeBoxTSTypeParameterDeclaration(pos) { + return deserializeTSTypeParameterDeclaration(int32[pos >> 2]); +} + +function deserializeOptionBoxTSTypeParameterDeclaration(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSTypeParameterDeclaration(pos); +} + +function deserializeBoxTSThisParameter(pos) { + return deserializeTSThisParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxTSThisParameter(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxTSThisParameter(pos); +} + +function deserializeBoxFormalParameters(pos) { + return deserializeFormalParameters(int32[pos >> 2]); +} + +function deserializeBoxFunctionBody(pos) { + return deserializeFunctionBody(int32[pos >> 2]); +} + +function deserializeOptionBoxFunctionBody(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxFunctionBody(pos); +} + +function deserializeVecFormalParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 72; + for (; pos !== endPos; ) { + arr.push(deserializeFormalParameter(pos)); + pos += 72; + } + return arr; +} + +function deserializeVecDecorator(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeDecorator(pos)); + pos += 32; + } + return arr; +} + +function deserializeBoxExpression(pos) { + return deserializeExpression(int32[pos >> 2]); +} + +function deserializeOptionBoxExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxExpression(pos); +} + +function deserializeOptionTSAccessibility(pos) { + return uint8[pos] === 3 ? null : deserializeTSAccessibility(pos); +} + +function deserializeVecTSClassImplements(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSClassImplements(pos)); + pos += 40; + } + return arr; +} + +function deserializeBoxClassBody(pos) { + return deserializeClassBody(int32[pos >> 2]); +} + +function deserializeVecClassElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeClassElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxStaticBlock(pos) { + return deserializeStaticBlock(int32[pos >> 2]); +} + +function deserializeBoxMethodDefinition(pos) { + return deserializeMethodDefinition(int32[pos >> 2]); +} + +function deserializeBoxPropertyDefinition(pos) { + return deserializePropertyDefinition(int32[pos >> 2]); +} + +function deserializeBoxAccessorProperty(pos) { + return deserializeAccessorProperty(int32[pos >> 2]); +} + +function deserializeBoxTSIndexSignature(pos) { + return deserializeTSIndexSignature(int32[pos >> 2]); +} + +function deserializeBoxImportDeclaration(pos) { + return deserializeImportDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportAllDeclaration(pos) { + return deserializeExportAllDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportDefaultDeclaration(pos) { + return deserializeExportDefaultDeclaration(int32[pos >> 2]); +} + +function deserializeBoxExportNamedDeclaration(pos) { + return deserializeExportNamedDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSExportAssignment(pos) { + return deserializeTSExportAssignment(int32[pos >> 2]); +} + +function deserializeBoxTSNamespaceExportDeclaration(pos) { + return deserializeTSNamespaceExportDeclaration(int32[pos >> 2]); +} + +function deserializeOptionImportPhase(pos) { + return uint8[pos] === 2 ? null : deserializeImportPhase(pos); +} + +function deserializeVecImportDeclarationSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeImportDeclarationSpecifier(pos)); + pos += 16; + } + return arr; +} + +function deserializeOptionVecImportDeclarationSpecifier(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeVecImportDeclarationSpecifier(pos); +} + +function deserializeBoxWithClause(pos) { + return deserializeWithClause(int32[pos >> 2]); +} + +function deserializeOptionBoxWithClause(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxWithClause(pos); +} + +function deserializeBoxImportSpecifier(pos) { + return deserializeImportSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportDefaultSpecifier(pos) { + return deserializeImportDefaultSpecifier(int32[pos >> 2]); +} + +function deserializeBoxImportNamespaceSpecifier(pos) { + return deserializeImportNamespaceSpecifier(int32[pos >> 2]); +} + +function deserializeVecImportAttribute(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 120; + for (; pos !== endPos; ) { + arr.push(deserializeImportAttribute(pos)); + pos += 120; + } + return arr; +} + +function deserializeOptionDeclaration(pos) { + return uint8[pos] === 31 ? null : deserializeDeclaration(pos); +} + +function deserializeVecExportSpecifier(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 7); + for (; pos !== endPos; ) { + arr.push(deserializeExportSpecifier(pos)); + pos += 128; + } + return arr; +} + +function deserializeOptionStringLiteral(pos) { + return uint8[pos + 12] === 2 ? null : deserializeStringLiteral(pos); +} + +function deserializeOptionModuleExportName(pos) { + return uint8[pos] === 3 ? null : deserializeModuleExportName(pos); +} + +function deserializeF64(pos) { + return float64[pos >> 3]; +} + +function deserializeU8(pos) { + return uint8[pos]; +} + +function deserializeBoxJSXOpeningElement(pos) { + return deserializeJSXOpeningElement(int32[pos >> 2]); +} + +function deserializeVecJSXChild(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXChild(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXClosingElement(pos) { + return deserializeJSXClosingElement(int32[pos >> 2]); +} + +function deserializeOptionBoxJSXClosingElement(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxJSXClosingElement(pos); +} + +function deserializeVecJSXAttributeItem(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeJSXAttributeItem(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxJSXIdentifier(pos) { + return deserializeJSXIdentifier(int32[pos >> 2]); +} + +function deserializeBoxJSXNamespacedName(pos) { + return deserializeJSXNamespacedName(int32[pos >> 2]); +} + +function deserializeBoxJSXMemberExpression(pos) { + return deserializeJSXMemberExpression(int32[pos >> 2]); +} + +function deserializeBoxJSXAttribute(pos) { + return deserializeJSXAttribute(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadAttribute(pos) { + return deserializeJSXSpreadAttribute(int32[pos >> 2]); +} + +function deserializeOptionJSXAttributeValue(pos) { + return uint8[pos] === 4 ? null : deserializeJSXAttributeValue(pos); +} + +function deserializeBoxJSXExpressionContainer(pos) { + return deserializeJSXExpressionContainer(int32[pos >> 2]); +} + +function deserializeBoxJSXText(pos) { + return deserializeJSXText(int32[pos >> 2]); +} + +function deserializeBoxJSXSpreadChild(pos) { + return deserializeJSXSpreadChild(int32[pos >> 2]); +} + +function deserializeVecTSEnumMember(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 48; + for (; pos !== endPos; ) { + arr.push(deserializeTSEnumMember(pos)); + pos += 48; + } + return arr; +} + +function deserializeBoxTSAnyKeyword(pos) { + return deserializeTSAnyKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBigIntKeyword(pos) { + return deserializeTSBigIntKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSBooleanKeyword(pos) { + return deserializeTSBooleanKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSIntrinsicKeyword(pos) { + return deserializeTSIntrinsicKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNeverKeyword(pos) { + return deserializeTSNeverKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNullKeyword(pos) { + return deserializeTSNullKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSNumberKeyword(pos) { + return deserializeTSNumberKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSObjectKeyword(pos) { + return deserializeTSObjectKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSStringKeyword(pos) { + return deserializeTSStringKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSSymbolKeyword(pos) { + return deserializeTSSymbolKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUndefinedKeyword(pos) { + return deserializeTSUndefinedKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSUnknownKeyword(pos) { + return deserializeTSUnknownKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSVoidKeyword(pos) { + return deserializeTSVoidKeyword(int32[pos >> 2]); +} + +function deserializeBoxTSArrayType(pos) { + return deserializeTSArrayType(int32[pos >> 2]); +} + +function deserializeBoxTSConditionalType(pos) { + return deserializeTSConditionalType(int32[pos >> 2]); +} + +function deserializeBoxTSConstructorType(pos) { + return deserializeTSConstructorType(int32[pos >> 2]); +} + +function deserializeBoxTSFunctionType(pos) { + return deserializeTSFunctionType(int32[pos >> 2]); +} + +function deserializeBoxTSImportType(pos) { + return deserializeTSImportType(int32[pos >> 2]); +} + +function deserializeBoxTSIndexedAccessType(pos) { + return deserializeTSIndexedAccessType(int32[pos >> 2]); +} + +function deserializeBoxTSInferType(pos) { + return deserializeTSInferType(int32[pos >> 2]); +} + +function deserializeBoxTSIntersectionType(pos) { + return deserializeTSIntersectionType(int32[pos >> 2]); +} + +function deserializeBoxTSLiteralType(pos) { + return deserializeTSLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSMappedType(pos) { + return deserializeTSMappedType(int32[pos >> 2]); +} + +function deserializeBoxTSNamedTupleMember(pos) { + return deserializeTSNamedTupleMember(int32[pos >> 2]); +} + +function deserializeBoxTSTemplateLiteralType(pos) { + return deserializeTSTemplateLiteralType(int32[pos >> 2]); +} + +function deserializeBoxTSThisType(pos) { + return deserializeTSThisType(int32[pos >> 2]); +} + +function deserializeBoxTSTupleType(pos) { + return deserializeTSTupleType(int32[pos >> 2]); +} + +function deserializeBoxTSTypeLiteral(pos) { + return deserializeTSTypeLiteral(int32[pos >> 2]); +} + +function deserializeBoxTSTypeOperator(pos) { + return deserializeTSTypeOperator(int32[pos >> 2]); +} + +function deserializeBoxTSTypePredicate(pos) { + return deserializeTSTypePredicate(int32[pos >> 2]); +} + +function deserializeBoxTSTypeQuery(pos) { + return deserializeTSTypeQuery(int32[pos >> 2]); +} + +function deserializeBoxTSTypeReference(pos) { + return deserializeTSTypeReference(int32[pos >> 2]); +} + +function deserializeBoxTSUnionType(pos) { + return deserializeTSUnionType(int32[pos >> 2]); +} + +function deserializeBoxTSParenthesizedType(pos) { + return deserializeTSParenthesizedType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNullableType(pos) { + return deserializeJSDocNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocNonNullableType(pos) { + return deserializeJSDocNonNullableType(int32[pos >> 2]); +} + +function deserializeBoxJSDocUnknownType(pos) { + return deserializeJSDocUnknownType(int32[pos >> 2]); +} + +function deserializeVecTSType(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSType(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecTSTupleElement(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSTupleElement(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSOptionalType(pos) { + return deserializeTSOptionalType(int32[pos >> 2]); +} + +function deserializeBoxTSRestType(pos) { + return deserializeTSRestType(int32[pos >> 2]); +} + +function deserializeBoxTSQualifiedName(pos) { + return deserializeTSQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSType(pos) { + return uint8[pos] === 38 ? null : deserializeTSType(pos); +} + +function deserializeVecTSTypeParameter(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeTSTypeParameter(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecTSInterfaceHeritage(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSInterfaceHeritage(pos)); + pos += 40; + } + return arr; +} + +function deserializeBoxTSInterfaceBody(pos) { + return deserializeTSInterfaceBody(int32[pos >> 2]); +} + +function deserializeVecTSSignature(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeTSSignature(pos)); + pos += 16; + } + return arr; +} + +function deserializeBoxTSPropertySignature(pos) { + return deserializeTSPropertySignature(int32[pos >> 2]); +} + +function deserializeBoxTSCallSignatureDeclaration(pos) { + return deserializeTSCallSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSConstructSignatureDeclaration(pos) { + return deserializeTSConstructSignatureDeclaration(int32[pos >> 2]); +} + +function deserializeBoxTSMethodSignature(pos) { + return deserializeTSMethodSignature(int32[pos >> 2]); +} + +function deserializeVecTSIndexSignatureName(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 40; + for (; pos !== endPos; ) { + arr.push(deserializeTSIndexSignatureName(pos)); + pos += 40; + } + return arr; +} + +function deserializeOptionTSModuleDeclarationBody(pos) { + return uint8[pos] === 2 ? null : deserializeTSModuleDeclarationBody(pos); +} + +function deserializeBoxTSModuleBlock(pos) { + return deserializeTSModuleBlock(int32[pos >> 2]); +} + +function deserializeBoxTSTypeParameter(pos) { + return deserializeTSTypeParameter(int32[pos >> 2]); +} + +function deserializeOptionBoxObjectExpression(pos) { + return int32[pos >> 2] === 0 && int32[(pos >> 2) + 1] === 0 + ? null + : deserializeBoxObjectExpression(pos); +} + +function deserializeOptionTSImportTypeQualifier(pos) { + return uint8[pos] === 2 ? null : deserializeTSImportTypeQualifier(pos); +} + +function deserializeBoxTSImportTypeQualifiedName(pos) { + return deserializeTSImportTypeQualifiedName(int32[pos >> 2]); +} + +function deserializeOptionTSMappedTypeModifierOperator(pos) { + return uint8[pos] === 3 ? null : deserializeTSMappedTypeModifierOperator(pos); +} + +function deserializeBoxTSExternalModuleReference(pos) { + return deserializeTSExternalModuleReference(int32[pos >> 2]); +} + +function deserializeI32(pos) { + return int32[pos >> 2]; +} + +function deserializeOptionNameSpan(pos) { + return int32[(pos >> 2) + 2] === 0 && int32[(pos >> 2) + 3] === 0 + ? null + : deserializeNameSpan(pos); +} + +function deserializeVecError(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 80; + for (; pos !== endPos; ) { + arr.push(deserializeError(pos)); + pos += 80; + } + return arr; +} + +function deserializeVecErrorLabel(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 24; + for (; pos !== endPos; ) { + arr.push(deserializeErrorLabel(pos)); + pos += 24; + } + return arr; +} + +function deserializeVecStaticImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 56; + for (; pos !== endPos; ) { + arr.push(deserializeStaticImport(pos)); + pos += 56; + } + return arr; +} + +function deserializeVecStaticExport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 5); + for (; pos !== endPos; ) { + arr.push(deserializeStaticExport(pos)); + pos += 32; + } + return arr; +} + +function deserializeVecDynamicImport(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 4); + for (; pos !== endPos; ) { + arr.push(deserializeDynamicImport(pos)); + pos += 16; + } + return arr; +} + +function deserializeVecSpan(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + (int32[pos32 + 2] << 3); + for (; pos !== endPos; ) { + arr.push(deserializeSpan(pos)); + pos += 8; + } + return arr; +} + +function deserializeVecImportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 96; + for (; pos !== endPos; ) { + arr.push(deserializeImportEntry(pos)); + pos += 96; + } + return arr; +} + +function deserializeVecExportEntry(pos) { + let arr = [], + pos32 = pos >> 2; + pos = int32[pos32]; + let endPos = pos + int32[pos32 + 2] * 144; + for (; pos !== endPos; ) { + arr.push(deserializeExportEntry(pos)); + pos += 144; + } + return arr; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/constructors.js b/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/constructors.js new file mode 100644 index 0000000000000000000000000000000000000000..56f20b48d2758c76ca91c5937d4baae436173cd9 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/constructors.js @@ -0,0 +1,13864 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer_lazy.rs`. + +import { constructorError, TOKEN } from "../../raw-transfer/lazy-common.js"; +import { NodeArray } from "../../raw-transfer/node-array.js"; + +const textDecoder = new TextDecoder("utf-8", { ignoreBOM: true }), + decodeStr = textDecoder.decode.bind(textDecoder), + { fromCodePoint } = String, + inspectSymbol = Symbol.for("nodejs.util.inspect.custom"); + +export class Program { + type = "Program"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get sourceType() { + const internal = this.#internal; + return new SourceType(internal.pos + 136, internal.ast); + } + + get hashbang() { + const internal = this.#internal; + return constructOptionHashbang(internal.pos + 56, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecStatement(internal.pos + 112, internal.ast)); + } + + toJSON() { + return { + type: "Program", + start: this.start, + end: this.end, + sourceType: this.sourceType, + hashbang: this.hashbang, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugProgram.prototype); + } +} + +const DebugProgram = class Program {}; + +function constructExpression(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Expression`); + } +} + +export class IdentifierName { + type = "IdentifierName"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "IdentifierName", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugIdentifierName.prototype); + } +} + +const DebugIdentifierName = class IdentifierName {}; + +export class IdentifierReference { + type = "IdentifierReference"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "IdentifierReference", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugIdentifierReference.prototype); + } +} + +const DebugIdentifierReference = class IdentifierReference {}; + +export class BindingIdentifier { + type = "BindingIdentifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "BindingIdentifier", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBindingIdentifier.prototype); + } +} + +const DebugBindingIdentifier = class BindingIdentifier {}; + +export class LabelIdentifier { + type = "LabelIdentifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "LabelIdentifier", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugLabelIdentifier.prototype); + } +} + +const DebugLabelIdentifier = class LabelIdentifier {}; + +export class ThisExpression { + type = "ThisExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "ThisExpression", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugThisExpression.prototype); + } +} + +const DebugThisExpression = class ThisExpression {}; + +export class ArrayExpression { + type = "ArrayExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $elements: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get elements() { + const internal = this.#internal, + cached = internal.$elements; + if (cached !== void 0) return cached; + return (internal.$elements = constructVecArrayExpressionElement( + internal.pos + 16, + internal.ast, + )); + } + + toJSON() { + return { + type: "ArrayExpression", + start: this.start, + end: this.end, + elements: this.elements, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugArrayExpression.prototype); + } +} + +const DebugArrayExpression = class ArrayExpression {}; + +function constructArrayExpressionElement(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + case 64: + return constructBoxSpreadElement(pos + 8, ast); + case 65: + return new Elision(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ArrayExpressionElement`); + } +} + +export class Elision { + type = "Elision"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "Elision", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugElision.prototype); + } +} + +const DebugElision = class Elision {}; + +export class ObjectExpression { + type = "ObjectExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $properties: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get properties() { + const internal = this.#internal, + cached = internal.$properties; + if (cached !== void 0) return cached; + return (internal.$properties = constructVecObjectPropertyKind(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "ObjectExpression", + start: this.start, + end: this.end, + properties: this.properties, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugObjectExpression.prototype); + } +} + +const DebugObjectExpression = class ObjectExpression {}; + +function constructObjectPropertyKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxObjectProperty(pos + 8, ast); + case 1: + return constructBoxSpreadElement(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ObjectPropertyKind`); + } +} + +export class ObjectProperty { + type = "ObjectProperty"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get kind() { + const internal = this.#internal; + return constructPropertyKind(internal.pos + 12, internal.ast); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 16, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + get method() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + get shorthand() { + const internal = this.#internal; + return constructBool(internal.pos + 14, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 15, internal.ast); + } + + toJSON() { + return { + type: "ObjectProperty", + start: this.start, + end: this.end, + kind: this.kind, + key: this.key, + value: this.value, + method: this.method, + shorthand: this.shorthand, + computed: this.computed, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugObjectProperty.prototype); + } +} + +const DebugObjectProperty = class ObjectProperty {}; + +function constructPropertyKey(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + case 64: + return constructBoxIdentifierName(pos + 8, ast); + case 65: + return constructBoxPrivateIdentifier(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for PropertyKey`); + } +} + +function constructPropertyKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "init"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for PropertyKind`); + } +} + +export class TemplateLiteral { + type = "TemplateLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $quasis: void 0, $expressions: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get quasis() { + const internal = this.#internal, + cached = internal.$quasis; + if (cached !== void 0) return cached; + return (internal.$quasis = constructVecTemplateElement(internal.pos + 16, internal.ast)); + } + + get expressions() { + const internal = this.#internal, + cached = internal.$expressions; + if (cached !== void 0) return cached; + return (internal.$expressions = constructVecExpression(internal.pos + 40, internal.ast)); + } + + toJSON() { + return { + type: "TemplateLiteral", + start: this.start, + end: this.end, + quasis: this.quasis, + expressions: this.expressions, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTemplateLiteral.prototype); + } +} + +const DebugTemplateLiteral = class TemplateLiteral {}; + +export class TaggedTemplateExpression { + type = "TaggedTemplateExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get tag() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + get quasi() { + const internal = this.#internal; + return new TemplateLiteral(internal.pos + 40, internal.ast); + } + + toJSON() { + return { + type: "TaggedTemplateExpression", + start: this.start, + end: this.end, + tag: this.tag, + typeArguments: this.typeArguments, + quasi: this.quasi, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTaggedTemplateExpression.prototype); + } +} + +const DebugTaggedTemplateExpression = class TaggedTemplateExpression {}; + +export class TemplateElement { + type = "TemplateElement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal; + return new TemplateElementValue(internal.pos + 16, internal.ast); + } + + get tail() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "TemplateElement", + start: this.start, + end: this.end, + value: this.value, + tail: this.tail, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTemplateElement.prototype); + } +} + +const DebugTemplateElement = class TemplateElement {}; + +export class TemplateElementValue { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $raw: void 0, $cooked: void 0 }; + nodes.set(pos, this); + } + + get raw() { + const internal = this.#internal, + cached = internal.$raw; + if (cached !== void 0) return cached; + return (internal.$raw = constructStr(internal.pos, internal.ast)); + } + + get cooked() { + const internal = this.#internal, + cached = internal.$cooked; + if (cached !== void 0) return cached; + return (internal.$cooked = constructOptionStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + raw: this.raw, + cooked: this.cooked, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTemplateElementValue.prototype); + } +} + +const DebugTemplateElementValue = class TemplateElementValue {}; + +function constructMemberExpression(pos, ast) { + switch (ast.buffer[pos]) { + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for MemberExpression`); + } +} + +export class ComputedMemberExpression { + type = "ComputedMemberExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get object() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get property() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "ComputedMemberExpression", + start: this.start, + end: this.end, + object: this.object, + property: this.property, + optional: this.optional, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugComputedMemberExpression.prototype); + } +} + +const DebugComputedMemberExpression = class ComputedMemberExpression {}; + +export class StaticMemberExpression { + type = "StaticMemberExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get object() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get property() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 32, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "StaticMemberExpression", + start: this.start, + end: this.end, + object: this.object, + property: this.property, + optional: this.optional, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugStaticMemberExpression.prototype); + } +} + +const DebugStaticMemberExpression = class StaticMemberExpression {}; + +export class PrivateFieldExpression { + type = "PrivateFieldExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get object() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get property() { + const internal = this.#internal; + return new PrivateIdentifier(internal.pos + 32, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "PrivateFieldExpression", + start: this.start, + end: this.end, + object: this.object, + property: this.property, + optional: this.optional, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugPrivateFieldExpression.prototype); + } +} + +const DebugPrivateFieldExpression = class PrivateFieldExpression {}; + +export class CallExpression { + type = "CallExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $arguments: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get callee() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + get arguments() { + const internal = this.#internal, + cached = internal.$arguments; + if (cached !== void 0) return cached; + return (internal.$arguments = constructVecArgument(internal.pos + 40, internal.ast)); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "CallExpression", + start: this.start, + end: this.end, + callee: this.callee, + typeArguments: this.typeArguments, + arguments: this.arguments, + optional: this.optional, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugCallExpression.prototype); + } +} + +const DebugCallExpression = class CallExpression {}; + +export class NewExpression { + type = "NewExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $arguments: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get callee() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + get arguments() { + const internal = this.#internal, + cached = internal.$arguments; + if (cached !== void 0) return cached; + return (internal.$arguments = constructVecArgument(internal.pos + 40, internal.ast)); + } + + toJSON() { + return { + type: "NewExpression", + start: this.start, + end: this.end, + callee: this.callee, + typeArguments: this.typeArguments, + arguments: this.arguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugNewExpression.prototype); + } +} + +const DebugNewExpression = class NewExpression {}; + +export class MetaProperty { + type = "MetaProperty"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get meta() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 16, internal.ast); + } + + get property() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "MetaProperty", + start: this.start, + end: this.end, + meta: this.meta, + property: this.property, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugMetaProperty.prototype); + } +} + +const DebugMetaProperty = class MetaProperty {}; + +export class SpreadElement { + type = "SpreadElement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "SpreadElement", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSpreadElement.prototype); + } +} + +const DebugSpreadElement = class SpreadElement {}; + +function constructArgument(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + case 64: + return constructBoxSpreadElement(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Argument`); + } +} + +export class UpdateExpression { + type = "UpdateExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get operator() { + const internal = this.#internal; + return constructUpdateOperator(internal.pos + 12, internal.ast); + } + + get prefix() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructSimpleAssignmentTarget(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "UpdateExpression", + start: this.start, + end: this.end, + operator: this.operator, + prefix: this.prefix, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugUpdateExpression.prototype); + } +} + +const DebugUpdateExpression = class UpdateExpression {}; + +export class UnaryExpression { + type = "UnaryExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get operator() { + const internal = this.#internal; + return constructUnaryOperator(internal.pos + 12, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "UnaryExpression", + start: this.start, + end: this.end, + operator: this.operator, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugUnaryExpression.prototype); + } +} + +const DebugUnaryExpression = class UnaryExpression {}; + +export class BinaryExpression { + type = "BinaryExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get operator() { + const internal = this.#internal; + return constructBinaryOperator(internal.pos + 12, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "BinaryExpression", + start: this.start, + end: this.end, + left: this.left, + operator: this.operator, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBinaryExpression.prototype); + } +} + +const DebugBinaryExpression = class BinaryExpression {}; + +export class PrivateInExpression { + type = "PrivateInExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return new PrivateIdentifier(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "PrivateInExpression", + start: this.start, + end: this.end, + left: this.left, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugPrivateInExpression.prototype); + } +} + +const DebugPrivateInExpression = class PrivateInExpression {}; + +export class LogicalExpression { + type = "LogicalExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get operator() { + const internal = this.#internal; + return constructLogicalOperator(internal.pos + 12, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "LogicalExpression", + start: this.start, + end: this.end, + left: this.left, + operator: this.operator, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugLogicalExpression.prototype); + } +} + +const DebugLogicalExpression = class LogicalExpression {}; + +export class ConditionalExpression { + type = "ConditionalExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get test() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get consequent() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + get alternate() { + const internal = this.#internal; + return constructExpression(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "ConditionalExpression", + start: this.start, + end: this.end, + test: this.test, + consequent: this.consequent, + alternate: this.alternate, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugConditionalExpression.prototype); + } +} + +const DebugConditionalExpression = class ConditionalExpression {}; + +export class AssignmentExpression { + type = "AssignmentExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get operator() { + const internal = this.#internal; + return constructAssignmentOperator(internal.pos + 12, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructAssignmentTarget(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "AssignmentExpression", + start: this.start, + end: this.end, + operator: this.operator, + left: this.left, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAssignmentExpression.prototype); + } +} + +const DebugAssignmentExpression = class AssignmentExpression {}; + +function constructAssignmentTarget(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxTSAsExpression(pos + 8, ast); + case 2: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 3: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 4: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 8: + return constructBoxArrayAssignmentTarget(pos + 8, ast); + case 9: + return constructBoxObjectAssignmentTarget(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AssignmentTarget`); + } +} + +function constructSimpleAssignmentTarget(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxTSAsExpression(pos + 8, ast); + case 2: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 3: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 4: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for SimpleAssignmentTarget`); + } +} + +function constructAssignmentTargetPattern(pos, ast) { + switch (ast.buffer[pos]) { + case 8: + return constructBoxArrayAssignmentTarget(pos + 8, ast); + case 9: + return constructBoxObjectAssignmentTarget(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AssignmentTargetPattern`); + } +} + +export class ArrayAssignmentTarget { + type = "ArrayAssignmentTarget"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $elements: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get elements() { + const internal = this.#internal, + cached = internal.$elements; + if (cached !== void 0) return cached; + return (internal.$elements = constructVecOptionAssignmentTargetMaybeDefault( + internal.pos + 16, + internal.ast, + )); + } + + toJSON() { + return { + type: "ArrayAssignmentTarget", + start: this.start, + end: this.end, + elements: this.elements, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugArrayAssignmentTarget.prototype); + } +} + +const DebugArrayAssignmentTarget = class ArrayAssignmentTarget {}; + +export class ObjectAssignmentTarget { + type = "ObjectAssignmentTarget"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $properties: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get properties() { + const internal = this.#internal, + cached = internal.$properties; + if (cached !== void 0) return cached; + return (internal.$properties = constructVecAssignmentTargetProperty( + internal.pos + 16, + internal.ast, + )); + } + + toJSON() { + return { + type: "ObjectAssignmentTarget", + start: this.start, + end: this.end, + properties: this.properties, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugObjectAssignmentTarget.prototype); + } +} + +const DebugObjectAssignmentTarget = class ObjectAssignmentTarget {}; + +export class AssignmentTargetRest { + type = "AssignmentTargetRest"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructAssignmentTarget(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "AssignmentTargetRest", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAssignmentTargetRest.prototype); + } +} + +const DebugAssignmentTargetRest = class AssignmentTargetRest {}; + +function constructAssignmentTargetMaybeDefault(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxTSAsExpression(pos + 8, ast); + case 2: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 3: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 4: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 8: + return constructBoxArrayAssignmentTarget(pos + 8, ast); + case 9: + return constructBoxObjectAssignmentTarget(pos + 8, ast); + case 16: + return constructBoxAssignmentTargetWithDefault(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error( + `Unexpected discriminant ${ast.buffer[pos]} for AssignmentTargetMaybeDefault`, + ); + } +} + +export class AssignmentTargetWithDefault { + type = "AssignmentTargetWithDefault"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructAssignmentTarget(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "AssignmentTargetWithDefault", + start: this.start, + end: this.end, + left: this.left, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAssignmentTargetWithDefault.prototype); + } +} + +const DebugAssignmentTargetWithDefault = class AssignmentTargetWithDefault {}; + +function constructAssignmentTargetProperty(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxAssignmentTargetPropertyIdentifier(pos + 8, ast); + case 1: + return constructBoxAssignmentTargetPropertyProperty(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AssignmentTargetProperty`); + } +} + +export class AssignmentTargetPropertyIdentifier { + type = "AssignmentTargetPropertyIdentifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get key() { + const internal = this.#internal; + return new IdentifierReference(internal.pos + 16, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "AssignmentTargetPropertyIdentifier", + start: this.start, + end: this.end, + key: this.key, + value: this.value, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAssignmentTargetPropertyIdentifier.prototype); + } +} + +const DebugAssignmentTargetPropertyIdentifier = class AssignmentTargetPropertyIdentifier {}; + +export class AssignmentTargetPropertyProperty { + type = "AssignmentTargetPropertyProperty"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 16, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructAssignmentTargetMaybeDefault(internal.pos + 32, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "AssignmentTargetPropertyProperty", + start: this.start, + end: this.end, + key: this.key, + value: this.value, + computed: this.computed, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAssignmentTargetPropertyProperty.prototype); + } +} + +const DebugAssignmentTargetPropertyProperty = class AssignmentTargetPropertyProperty {}; + +export class SequenceExpression { + type = "SequenceExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $expressions: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expressions() { + const internal = this.#internal, + cached = internal.$expressions; + if (cached !== void 0) return cached; + return (internal.$expressions = constructVecExpression(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "SequenceExpression", + start: this.start, + end: this.end, + expressions: this.expressions, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSequenceExpression.prototype); + } +} + +const DebugSequenceExpression = class SequenceExpression {}; + +export class Super { + type = "Super"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "Super", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSuper.prototype); + } +} + +const DebugSuper = class Super {}; + +export class AwaitExpression { + type = "AwaitExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "AwaitExpression", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAwaitExpression.prototype); + } +} + +const DebugAwaitExpression = class AwaitExpression {}; + +export class ChainExpression { + type = "ChainExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructChainElement(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ChainExpression", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugChainExpression.prototype); + } +} + +const DebugChainExpression = class ChainExpression {}; + +function constructChainElement(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxCallExpression(pos + 8, ast); + case 1: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ChainElement`); + } +} + +export class ParenthesizedExpression { + type = "ParenthesizedExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ParenthesizedExpression", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugParenthesizedExpression.prototype); + } +} + +const DebugParenthesizedExpression = class ParenthesizedExpression {}; + +function constructStatement(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBlockStatement(pos + 8, ast); + case 1: + return constructBoxBreakStatement(pos + 8, ast); + case 2: + return constructBoxContinueStatement(pos + 8, ast); + case 3: + return constructBoxDebuggerStatement(pos + 8, ast); + case 4: + return constructBoxDoWhileStatement(pos + 8, ast); + case 5: + return constructBoxEmptyStatement(pos + 8, ast); + case 6: + return constructBoxExpressionStatement(pos + 8, ast); + case 7: + return constructBoxForInStatement(pos + 8, ast); + case 8: + return constructBoxForOfStatement(pos + 8, ast); + case 9: + return constructBoxForStatement(pos + 8, ast); + case 10: + return constructBoxIfStatement(pos + 8, ast); + case 11: + return constructBoxLabeledStatement(pos + 8, ast); + case 12: + return constructBoxReturnStatement(pos + 8, ast); + case 13: + return constructBoxSwitchStatement(pos + 8, ast); + case 14: + return constructBoxThrowStatement(pos + 8, ast); + case 15: + return constructBoxTryStatement(pos + 8, ast); + case 16: + return constructBoxWhileStatement(pos + 8, ast); + case 17: + return constructBoxWithStatement(pos + 8, ast); + case 32: + return constructBoxVariableDeclaration(pos + 8, ast); + case 33: + return constructBoxFunction(pos + 8, ast); + case 34: + return constructBoxClass(pos + 8, ast); + case 35: + return constructBoxTSTypeAliasDeclaration(pos + 8, ast); + case 36: + return constructBoxTSInterfaceDeclaration(pos + 8, ast); + case 37: + return constructBoxTSEnumDeclaration(pos + 8, ast); + case 38: + return constructBoxTSModuleDeclaration(pos + 8, ast); + case 39: + return constructBoxTSGlobalDeclaration(pos + 8, ast); + case 40: + return constructBoxTSImportEqualsDeclaration(pos + 8, ast); + case 64: + return constructBoxImportDeclaration(pos + 8, ast); + case 65: + return constructBoxExportAllDeclaration(pos + 8, ast); + case 66: + return constructBoxExportDefaultDeclaration(pos + 8, ast); + case 67: + return constructBoxExportNamedDeclaration(pos + 8, ast); + case 68: + return constructBoxTSExportAssignment(pos + 8, ast); + case 69: + return constructBoxTSNamespaceExportDeclaration(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Statement`); + } +} + +export class Directive { + type = "Directive"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $directive: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return new StringLiteral(internal.pos + 16, internal.ast); + } + + get directive() { + const internal = this.#internal, + cached = internal.$directive; + if (cached !== void 0) return cached; + return (internal.$directive = constructStr(internal.pos + 64, internal.ast)); + } + + toJSON() { + return { + type: "Directive", + start: this.start, + end: this.end, + expression: this.expression, + directive: this.directive, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugDirective.prototype); + } +} + +const DebugDirective = class Directive {}; + +export class Hashbang { + type = "Hashbang"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $value: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal, + cached = internal.$value; + if (cached !== void 0) return cached; + return (internal.$value = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "Hashbang", + start: this.start, + end: this.end, + value: this.value, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugHashbang.prototype); + } +} + +const DebugHashbang = class Hashbang {}; + +export class BlockStatement { + type = "BlockStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecStatement(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "BlockStatement", + start: this.start, + end: this.end, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBlockStatement.prototype); + } +} + +const DebugBlockStatement = class BlockStatement {}; + +function constructDeclaration(pos, ast) { + switch (ast.buffer[pos]) { + case 32: + return constructBoxVariableDeclaration(pos + 8, ast); + case 33: + return constructBoxFunction(pos + 8, ast); + case 34: + return constructBoxClass(pos + 8, ast); + case 35: + return constructBoxTSTypeAliasDeclaration(pos + 8, ast); + case 36: + return constructBoxTSInterfaceDeclaration(pos + 8, ast); + case 37: + return constructBoxTSEnumDeclaration(pos + 8, ast); + case 38: + return constructBoxTSModuleDeclaration(pos + 8, ast); + case 39: + return constructBoxTSGlobalDeclaration(pos + 8, ast); + case 40: + return constructBoxTSImportEqualsDeclaration(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Declaration`); + } +} + +export class VariableDeclaration { + type = "VariableDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $declarations: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get kind() { + const internal = this.#internal; + return constructVariableDeclarationKind(internal.pos + 12, internal.ast); + } + + get declarations() { + const internal = this.#internal, + cached = internal.$declarations; + if (cached !== void 0) return cached; + return (internal.$declarations = constructVecVariableDeclarator( + internal.pos + 16, + internal.ast, + )); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + toJSON() { + return { + type: "VariableDeclaration", + start: this.start, + end: this.end, + kind: this.kind, + declarations: this.declarations, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugVariableDeclaration.prototype); + } +} + +const DebugVariableDeclaration = class VariableDeclaration {}; + +function constructVariableDeclarationKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "var"; + case 1: + return "let"; + case 2: + return "const"; + case 3: + return "using"; + case 4: + return "await using"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for VariableDeclarationKind`); + } +} + +export class VariableDeclarator { + type = "VariableDeclarator"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return constructBindingPattern(internal.pos + 16, internal.ast); + } + + get init() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 40, internal.ast); + } + + get definite() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + toJSON() { + return { + type: "VariableDeclarator", + start: this.start, + end: this.end, + id: this.id, + init: this.init, + definite: this.definite, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugVariableDeclarator.prototype); + } +} + +const DebugVariableDeclarator = class VariableDeclarator {}; + +export class EmptyStatement { + type = "EmptyStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "EmptyStatement", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugEmptyStatement.prototype); + } +} + +const DebugEmptyStatement = class EmptyStatement {}; + +export class ExpressionStatement { + type = "ExpressionStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ExpressionStatement", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugExpressionStatement.prototype); + } +} + +const DebugExpressionStatement = class ExpressionStatement {}; + +export class IfStatement { + type = "IfStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get test() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get consequent() { + const internal = this.#internal; + return constructStatement(internal.pos + 32, internal.ast); + } + + get alternate() { + const internal = this.#internal; + return constructOptionStatement(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "IfStatement", + start: this.start, + end: this.end, + test: this.test, + consequent: this.consequent, + alternate: this.alternate, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugIfStatement.prototype); + } +} + +const DebugIfStatement = class IfStatement {}; + +export class DoWhileStatement { + type = "DoWhileStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 16, internal.ast); + } + + get test() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "DoWhileStatement", + start: this.start, + end: this.end, + body: this.body, + test: this.test, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugDoWhileStatement.prototype); + } +} + +const DebugDoWhileStatement = class DoWhileStatement {}; + +export class WhileStatement { + type = "WhileStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get test() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "WhileStatement", + start: this.start, + end: this.end, + test: this.test, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugWhileStatement.prototype); + } +} + +const DebugWhileStatement = class WhileStatement {}; + +export class ForStatement { + type = "ForStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get init() { + const internal = this.#internal; + return constructOptionForStatementInit(internal.pos + 16, internal.ast); + } + + get test() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 32, internal.ast); + } + + get update() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 48, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 64, internal.ast); + } + + toJSON() { + return { + type: "ForStatement", + start: this.start, + end: this.end, + init: this.init, + test: this.test, + update: this.update, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugForStatement.prototype); + } +} + +const DebugForStatement = class ForStatement {}; + +function constructForStatementInit(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + case 64: + return constructBoxVariableDeclaration(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ForStatementInit`); + } +} + +export class ForInStatement { + type = "ForInStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructForStatementLeft(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "ForInStatement", + start: this.start, + end: this.end, + left: this.left, + right: this.right, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugForInStatement.prototype); + } +} + +const DebugForInStatement = class ForInStatement {}; + +function constructForStatementLeft(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxTSAsExpression(pos + 8, ast); + case 2: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 3: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 4: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 8: + return constructBoxArrayAssignmentTarget(pos + 8, ast); + case 9: + return constructBoxObjectAssignmentTarget(pos + 8, ast); + case 16: + return constructBoxVariableDeclaration(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ForStatementLeft`); + } +} + +export class ForOfStatement { + type = "ForOfStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get await() { + const internal = this.#internal; + return constructBool(internal.pos + 64, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructForStatementLeft(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "ForOfStatement", + start: this.start, + end: this.end, + await: this.await, + left: this.left, + right: this.right, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugForOfStatement.prototype); + } +} + +const DebugForOfStatement = class ForOfStatement {}; + +export class ContinueStatement { + type = "ContinueStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get label() { + const internal = this.#internal; + return constructOptionLabelIdentifier(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ContinueStatement", + start: this.start, + end: this.end, + label: this.label, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugContinueStatement.prototype); + } +} + +const DebugContinueStatement = class ContinueStatement {}; + +export class BreakStatement { + type = "BreakStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get label() { + const internal = this.#internal; + return constructOptionLabelIdentifier(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "BreakStatement", + start: this.start, + end: this.end, + label: this.label, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBreakStatement.prototype); + } +} + +const DebugBreakStatement = class BreakStatement {}; + +export class ReturnStatement { + type = "ReturnStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ReturnStatement", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugReturnStatement.prototype); + } +} + +const DebugReturnStatement = class ReturnStatement {}; + +export class WithStatement { + type = "WithStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get object() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "WithStatement", + start: this.start, + end: this.end, + object: this.object, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugWithStatement.prototype); + } +} + +const DebugWithStatement = class WithStatement {}; + +export class SwitchStatement { + type = "SwitchStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $cases: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get discriminant() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get cases() { + const internal = this.#internal, + cached = internal.$cases; + if (cached !== void 0) return cached; + return (internal.$cases = constructVecSwitchCase(internal.pos + 32, internal.ast)); + } + + toJSON() { + return { + type: "SwitchStatement", + start: this.start, + end: this.end, + discriminant: this.discriminant, + cases: this.cases, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSwitchStatement.prototype); + } +} + +const DebugSwitchStatement = class SwitchStatement {}; + +export class SwitchCase { + type = "SwitchCase"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $consequent: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get test() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 16, internal.ast); + } + + get consequent() { + const internal = this.#internal, + cached = internal.$consequent; + if (cached !== void 0) return cached; + return (internal.$consequent = constructVecStatement(internal.pos + 32, internal.ast)); + } + + toJSON() { + return { + type: "SwitchCase", + start: this.start, + end: this.end, + test: this.test, + consequent: this.consequent, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSwitchCase.prototype); + } +} + +const DebugSwitchCase = class SwitchCase {}; + +export class LabeledStatement { + type = "LabeledStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get label() { + const internal = this.#internal; + return new LabelIdentifier(internal.pos + 16, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructStatement(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "LabeledStatement", + start: this.start, + end: this.end, + label: this.label, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugLabeledStatement.prototype); + } +} + +const DebugLabeledStatement = class LabeledStatement {}; + +export class ThrowStatement { + type = "ThrowStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ThrowStatement", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugThrowStatement.prototype); + } +} + +const DebugThrowStatement = class ThrowStatement {}; + +export class TryStatement { + type = "TryStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get block() { + const internal = this.#internal; + return constructBoxBlockStatement(internal.pos + 16, internal.ast); + } + + get handler() { + const internal = this.#internal; + return constructOptionBoxCatchClause(internal.pos + 24, internal.ast); + } + + get finalizer() { + const internal = this.#internal; + return constructOptionBoxBlockStatement(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TryStatement", + start: this.start, + end: this.end, + block: this.block, + handler: this.handler, + finalizer: this.finalizer, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTryStatement.prototype); + } +} + +const DebugTryStatement = class TryStatement {}; + +export class CatchClause { + type = "CatchClause"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get param() { + const internal = this.#internal; + return constructOptionCatchParameter(internal.pos + 16, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructBoxBlockStatement(internal.pos + 56, internal.ast); + } + + toJSON() { + return { + type: "CatchClause", + start: this.start, + end: this.end, + param: this.param, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugCatchClause.prototype); + } +} + +const DebugCatchClause = class CatchClause {}; + +export class CatchParameter { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get pattern() { + const internal = this.#internal; + return constructBindingPattern(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + pattern: this.pattern, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugCatchParameter.prototype); + } +} + +const DebugCatchParameter = class CatchParameter {}; + +export class DebuggerStatement { + type = "DebuggerStatement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "DebuggerStatement", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugDebuggerStatement.prototype); + } +} + +const DebugDebuggerStatement = class DebuggerStatement {}; + +function constructBindingPattern(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBindingIdentifier(pos + 8, ast); + case 1: + return constructBoxObjectPattern(pos + 8, ast); + case 2: + return constructBoxArrayPattern(pos + 8, ast); + case 3: + return constructBoxAssignmentPattern(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for BindingPattern`); + } +} + +export class AssignmentPattern { + type = "AssignmentPattern"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructBindingPattern(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "AssignmentPattern", + start: this.start, + end: this.end, + left: this.left, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAssignmentPattern.prototype); + } +} + +const DebugAssignmentPattern = class AssignmentPattern {}; + +export class ObjectPattern { + type = "ObjectPattern"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $properties: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get properties() { + const internal = this.#internal, + cached = internal.$properties; + if (cached !== void 0) return cached; + return (internal.$properties = constructVecBindingProperty(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "ObjectPattern", + start: this.start, + end: this.end, + properties: this.properties, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugObjectPattern.prototype); + } +} + +const DebugObjectPattern = class ObjectPattern {}; + +export class BindingProperty { + type = "BindingProperty"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 16, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructBindingPattern(internal.pos + 32, internal.ast); + } + + get shorthand() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + toJSON() { + return { + type: "BindingProperty", + start: this.start, + end: this.end, + key: this.key, + value: this.value, + shorthand: this.shorthand, + computed: this.computed, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBindingProperty.prototype); + } +} + +const DebugBindingProperty = class BindingProperty {}; + +export class ArrayPattern { + type = "ArrayPattern"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $elements: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get elements() { + const internal = this.#internal, + cached = internal.$elements; + if (cached !== void 0) return cached; + return (internal.$elements = constructVecOptionBindingPattern(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "ArrayPattern", + start: this.start, + end: this.end, + elements: this.elements, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugArrayPattern.prototype); + } +} + +const DebugArrayPattern = class ArrayPattern {}; + +export class BindingRestElement { + type = "BindingRestElement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructBindingPattern(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "BindingRestElement", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBindingRestElement.prototype); + } +} + +const DebugBindingRestElement = class BindingRestElement {}; + +export class Function { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get type() { + const internal = this.#internal; + return constructFunctionType(internal.pos + 88, internal.ast); + } + + get id() { + const internal = this.#internal; + return constructOptionBindingIdentifier(internal.pos + 16, internal.ast); + } + + get generator() { + const internal = this.#internal; + return constructBool(internal.pos + 89, internal.ast); + } + + get async() { + const internal = this.#internal; + return constructBool(internal.pos + 90, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 91, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 48, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 64, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 72, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructOptionBoxFunctionBody(internal.pos + 80, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + type: this.type, + id: this.id, + generator: this.generator, + async: this.async, + declare: this.declare, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugFunction.prototype); + } +} + +const DebugFunction = class Function {}; + +function constructFunctionType(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "FunctionDeclaration"; + case 1: + return "FunctionExpression"; + case 2: + return "TSDeclareFunction"; + case 3: + return "TSEmptyBodyFunctionExpression"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for FunctionType`); + } +} + +export class FormalParameters { + type = "FormalParameters"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $items: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get kind() { + const internal = this.#internal; + return constructFormalParameterKind(internal.pos + 12, internal.ast); + } + + get items() { + const internal = this.#internal, + cached = internal.$items; + if (cached !== void 0) return cached; + return (internal.$items = constructVecFormalParameter(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "FormalParameters", + start: this.start, + end: this.end, + kind: this.kind, + items: this.items, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugFormalParameters.prototype); + } +} + +const DebugFormalParameters = class FormalParameters {}; + +export class FormalParameter { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $decorators: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get decorators() { + const internal = this.#internal, + cached = internal.$decorators; + if (cached !== void 0) return cached; + return (internal.$decorators = constructVecDecorator(internal.pos + 16, internal.ast)); + } + + get pattern() { + const internal = this.#internal; + return constructBindingPattern(internal.pos + 40, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 56, internal.ast); + } + + get initializer() { + const internal = this.#internal; + return constructOptionBoxExpression(internal.pos + 64, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + decorators: this.decorators, + pattern: this.pattern, + typeAnnotation: this.typeAnnotation, + initializer: this.initializer, + optional: this.optional, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugFormalParameter.prototype); + } +} + +const DebugFormalParameter = class FormalParameter {}; + +function constructFormalParameterKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "FormalParameter"; + case 1: + return "UniqueFormalParameters"; + case 2: + return "ArrowFormalParameters"; + case 3: + return "Signature"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for FormalParameterKind`); + } +} + +export class FunctionBody { + type = "FunctionBody"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecStatement(internal.pos + 40, internal.ast)); + } + + toJSON() { + return { + type: "FunctionBody", + start: this.start, + end: this.end, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugFunctionBody.prototype); + } +} + +const DebugFunctionBody = class FunctionBody {}; + +export class ArrowFunctionExpression { + type = "ArrowFunctionExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructBool(internal.pos + 48, internal.ast); + } + + get async() { + const internal = this.#internal; + return constructBool(internal.pos + 49, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 16, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 24, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 32, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructBoxFunctionBody(internal.pos + 40, internal.ast); + } + + toJSON() { + return { + type: "ArrowFunctionExpression", + start: this.start, + end: this.end, + expression: this.expression, + async: this.async, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugArrowFunctionExpression.prototype); + } +} + +const DebugArrowFunctionExpression = class ArrowFunctionExpression {}; + +export class YieldExpression { + type = "YieldExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get delegate() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "YieldExpression", + start: this.start, + end: this.end, + delegate: this.delegate, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugYieldExpression.prototype); + } +} + +const DebugYieldExpression = class YieldExpression {}; + +export class Class { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $decorators: void 0, $implements: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get type() { + const internal = this.#internal; + return constructClassType(internal.pos + 136, internal.ast); + } + + get decorators() { + const internal = this.#internal, + cached = internal.$decorators; + if (cached !== void 0) return cached; + return (internal.$decorators = constructVecDecorator(internal.pos + 16, internal.ast)); + } + + get id() { + const internal = this.#internal; + return constructOptionBindingIdentifier(internal.pos + 40, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 72, internal.ast); + } + + get superClass() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 80, internal.ast); + } + + get superTypeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 96, internal.ast); + } + + get implements() { + const internal = this.#internal, + cached = internal.$implements; + if (cached !== void 0) return cached; + return (internal.$implements = constructVecTSClassImplements(internal.pos + 104, internal.ast)); + } + + get body() { + const internal = this.#internal; + return constructBoxClassBody(internal.pos + 128, internal.ast); + } + + get abstract() { + const internal = this.#internal; + return constructBool(internal.pos + 137, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 138, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + type: this.type, + decorators: this.decorators, + id: this.id, + typeParameters: this.typeParameters, + superClass: this.superClass, + superTypeArguments: this.superTypeArguments, + implements: this.implements, + body: this.body, + abstract: this.abstract, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugClass.prototype); + } +} + +const DebugClass = class Class {}; + +function constructClassType(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "ClassDeclaration"; + case 1: + return "ClassExpression"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ClassType`); + } +} + +export class ClassBody { + type = "ClassBody"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecClassElement(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "ClassBody", + start: this.start, + end: this.end, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugClassBody.prototype); + } +} + +const DebugClassBody = class ClassBody {}; + +function constructClassElement(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxStaticBlock(pos + 8, ast); + case 1: + return constructBoxMethodDefinition(pos + 8, ast); + case 2: + return constructBoxPropertyDefinition(pos + 8, ast); + case 3: + return constructBoxAccessorProperty(pos + 8, ast); + case 4: + return constructBoxTSIndexSignature(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ClassElement`); + } +} + +export class MethodDefinition { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $decorators: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get type() { + const internal = this.#internal; + return constructMethodDefinitionType(internal.pos + 12, internal.ast); + } + + get decorators() { + const internal = this.#internal, + cached = internal.$decorators; + if (cached !== void 0) return cached; + return (internal.$decorators = constructVecDecorator(internal.pos + 16, internal.ast)); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 40, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructBoxFunction(internal.pos + 56, internal.ast); + } + + get kind() { + const internal = this.#internal; + return constructMethodDefinitionKind(internal.pos + 13, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 14, internal.ast); + } + + get static() { + const internal = this.#internal; + return constructBool(internal.pos + 15, internal.ast); + } + + get override() { + const internal = this.#internal; + return constructBool(internal.pos + 64, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 65, internal.ast); + } + + get accessibility() { + const internal = this.#internal; + return constructOptionTSAccessibility(internal.pos + 66, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + type: this.type, + decorators: this.decorators, + key: this.key, + value: this.value, + kind: this.kind, + computed: this.computed, + static: this.static, + override: this.override, + optional: this.optional, + accessibility: this.accessibility, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugMethodDefinition.prototype); + } +} + +const DebugMethodDefinition = class MethodDefinition {}; + +function constructMethodDefinitionType(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "MethodDefinition"; + case 1: + return "TSAbstractMethodDefinition"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for MethodDefinitionType`); + } +} + +export class PropertyDefinition { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $decorators: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get type() { + const internal = this.#internal; + return constructPropertyDefinitionType(internal.pos + 12, internal.ast); + } + + get decorators() { + const internal = this.#internal, + cached = internal.$decorators; + if (cached !== void 0) return cached; + return (internal.$decorators = constructVecDecorator(internal.pos + 16, internal.ast)); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 40, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 56, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 64, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + get static() { + const internal = this.#internal; + return constructBool(internal.pos + 14, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 15, internal.ast); + } + + get override() { + const internal = this.#internal; + return constructBool(internal.pos + 80, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 81, internal.ast); + } + + get definite() { + const internal = this.#internal; + return constructBool(internal.pos + 82, internal.ast); + } + + get readonly() { + const internal = this.#internal; + return constructBool(internal.pos + 83, internal.ast); + } + + get accessibility() { + const internal = this.#internal; + return constructOptionTSAccessibility(internal.pos + 84, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + type: this.type, + decorators: this.decorators, + key: this.key, + typeAnnotation: this.typeAnnotation, + value: this.value, + computed: this.computed, + static: this.static, + declare: this.declare, + override: this.override, + optional: this.optional, + definite: this.definite, + readonly: this.readonly, + accessibility: this.accessibility, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugPropertyDefinition.prototype); + } +} + +const DebugPropertyDefinition = class PropertyDefinition {}; + +function constructPropertyDefinitionType(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "PropertyDefinition"; + case 1: + return "TSAbstractPropertyDefinition"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for PropertyDefinitionType`); + } +} + +function constructMethodDefinitionKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "constructor"; + case 1: + return "method"; + case 2: + return "get"; + case 3: + return "set"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for MethodDefinitionKind`); + } +} + +export class PrivateIdentifier { + type = "PrivateIdentifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "PrivateIdentifier", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugPrivateIdentifier.prototype); + } +} + +const DebugPrivateIdentifier = class PrivateIdentifier {}; + +export class StaticBlock { + type = "StaticBlock"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecStatement(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "StaticBlock", + start: this.start, + end: this.end, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugStaticBlock.prototype); + } +} + +const DebugStaticBlock = class StaticBlock {}; + +function constructModuleDeclaration(pos, ast) { + switch (ast.buffer[pos]) { + case 64: + return constructBoxImportDeclaration(pos + 8, ast); + case 65: + return constructBoxExportAllDeclaration(pos + 8, ast); + case 66: + return constructBoxExportDefaultDeclaration(pos + 8, ast); + case 67: + return constructBoxExportNamedDeclaration(pos + 8, ast); + case 68: + return constructBoxTSExportAssignment(pos + 8, ast); + case 69: + return constructBoxTSNamespaceExportDeclaration(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ModuleDeclaration`); + } +} + +function constructAccessorPropertyType(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "AccessorProperty"; + case 1: + return "TSAbstractAccessorProperty"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AccessorPropertyType`); + } +} + +export class AccessorProperty { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $decorators: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get type() { + const internal = this.#internal; + return constructAccessorPropertyType(internal.pos + 12, internal.ast); + } + + get decorators() { + const internal = this.#internal, + cached = internal.$decorators; + if (cached !== void 0) return cached; + return (internal.$decorators = constructVecDecorator(internal.pos + 16, internal.ast)); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 40, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 56, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 64, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + get static() { + const internal = this.#internal; + return constructBool(internal.pos + 14, internal.ast); + } + + get override() { + const internal = this.#internal; + return constructBool(internal.pos + 15, internal.ast); + } + + get definite() { + const internal = this.#internal; + return constructBool(internal.pos + 80, internal.ast); + } + + get accessibility() { + const internal = this.#internal; + return constructOptionTSAccessibility(internal.pos + 81, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + type: this.type, + decorators: this.decorators, + key: this.key, + typeAnnotation: this.typeAnnotation, + value: this.value, + computed: this.computed, + static: this.static, + override: this.override, + definite: this.definite, + accessibility: this.accessibility, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugAccessorProperty.prototype); + } +} + +const DebugAccessorProperty = class AccessorProperty {}; + +export class ImportExpression { + type = "ImportExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get source() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get options() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 32, internal.ast); + } + + get phase() { + const internal = this.#internal; + return constructOptionImportPhase(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "ImportExpression", + start: this.start, + end: this.end, + source: this.source, + options: this.options, + phase: this.phase, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportExpression.prototype); + } +} + +const DebugImportExpression = class ImportExpression {}; + +export class ImportDeclaration { + type = "ImportDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $specifiers: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get specifiers() { + const internal = this.#internal, + cached = internal.$specifiers; + if (cached !== void 0) return cached; + return (internal.$specifiers = constructOptionVecImportDeclarationSpecifier( + internal.pos + 16, + internal.ast, + )); + } + + get source() { + const internal = this.#internal; + return new StringLiteral(internal.pos + 40, internal.ast); + } + + get phase() { + const internal = this.#internal; + return constructOptionImportPhase(internal.pos + 12, internal.ast); + } + + get attributes() { + const internal = this.#internal; + return constructOptionBoxWithClause(internal.pos + 88, internal.ast); + } + + get importKind() { + const internal = this.#internal; + return constructImportOrExportKind(internal.pos + 13, internal.ast); + } + + toJSON() { + return { + type: "ImportDeclaration", + start: this.start, + end: this.end, + specifiers: this.specifiers, + source: this.source, + phase: this.phase, + attributes: this.attributes, + importKind: this.importKind, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportDeclaration.prototype); + } +} + +const DebugImportDeclaration = class ImportDeclaration {}; + +function constructImportPhase(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "source"; + case 1: + return "defer"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportPhase`); + } +} + +function constructImportDeclarationSpecifier(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxImportSpecifier(pos + 8, ast); + case 1: + return constructBoxImportDefaultSpecifier(pos + 8, ast); + case 2: + return constructBoxImportNamespaceSpecifier(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportDeclarationSpecifier`); + } +} + +export class ImportSpecifier { + type = "ImportSpecifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get imported() { + const internal = this.#internal; + return constructModuleExportName(internal.pos + 16, internal.ast); + } + + get local() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 72, internal.ast); + } + + get importKind() { + const internal = this.#internal; + return constructImportOrExportKind(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "ImportSpecifier", + start: this.start, + end: this.end, + imported: this.imported, + local: this.local, + importKind: this.importKind, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportSpecifier.prototype); + } +} + +const DebugImportSpecifier = class ImportSpecifier {}; + +export class ImportDefaultSpecifier { + type = "ImportDefaultSpecifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get local() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ImportDefaultSpecifier", + start: this.start, + end: this.end, + local: this.local, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportDefaultSpecifier.prototype); + } +} + +const DebugImportDefaultSpecifier = class ImportDefaultSpecifier {}; + +export class ImportNamespaceSpecifier { + type = "ImportNamespaceSpecifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get local() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ImportNamespaceSpecifier", + start: this.start, + end: this.end, + local: this.local, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportNamespaceSpecifier.prototype); + } +} + +const DebugImportNamespaceSpecifier = class ImportNamespaceSpecifier {}; + +export class WithClause { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $attributes: void 0 }; + nodes.set(pos, this); + } + + get attributes() { + const internal = this.#internal, + cached = internal.$attributes; + if (cached !== void 0) return cached; + return (internal.$attributes = constructVecImportAttribute(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + attributes: this.attributes, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugWithClause.prototype); + } +} + +const DebugWithClause = class WithClause {}; + +export class ImportAttribute { + type = "ImportAttribute"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get key() { + const internal = this.#internal; + return constructImportAttributeKey(internal.pos + 16, internal.ast); + } + + get value() { + const internal = this.#internal; + return new StringLiteral(internal.pos + 72, internal.ast); + } + + toJSON() { + return { + type: "ImportAttribute", + start: this.start, + end: this.end, + key: this.key, + value: this.value, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportAttribute.prototype); + } +} + +const DebugImportAttribute = class ImportAttribute {}; + +function constructImportAttributeKey(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new IdentifierName(pos + 8, ast); + case 1: + return new StringLiteral(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportAttributeKey`); + } +} + +export class ExportNamedDeclaration { + type = "ExportNamedDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $specifiers: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get declaration() { + const internal = this.#internal; + return constructOptionDeclaration(internal.pos + 16, internal.ast); + } + + get specifiers() { + const internal = this.#internal, + cached = internal.$specifiers; + if (cached !== void 0) return cached; + return (internal.$specifiers = constructVecExportSpecifier(internal.pos + 32, internal.ast)); + } + + get source() { + const internal = this.#internal; + return constructOptionStringLiteral(internal.pos + 56, internal.ast); + } + + get exportKind() { + const internal = this.#internal; + return constructImportOrExportKind(internal.pos + 12, internal.ast); + } + + get attributes() { + const internal = this.#internal; + return constructOptionBoxWithClause(internal.pos + 104, internal.ast); + } + + toJSON() { + return { + type: "ExportNamedDeclaration", + start: this.start, + end: this.end, + declaration: this.declaration, + specifiers: this.specifiers, + source: this.source, + exportKind: this.exportKind, + attributes: this.attributes, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugExportNamedDeclaration.prototype); + } +} + +const DebugExportNamedDeclaration = class ExportNamedDeclaration {}; + +export class ExportDefaultDeclaration { + type = "ExportDefaultDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get declaration() { + const internal = this.#internal; + return constructExportDefaultDeclarationKind(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "ExportDefaultDeclaration", + start: this.start, + end: this.end, + declaration: this.declaration, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugExportDefaultDeclaration.prototype); + } +} + +const DebugExportDefaultDeclaration = class ExportDefaultDeclaration {}; + +export class ExportAllDeclaration { + type = "ExportAllDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get exported() { + const internal = this.#internal; + return constructOptionModuleExportName(internal.pos + 16, internal.ast); + } + + get source() { + const internal = this.#internal; + return new StringLiteral(internal.pos + 72, internal.ast); + } + + get attributes() { + const internal = this.#internal; + return constructOptionBoxWithClause(internal.pos + 120, internal.ast); + } + + get exportKind() { + const internal = this.#internal; + return constructImportOrExportKind(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "ExportAllDeclaration", + start: this.start, + end: this.end, + exported: this.exported, + source: this.source, + attributes: this.attributes, + exportKind: this.exportKind, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugExportAllDeclaration.prototype); + } +} + +const DebugExportAllDeclaration = class ExportAllDeclaration {}; + +export class ExportSpecifier { + type = "ExportSpecifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get local() { + const internal = this.#internal; + return constructModuleExportName(internal.pos + 16, internal.ast); + } + + get exported() { + const internal = this.#internal; + return constructModuleExportName(internal.pos + 72, internal.ast); + } + + get exportKind() { + const internal = this.#internal; + return constructImportOrExportKind(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "ExportSpecifier", + start: this.start, + end: this.end, + local: this.local, + exported: this.exported, + exportKind: this.exportKind, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugExportSpecifier.prototype); + } +} + +const DebugExportSpecifier = class ExportSpecifier {}; + +function constructExportDefaultDeclarationKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + case 64: + return constructBoxFunction(pos + 8, ast); + case 65: + return constructBoxClass(pos + 8, ast); + case 66: + return constructBoxTSInterfaceDeclaration(pos + 8, ast); + default: + throw new Error( + `Unexpected discriminant ${ast.buffer[pos]} for ExportDefaultDeclarationKind`, + ); + } +} + +function constructModuleExportName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new IdentifierName(pos + 8, ast); + case 1: + return new IdentifierReference(pos + 8, ast); + case 2: + return new StringLiteral(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ModuleExportName`); + } +} + +export class V8IntrinsicExpression { + type = "V8IntrinsicExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $arguments: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 16, internal.ast); + } + + get arguments() { + const internal = this.#internal, + cached = internal.$arguments; + if (cached !== void 0) return cached; + return (internal.$arguments = constructVecArgument(internal.pos + 48, internal.ast)); + } + + toJSON() { + return { + type: "V8IntrinsicExpression", + start: this.start, + end: this.end, + name: this.name, + arguments: this.arguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugV8IntrinsicExpression.prototype); + } +} + +const DebugV8IntrinsicExpression = class V8IntrinsicExpression {}; + +export class BooleanLiteral { + type = "BooleanLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "BooleanLiteral", + start: this.start, + end: this.end, + value: this.value, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBooleanLiteral.prototype); + } +} + +const DebugBooleanLiteral = class BooleanLiteral {}; + +export class NullLiteral { + type = "NullLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "NullLiteral", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugNullLiteral.prototype); + } +} + +const DebugNullLiteral = class NullLiteral {}; + +export class NumericLiteral { + type = "NumericLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $raw: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructF64(internal.pos + 32, internal.ast); + } + + get raw() { + const internal = this.#internal, + cached = internal.$raw; + if (cached !== void 0) return cached; + return (internal.$raw = constructOptionStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "NumericLiteral", + start: this.start, + end: this.end, + value: this.value, + raw: this.raw, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugNumericLiteral.prototype); + } +} + +const DebugNumericLiteral = class NumericLiteral {}; + +export class StringLiteral { + type = "StringLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $value: void 0, $raw: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal, + cached = internal.$value; + if (cached !== void 0) return cached; + return (internal.$value = constructStr(internal.pos + 16, internal.ast)); + } + + get raw() { + const internal = this.#internal, + cached = internal.$raw; + if (cached !== void 0) return cached; + return (internal.$raw = constructOptionStr(internal.pos + 32, internal.ast)); + } + + toJSON() { + return { + type: "StringLiteral", + start: this.start, + end: this.end, + value: this.value, + raw: this.raw, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugStringLiteral.prototype); + } +} + +const DebugStringLiteral = class StringLiteral {}; + +export class BigIntLiteral { + type = "BigIntLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $value: void 0, $raw: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal, + cached = internal.$value; + if (cached !== void 0) return cached; + return (internal.$value = constructStr(internal.pos + 16, internal.ast)); + } + + get raw() { + const internal = this.#internal, + cached = internal.$raw; + if (cached !== void 0) return cached; + return (internal.$raw = constructOptionStr(internal.pos + 32, internal.ast)); + } + + toJSON() { + return { + type: "BigIntLiteral", + start: this.start, + end: this.end, + value: this.value, + raw: this.raw, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugBigIntLiteral.prototype); + } +} + +const DebugBigIntLiteral = class BigIntLiteral {}; + +export class RegExpLiteral { + type = "RegExpLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $raw: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get regex() { + const internal = this.#internal; + return new RegExp(internal.pos + 16, internal.ast); + } + + get raw() { + const internal = this.#internal, + cached = internal.$raw; + if (cached !== void 0) return cached; + return (internal.$raw = constructOptionStr(internal.pos + 48, internal.ast)); + } + + toJSON() { + return { + type: "RegExpLiteral", + start: this.start, + end: this.end, + regex: this.regex, + raw: this.raw, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugRegExpLiteral.prototype); + } +} + +const DebugRegExpLiteral = class RegExpLiteral {}; + +export class RegExp { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + // `pos` would be same as one of fields, so add offset to ensure unique cache key + const cached = nodes.get(pos + 1); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos + 1, this); + } + + get pattern() { + const internal = this.#internal; + return new RegExpPattern(internal.pos, internal.ast); + } + + get flags() { + const internal = this.#internal; + return new RegExpFlags(internal.pos + 24, internal.ast); + } + + toJSON() { + return { + pattern: this.pattern, + flags: this.flags, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugRegExp.prototype); + } +} + +const DebugRegExp = class RegExp {}; + +export class RegExpPattern { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $pattern: void 0 }; + nodes.set(pos, this); + } + + get pattern() { + const internal = this.#internal, + cached = internal.$pattern; + if (cached !== void 0) return cached; + return (internal.$pattern = constructStr(internal.pos, internal.ast)); + } + + toJSON() { + return { + pattern: this.pattern, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugRegExpPattern.prototype); + } +} + +const DebugRegExpPattern = class RegExpPattern {}; + +export class RegExpFlags { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + toJSON() { + return {}; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugRegExpFlags.prototype); + } +} + +const DebugRegExpFlags = class RegExpFlags {}; + +export class JSXElement { + type = "JSXElement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $children: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get openingElement() { + const internal = this.#internal; + return constructBoxJSXOpeningElement(internal.pos + 16, internal.ast); + } + + get children() { + const internal = this.#internal, + cached = internal.$children; + if (cached !== void 0) return cached; + return (internal.$children = constructVecJSXChild(internal.pos + 24, internal.ast)); + } + + get closingElement() { + const internal = this.#internal; + return constructOptionBoxJSXClosingElement(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "JSXElement", + start: this.start, + end: this.end, + openingElement: this.openingElement, + children: this.children, + closingElement: this.closingElement, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXElement.prototype); + } +} + +const DebugJSXElement = class JSXElement {}; + +export class JSXOpeningElement { + type = "JSXOpeningElement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $attributes: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal; + return constructJSXElementName(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + get attributes() { + const internal = this.#internal, + cached = internal.$attributes; + if (cached !== void 0) return cached; + return (internal.$attributes = constructVecJSXAttributeItem(internal.pos + 40, internal.ast)); + } + + toJSON() { + return { + type: "JSXOpeningElement", + start: this.start, + end: this.end, + name: this.name, + typeArguments: this.typeArguments, + attributes: this.attributes, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXOpeningElement.prototype); + } +} + +const DebugJSXOpeningElement = class JSXOpeningElement {}; + +export class JSXClosingElement { + type = "JSXClosingElement"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal; + return constructJSXElementName(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "JSXClosingElement", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXClosingElement.prototype); + } +} + +const DebugJSXClosingElement = class JSXClosingElement {}; + +export class JSXFragment { + type = "JSXFragment"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $children: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get openingFragment() { + const internal = this.#internal; + return new JSXOpeningFragment(internal.pos + 16, internal.ast); + } + + get children() { + const internal = this.#internal, + cached = internal.$children; + if (cached !== void 0) return cached; + return (internal.$children = constructVecJSXChild(internal.pos + 32, internal.ast)); + } + + get closingFragment() { + const internal = this.#internal; + return new JSXClosingFragment(internal.pos + 56, internal.ast); + } + + toJSON() { + return { + type: "JSXFragment", + start: this.start, + end: this.end, + openingFragment: this.openingFragment, + children: this.children, + closingFragment: this.closingFragment, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXFragment.prototype); + } +} + +const DebugJSXFragment = class JSXFragment {}; + +export class JSXOpeningFragment { + type = "JSXOpeningFragment"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "JSXOpeningFragment", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXOpeningFragment.prototype); + } +} + +const DebugJSXOpeningFragment = class JSXOpeningFragment {}; + +export class JSXClosingFragment { + type = "JSXClosingFragment"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "JSXClosingFragment", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXClosingFragment.prototype); + } +} + +const DebugJSXClosingFragment = class JSXClosingFragment {}; + +function constructJSXElementName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxJSXIdentifier(pos + 8, ast); + case 1: + return constructBoxIdentifierReference(pos + 8, ast); + case 2: + return constructBoxJSXNamespacedName(pos + 8, ast); + case 3: + return constructBoxJSXMemberExpression(pos + 8, ast); + case 4: + return constructBoxThisExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXElementName`); + } +} + +export class JSXNamespacedName { + type = "JSXNamespacedName"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get namespace() { + const internal = this.#internal; + return new JSXIdentifier(internal.pos + 16, internal.ast); + } + + get name() { + const internal = this.#internal; + return new JSXIdentifier(internal.pos + 48, internal.ast); + } + + toJSON() { + return { + type: "JSXNamespacedName", + start: this.start, + end: this.end, + namespace: this.namespace, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXNamespacedName.prototype); + } +} + +const DebugJSXNamespacedName = class JSXNamespacedName {}; + +export class JSXMemberExpression { + type = "JSXMemberExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get object() { + const internal = this.#internal; + return constructJSXMemberExpressionObject(internal.pos + 16, internal.ast); + } + + get property() { + const internal = this.#internal; + return new JSXIdentifier(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "JSXMemberExpression", + start: this.start, + end: this.end, + object: this.object, + property: this.property, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXMemberExpression.prototype); + } +} + +const DebugJSXMemberExpression = class JSXMemberExpression {}; + +function constructJSXMemberExpressionObject(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxJSXMemberExpression(pos + 8, ast); + case 2: + return constructBoxThisExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXMemberExpressionObject`); + } +} + +export class JSXExpressionContainer { + type = "JSXExpressionContainer"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructJSXExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "JSXExpressionContainer", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXExpressionContainer.prototype); + } +} + +const DebugJSXExpressionContainer = class JSXExpressionContainer {}; + +function constructJSXExpression(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNullLiteral(pos + 8, ast); + case 2: + return constructBoxNumericLiteral(pos + 8, ast); + case 3: + return constructBoxBigIntLiteral(pos + 8, ast); + case 4: + return constructBoxRegExpLiteral(pos + 8, ast); + case 5: + return constructBoxStringLiteral(pos + 8, ast); + case 6: + return constructBoxTemplateLiteral(pos + 8, ast); + case 7: + return constructBoxIdentifierReference(pos + 8, ast); + case 8: + return constructBoxMetaProperty(pos + 8, ast); + case 9: + return constructBoxSuper(pos + 8, ast); + case 10: + return constructBoxArrayExpression(pos + 8, ast); + case 11: + return constructBoxArrowFunctionExpression(pos + 8, ast); + case 12: + return constructBoxAssignmentExpression(pos + 8, ast); + case 13: + return constructBoxAwaitExpression(pos + 8, ast); + case 14: + return constructBoxBinaryExpression(pos + 8, ast); + case 15: + return constructBoxCallExpression(pos + 8, ast); + case 16: + return constructBoxChainExpression(pos + 8, ast); + case 17: + return constructBoxClass(pos + 8, ast); + case 18: + return constructBoxConditionalExpression(pos + 8, ast); + case 19: + return constructBoxFunction(pos + 8, ast); + case 20: + return constructBoxImportExpression(pos + 8, ast); + case 21: + return constructBoxLogicalExpression(pos + 8, ast); + case 22: + return constructBoxNewExpression(pos + 8, ast); + case 23: + return constructBoxObjectExpression(pos + 8, ast); + case 24: + return constructBoxParenthesizedExpression(pos + 8, ast); + case 25: + return constructBoxSequenceExpression(pos + 8, ast); + case 26: + return constructBoxTaggedTemplateExpression(pos + 8, ast); + case 27: + return constructBoxThisExpression(pos + 8, ast); + case 28: + return constructBoxUnaryExpression(pos + 8, ast); + case 29: + return constructBoxUpdateExpression(pos + 8, ast); + case 30: + return constructBoxYieldExpression(pos + 8, ast); + case 31: + return constructBoxPrivateInExpression(pos + 8, ast); + case 32: + return constructBoxJSXElement(pos + 8, ast); + case 33: + return constructBoxJSXFragment(pos + 8, ast); + case 34: + return constructBoxTSAsExpression(pos + 8, ast); + case 35: + return constructBoxTSSatisfiesExpression(pos + 8, ast); + case 36: + return constructBoxTSTypeAssertion(pos + 8, ast); + case 37: + return constructBoxTSNonNullExpression(pos + 8, ast); + case 38: + return constructBoxTSInstantiationExpression(pos + 8, ast); + case 39: + return constructBoxV8IntrinsicExpression(pos + 8, ast); + case 48: + return constructBoxComputedMemberExpression(pos + 8, ast); + case 49: + return constructBoxStaticMemberExpression(pos + 8, ast); + case 50: + return constructBoxPrivateFieldExpression(pos + 8, ast); + case 64: + return new JSXEmptyExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXExpression`); + } +} + +export class JSXEmptyExpression { + type = "JSXEmptyExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "JSXEmptyExpression", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXEmptyExpression.prototype); + } +} + +const DebugJSXEmptyExpression = class JSXEmptyExpression {}; + +function constructJSXAttributeItem(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxJSXAttribute(pos + 8, ast); + case 1: + return constructBoxJSXSpreadAttribute(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXAttributeItem`); + } +} + +export class JSXAttribute { + type = "JSXAttribute"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal; + return constructJSXAttributeName(internal.pos + 16, internal.ast); + } + + get value() { + const internal = this.#internal; + return constructOptionJSXAttributeValue(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "JSXAttribute", + start: this.start, + end: this.end, + name: this.name, + value: this.value, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXAttribute.prototype); + } +} + +const DebugJSXAttribute = class JSXAttribute {}; + +export class JSXSpreadAttribute { + type = "JSXSpreadAttribute"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get argument() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "JSXSpreadAttribute", + start: this.start, + end: this.end, + argument: this.argument, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXSpreadAttribute.prototype); + } +} + +const DebugJSXSpreadAttribute = class JSXSpreadAttribute {}; + +function constructJSXAttributeName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxJSXIdentifier(pos + 8, ast); + case 1: + return constructBoxJSXNamespacedName(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXAttributeName`); + } +} + +function constructJSXAttributeValue(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxStringLiteral(pos + 8, ast); + case 1: + return constructBoxJSXExpressionContainer(pos + 8, ast); + case 2: + return constructBoxJSXElement(pos + 8, ast); + case 3: + return constructBoxJSXFragment(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXAttributeValue`); + } +} + +export class JSXIdentifier { + type = "JSXIdentifier"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "JSXIdentifier", + start: this.start, + end: this.end, + name: this.name, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXIdentifier.prototype); + } +} + +const DebugJSXIdentifier = class JSXIdentifier {}; + +function constructJSXChild(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxJSXText(pos + 8, ast); + case 1: + return constructBoxJSXElement(pos + 8, ast); + case 2: + return constructBoxJSXFragment(pos + 8, ast); + case 3: + return constructBoxJSXExpressionContainer(pos + 8, ast); + case 4: + return constructBoxJSXSpreadChild(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXChild`); + } +} + +export class JSXSpreadChild { + type = "JSXSpreadChild"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "JSXSpreadChild", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXSpreadChild.prototype); + } +} + +const DebugJSXSpreadChild = class JSXSpreadChild {}; + +export class JSXText { + type = "JSXText"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $value: void 0, $raw: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get value() { + const internal = this.#internal, + cached = internal.$value; + if (cached !== void 0) return cached; + return (internal.$value = constructStr(internal.pos + 16, internal.ast)); + } + + get raw() { + const internal = this.#internal, + cached = internal.$raw; + if (cached !== void 0) return cached; + return (internal.$raw = constructOptionStr(internal.pos + 32, internal.ast)); + } + + toJSON() { + return { + type: "JSXText", + start: this.start, + end: this.end, + value: this.value, + raw: this.raw, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSXText.prototype); + } +} + +const DebugJSXText = class JSXText {}; + +export class TSThisParameter { + type = "TSThisParameter"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 24, internal.ast); + } + + toJSON() { + return { + type: "TSThisParameter", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSThisParameter.prototype); + } +} + +const DebugTSThisParameter = class TSThisParameter {}; + +export class TSEnumDeclaration { + type = "TSEnumDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + get body() { + const internal = this.#internal; + return new TSEnumBody(internal.pos + 48, internal.ast); + } + + get const() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + toJSON() { + return { + type: "TSEnumDeclaration", + start: this.start, + end: this.end, + id: this.id, + body: this.body, + const: this.const, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSEnumDeclaration.prototype); + } +} + +const DebugTSEnumDeclaration = class TSEnumDeclaration {}; + +export class TSEnumBody { + type = "TSEnumBody"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $members: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get members() { + const internal = this.#internal, + cached = internal.$members; + if (cached !== void 0) return cached; + return (internal.$members = constructVecTSEnumMember(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSEnumBody", + start: this.start, + end: this.end, + members: this.members, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSEnumBody.prototype); + } +} + +const DebugTSEnumBody = class TSEnumBody {}; + +export class TSEnumMember { + type = "TSEnumMember"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return constructTSEnumMemberName(internal.pos + 16, internal.ast); + } + + get initializer() { + const internal = this.#internal; + return constructOptionExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSEnumMember", + start: this.start, + end: this.end, + id: this.id, + initializer: this.initializer, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSEnumMember.prototype); + } +} + +const DebugTSEnumMember = class TSEnumMember {}; + +function constructTSEnumMemberName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierName(pos + 8, ast); + case 1: + return constructBoxStringLiteral(pos + 8, ast); + case 2: + return constructBoxStringLiteral(pos + 8, ast); + case 3: + return constructBoxTemplateLiteral(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSEnumMemberName`); + } +} + +export class TSTypeAnnotation { + type = "TSTypeAnnotation"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSTypeAnnotation", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeAnnotation.prototype); + } +} + +const DebugTSTypeAnnotation = class TSTypeAnnotation {}; + +export class TSLiteralType { + type = "TSLiteralType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get literal() { + const internal = this.#internal; + return constructTSLiteral(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSLiteralType", + start: this.start, + end: this.end, + literal: this.literal, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSLiteralType.prototype); + } +} + +const DebugTSLiteralType = class TSLiteralType {}; + +function constructTSLiteral(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxBooleanLiteral(pos + 8, ast); + case 1: + return constructBoxNumericLiteral(pos + 8, ast); + case 2: + return constructBoxBigIntLiteral(pos + 8, ast); + case 3: + return constructBoxStringLiteral(pos + 8, ast); + case 4: + return constructBoxTemplateLiteral(pos + 8, ast); + case 5: + return constructBoxUnaryExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSLiteral`); + } +} + +function constructTSType(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxTSAnyKeyword(pos + 8, ast); + case 1: + return constructBoxTSBigIntKeyword(pos + 8, ast); + case 2: + return constructBoxTSBooleanKeyword(pos + 8, ast); + case 3: + return constructBoxTSIntrinsicKeyword(pos + 8, ast); + case 4: + return constructBoxTSNeverKeyword(pos + 8, ast); + case 5: + return constructBoxTSNullKeyword(pos + 8, ast); + case 6: + return constructBoxTSNumberKeyword(pos + 8, ast); + case 7: + return constructBoxTSObjectKeyword(pos + 8, ast); + case 8: + return constructBoxTSStringKeyword(pos + 8, ast); + case 9: + return constructBoxTSSymbolKeyword(pos + 8, ast); + case 10: + return constructBoxTSThisType(pos + 8, ast); + case 11: + return constructBoxTSUndefinedKeyword(pos + 8, ast); + case 12: + return constructBoxTSUnknownKeyword(pos + 8, ast); + case 13: + return constructBoxTSVoidKeyword(pos + 8, ast); + case 14: + return constructBoxTSArrayType(pos + 8, ast); + case 15: + return constructBoxTSConditionalType(pos + 8, ast); + case 16: + return constructBoxTSConstructorType(pos + 8, ast); + case 17: + return constructBoxTSFunctionType(pos + 8, ast); + case 18: + return constructBoxTSImportType(pos + 8, ast); + case 19: + return constructBoxTSIndexedAccessType(pos + 8, ast); + case 20: + return constructBoxTSInferType(pos + 8, ast); + case 21: + return constructBoxTSIntersectionType(pos + 8, ast); + case 22: + return constructBoxTSLiteralType(pos + 8, ast); + case 23: + return constructBoxTSMappedType(pos + 8, ast); + case 24: + return constructBoxTSNamedTupleMember(pos + 8, ast); + case 26: + return constructBoxTSTemplateLiteralType(pos + 8, ast); + case 27: + return constructBoxTSTupleType(pos + 8, ast); + case 28: + return constructBoxTSTypeLiteral(pos + 8, ast); + case 29: + return constructBoxTSTypeOperator(pos + 8, ast); + case 30: + return constructBoxTSTypePredicate(pos + 8, ast); + case 31: + return constructBoxTSTypeQuery(pos + 8, ast); + case 32: + return constructBoxTSTypeReference(pos + 8, ast); + case 33: + return constructBoxTSUnionType(pos + 8, ast); + case 34: + return constructBoxTSParenthesizedType(pos + 8, ast); + case 35: + return constructBoxJSDocNullableType(pos + 8, ast); + case 36: + return constructBoxJSDocNonNullableType(pos + 8, ast); + case 37: + return constructBoxJSDocUnknownType(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSType`); + } +} + +export class TSConditionalType { + type = "TSConditionalType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get checkType() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + get extendsType() { + const internal = this.#internal; + return constructTSType(internal.pos + 32, internal.ast); + } + + get trueType() { + const internal = this.#internal; + return constructTSType(internal.pos + 48, internal.ast); + } + + get falseType() { + const internal = this.#internal; + return constructTSType(internal.pos + 64, internal.ast); + } + + toJSON() { + return { + type: "TSConditionalType", + start: this.start, + end: this.end, + checkType: this.checkType, + extendsType: this.extendsType, + trueType: this.trueType, + falseType: this.falseType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSConditionalType.prototype); + } +} + +const DebugTSConditionalType = class TSConditionalType {}; + +export class TSUnionType { + type = "TSUnionType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $types: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get types() { + const internal = this.#internal, + cached = internal.$types; + if (cached !== void 0) return cached; + return (internal.$types = constructVecTSType(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSUnionType", + start: this.start, + end: this.end, + types: this.types, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSUnionType.prototype); + } +} + +const DebugTSUnionType = class TSUnionType {}; + +export class TSIntersectionType { + type = "TSIntersectionType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $types: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get types() { + const internal = this.#internal, + cached = internal.$types; + if (cached !== void 0) return cached; + return (internal.$types = constructVecTSType(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSIntersectionType", + start: this.start, + end: this.end, + types: this.types, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSIntersectionType.prototype); + } +} + +const DebugTSIntersectionType = class TSIntersectionType {}; + +export class TSParenthesizedType { + type = "TSParenthesizedType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSParenthesizedType", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSParenthesizedType.prototype); + } +} + +const DebugTSParenthesizedType = class TSParenthesizedType {}; + +export class TSTypeOperator { + type = "TSTypeOperator"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get operator() { + const internal = this.#internal; + return constructTSTypeOperatorOperator(internal.pos + 12, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSTypeOperator", + start: this.start, + end: this.end, + operator: this.operator, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeOperator.prototype); + } +} + +const DebugTSTypeOperator = class TSTypeOperator {}; + +function constructTSTypeOperatorOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "keyof"; + case 1: + return "unique"; + case 2: + return "readonly"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypeOperatorOperator`); + } +} + +export class TSArrayType { + type = "TSArrayType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get elementType() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSArrayType", + start: this.start, + end: this.end, + elementType: this.elementType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSArrayType.prototype); + } +} + +const DebugTSArrayType = class TSArrayType {}; + +export class TSIndexedAccessType { + type = "TSIndexedAccessType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get objectType() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + get indexType() { + const internal = this.#internal; + return constructTSType(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSIndexedAccessType", + start: this.start, + end: this.end, + objectType: this.objectType, + indexType: this.indexType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSIndexedAccessType.prototype); + } +} + +const DebugTSIndexedAccessType = class TSIndexedAccessType {}; + +export class TSTupleType { + type = "TSTupleType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $elementTypes: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get elementTypes() { + const internal = this.#internal, + cached = internal.$elementTypes; + if (cached !== void 0) return cached; + return (internal.$elementTypes = constructVecTSTupleElement(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSTupleType", + start: this.start, + end: this.end, + elementTypes: this.elementTypes, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTupleType.prototype); + } +} + +const DebugTSTupleType = class TSTupleType {}; + +export class TSNamedTupleMember { + type = "TSNamedTupleMember"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get label() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 16, internal.ast); + } + + get elementType() { + const internal = this.#internal; + return constructTSTupleElement(internal.pos + 48, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "TSNamedTupleMember", + start: this.start, + end: this.end, + label: this.label, + elementType: this.elementType, + optional: this.optional, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSNamedTupleMember.prototype); + } +} + +const DebugTSNamedTupleMember = class TSNamedTupleMember {}; + +export class TSOptionalType { + type = "TSOptionalType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSOptionalType", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSOptionalType.prototype); + } +} + +const DebugTSOptionalType = class TSOptionalType {}; + +export class TSRestType { + type = "TSRestType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSRestType", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSRestType.prototype); + } +} + +const DebugTSRestType = class TSRestType {}; + +function constructTSTupleElement(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxTSAnyKeyword(pos + 8, ast); + case 1: + return constructBoxTSBigIntKeyword(pos + 8, ast); + case 2: + return constructBoxTSBooleanKeyword(pos + 8, ast); + case 3: + return constructBoxTSIntrinsicKeyword(pos + 8, ast); + case 4: + return constructBoxTSNeverKeyword(pos + 8, ast); + case 5: + return constructBoxTSNullKeyword(pos + 8, ast); + case 6: + return constructBoxTSNumberKeyword(pos + 8, ast); + case 7: + return constructBoxTSObjectKeyword(pos + 8, ast); + case 8: + return constructBoxTSStringKeyword(pos + 8, ast); + case 9: + return constructBoxTSSymbolKeyword(pos + 8, ast); + case 10: + return constructBoxTSThisType(pos + 8, ast); + case 11: + return constructBoxTSUndefinedKeyword(pos + 8, ast); + case 12: + return constructBoxTSUnknownKeyword(pos + 8, ast); + case 13: + return constructBoxTSVoidKeyword(pos + 8, ast); + case 14: + return constructBoxTSArrayType(pos + 8, ast); + case 15: + return constructBoxTSConditionalType(pos + 8, ast); + case 16: + return constructBoxTSConstructorType(pos + 8, ast); + case 17: + return constructBoxTSFunctionType(pos + 8, ast); + case 18: + return constructBoxTSImportType(pos + 8, ast); + case 19: + return constructBoxTSIndexedAccessType(pos + 8, ast); + case 20: + return constructBoxTSInferType(pos + 8, ast); + case 21: + return constructBoxTSIntersectionType(pos + 8, ast); + case 22: + return constructBoxTSLiteralType(pos + 8, ast); + case 23: + return constructBoxTSMappedType(pos + 8, ast); + case 24: + return constructBoxTSNamedTupleMember(pos + 8, ast); + case 26: + return constructBoxTSTemplateLiteralType(pos + 8, ast); + case 27: + return constructBoxTSTupleType(pos + 8, ast); + case 28: + return constructBoxTSTypeLiteral(pos + 8, ast); + case 29: + return constructBoxTSTypeOperator(pos + 8, ast); + case 30: + return constructBoxTSTypePredicate(pos + 8, ast); + case 31: + return constructBoxTSTypeQuery(pos + 8, ast); + case 32: + return constructBoxTSTypeReference(pos + 8, ast); + case 33: + return constructBoxTSUnionType(pos + 8, ast); + case 34: + return constructBoxTSParenthesizedType(pos + 8, ast); + case 35: + return constructBoxJSDocNullableType(pos + 8, ast); + case 36: + return constructBoxJSDocNonNullableType(pos + 8, ast); + case 37: + return constructBoxJSDocUnknownType(pos + 8, ast); + case 64: + return constructBoxTSOptionalType(pos + 8, ast); + case 65: + return constructBoxTSRestType(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTupleElement`); + } +} + +export class TSAnyKeyword { + type = "TSAnyKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSAnyKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSAnyKeyword.prototype); + } +} + +const DebugTSAnyKeyword = class TSAnyKeyword {}; + +export class TSStringKeyword { + type = "TSStringKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSStringKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSStringKeyword.prototype); + } +} + +const DebugTSStringKeyword = class TSStringKeyword {}; + +export class TSBooleanKeyword { + type = "TSBooleanKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSBooleanKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSBooleanKeyword.prototype); + } +} + +const DebugTSBooleanKeyword = class TSBooleanKeyword {}; + +export class TSNumberKeyword { + type = "TSNumberKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSNumberKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSNumberKeyword.prototype); + } +} + +const DebugTSNumberKeyword = class TSNumberKeyword {}; + +export class TSNeverKeyword { + type = "TSNeverKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSNeverKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSNeverKeyword.prototype); + } +} + +const DebugTSNeverKeyword = class TSNeverKeyword {}; + +export class TSIntrinsicKeyword { + type = "TSIntrinsicKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSIntrinsicKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSIntrinsicKeyword.prototype); + } +} + +const DebugTSIntrinsicKeyword = class TSIntrinsicKeyword {}; + +export class TSUnknownKeyword { + type = "TSUnknownKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSUnknownKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSUnknownKeyword.prototype); + } +} + +const DebugTSUnknownKeyword = class TSUnknownKeyword {}; + +export class TSNullKeyword { + type = "TSNullKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSNullKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSNullKeyword.prototype); + } +} + +const DebugTSNullKeyword = class TSNullKeyword {}; + +export class TSUndefinedKeyword { + type = "TSUndefinedKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSUndefinedKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSUndefinedKeyword.prototype); + } +} + +const DebugTSUndefinedKeyword = class TSUndefinedKeyword {}; + +export class TSVoidKeyword { + type = "TSVoidKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSVoidKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSVoidKeyword.prototype); + } +} + +const DebugTSVoidKeyword = class TSVoidKeyword {}; + +export class TSSymbolKeyword { + type = "TSSymbolKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSSymbolKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSSymbolKeyword.prototype); + } +} + +const DebugTSSymbolKeyword = class TSSymbolKeyword {}; + +export class TSThisType { + type = "TSThisType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSThisType", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSThisType.prototype); + } +} + +const DebugTSThisType = class TSThisType {}; + +export class TSObjectKeyword { + type = "TSObjectKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSObjectKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSObjectKeyword.prototype); + } +} + +const DebugTSObjectKeyword = class TSObjectKeyword {}; + +export class TSBigIntKeyword { + type = "TSBigIntKeyword"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "TSBigIntKeyword", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSBigIntKeyword.prototype); + } +} + +const DebugTSBigIntKeyword = class TSBigIntKeyword {}; + +export class TSTypeReference { + type = "TSTypeReference"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeName() { + const internal = this.#internal; + return constructTSTypeName(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSTypeReference", + start: this.start, + end: this.end, + typeName: this.typeName, + typeArguments: this.typeArguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeReference.prototype); + } +} + +const DebugTSTypeReference = class TSTypeReference {}; + +function constructTSTypeName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxTSQualifiedName(pos + 8, ast); + case 2: + return constructBoxThisExpression(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypeName`); + } +} + +export class TSQualifiedName { + type = "TSQualifiedName"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructTSTypeName(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSQualifiedName", + start: this.start, + end: this.end, + left: this.left, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSQualifiedName.prototype); + } +} + +const DebugTSQualifiedName = class TSQualifiedName {}; + +export class TSTypeParameterInstantiation { + type = "TSTypeParameterInstantiation"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $params: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get params() { + const internal = this.#internal, + cached = internal.$params; + if (cached !== void 0) return cached; + return (internal.$params = constructVecTSType(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSTypeParameterInstantiation", + start: this.start, + end: this.end, + params: this.params, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeParameterInstantiation.prototype); + } +} + +const DebugTSTypeParameterInstantiation = class TSTypeParameterInstantiation {}; + +export class TSTypeParameter { + type = "TSTypeParameter"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + get constraint() { + const internal = this.#internal; + return constructOptionTSType(internal.pos + 48, internal.ast); + } + + get default() { + const internal = this.#internal; + return constructOptionTSType(internal.pos + 64, internal.ast); + } + + get in() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get out() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + get const() { + const internal = this.#internal; + return constructBool(internal.pos + 14, internal.ast); + } + + toJSON() { + return { + type: "TSTypeParameter", + start: this.start, + end: this.end, + name: this.name, + constraint: this.constraint, + default: this.default, + in: this.in, + out: this.out, + const: this.const, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeParameter.prototype); + } +} + +const DebugTSTypeParameter = class TSTypeParameter {}; + +export class TSTypeParameterDeclaration { + type = "TSTypeParameterDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $params: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get params() { + const internal = this.#internal, + cached = internal.$params; + if (cached !== void 0) return cached; + return (internal.$params = constructVecTSTypeParameter(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSTypeParameterDeclaration", + start: this.start, + end: this.end, + params: this.params, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeParameterDeclaration.prototype); + } +} + +const DebugTSTypeParameterDeclaration = class TSTypeParameterDeclaration {}; + +export class TSTypeAliasDeclaration { + type = "TSTypeAliasDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 48, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 56, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 72, internal.ast); + } + + toJSON() { + return { + type: "TSTypeAliasDeclaration", + start: this.start, + end: this.end, + id: this.id, + typeParameters: this.typeParameters, + typeAnnotation: this.typeAnnotation, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeAliasDeclaration.prototype); + } +} + +const DebugTSTypeAliasDeclaration = class TSTypeAliasDeclaration {}; + +function constructTSAccessibility(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "private"; + case 1: + return "protected"; + case 2: + return "public"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSAccessibility`); + } +} + +export class TSClassImplements { + type = "TSClassImplements"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructTSTypeName(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSClassImplements", + start: this.start, + end: this.end, + expression: this.expression, + typeArguments: this.typeArguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSClassImplements.prototype); + } +} + +const DebugTSClassImplements = class TSClassImplements {}; + +export class TSInterfaceDeclaration { + type = "TSInterfaceDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $extends: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 48, internal.ast); + } + + get extends() { + const internal = this.#internal, + cached = internal.$extends; + if (cached !== void 0) return cached; + return (internal.$extends = constructVecTSInterfaceHeritage(internal.pos + 56, internal.ast)); + } + + get body() { + const internal = this.#internal; + return constructBoxTSInterfaceBody(internal.pos + 80, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 88, internal.ast); + } + + toJSON() { + return { + type: "TSInterfaceDeclaration", + start: this.start, + end: this.end, + id: this.id, + typeParameters: this.typeParameters, + extends: this.extends, + body: this.body, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSInterfaceDeclaration.prototype); + } +} + +const DebugTSInterfaceDeclaration = class TSInterfaceDeclaration {}; + +export class TSInterfaceBody { + type = "TSInterfaceBody"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecTSSignature(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSInterfaceBody", + start: this.start, + end: this.end, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSInterfaceBody.prototype); + } +} + +const DebugTSInterfaceBody = class TSInterfaceBody {}; + +export class TSPropertySignature { + type = "TSPropertySignature"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + get readonly() { + const internal = this.#internal; + return constructBool(internal.pos + 14, internal.ast); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 16, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSPropertySignature", + start: this.start, + end: this.end, + computed: this.computed, + optional: this.optional, + readonly: this.readonly, + key: this.key, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSPropertySignature.prototype); + } +} + +const DebugTSPropertySignature = class TSPropertySignature {}; + +function constructTSSignature(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxTSIndexSignature(pos + 8, ast); + case 1: + return constructBoxTSPropertySignature(pos + 8, ast); + case 2: + return constructBoxTSCallSignatureDeclaration(pos + 8, ast); + case 3: + return constructBoxTSConstructSignatureDeclaration(pos + 8, ast); + case 4: + return constructBoxTSMethodSignature(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSSignature`); + } +} + +export class TSIndexSignature { + type = "TSIndexSignature"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $parameters: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get parameters() { + const internal = this.#internal, + cached = internal.$parameters; + if (cached !== void 0) return cached; + return (internal.$parameters = constructVecTSIndexSignatureName( + internal.pos + 16, + internal.ast, + )); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructBoxTSTypeAnnotation(internal.pos + 40, internal.ast); + } + + get readonly() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get static() { + const internal = this.#internal; + return constructBool(internal.pos + 13, internal.ast); + } + + toJSON() { + return { + type: "TSIndexSignature", + start: this.start, + end: this.end, + parameters: this.parameters, + typeAnnotation: this.typeAnnotation, + readonly: this.readonly, + static: this.static, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSIndexSignature.prototype); + } +} + +const DebugTSIndexSignature = class TSIndexSignature {}; + +export class TSCallSignatureDeclaration { + type = "TSCallSignatureDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 16, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 32, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 40, internal.ast); + } + + toJSON() { + return { + type: "TSCallSignatureDeclaration", + start: this.start, + end: this.end, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSCallSignatureDeclaration.prototype); + } +} + +const DebugTSCallSignatureDeclaration = class TSCallSignatureDeclaration {}; + +function constructTSMethodSignatureKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "method"; + case 1: + return "get"; + case 2: + return "set"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSMethodSignatureKind`); + } +} + +export class TSMethodSignature { + type = "TSMethodSignature"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get key() { + const internal = this.#internal; + return constructPropertyKey(internal.pos + 16, internal.ast); + } + + get computed() { + const internal = this.#internal; + return constructBool(internal.pos + 64, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructBool(internal.pos + 65, internal.ast); + } + + get kind() { + const internal = this.#internal; + return constructTSMethodSignatureKind(internal.pos + 66, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 32, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 48, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 56, internal.ast); + } + + toJSON() { + return { + type: "TSMethodSignature", + start: this.start, + end: this.end, + key: this.key, + computed: this.computed, + optional: this.optional, + kind: this.kind, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSMethodSignature.prototype); + } +} + +const DebugTSMethodSignature = class TSMethodSignature {}; + +export class TSConstructSignatureDeclaration { + type = "TSConstructSignatureDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 16, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 24, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSConstructSignatureDeclaration", + start: this.start, + end: this.end, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSConstructSignatureDeclaration.prototype); + } +} + +const DebugTSConstructSignatureDeclaration = class TSConstructSignatureDeclaration {}; + +export class TSIndexSignatureName { + type = "TSIndexSignatureName"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $name: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get name() { + const internal = this.#internal, + cached = internal.$name; + if (cached !== void 0) return cached; + return (internal.$name = constructStr(internal.pos + 16, internal.ast)); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructBoxTSTypeAnnotation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSIndexSignatureName", + start: this.start, + end: this.end, + name: this.name, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSIndexSignatureName.prototype); + } +} + +const DebugTSIndexSignatureName = class TSIndexSignatureName {}; + +export class TSInterfaceHeritage { + type = "TSInterfaceHeritage"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSInterfaceHeritage", + start: this.start, + end: this.end, + expression: this.expression, + typeArguments: this.typeArguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSInterfaceHeritage.prototype); + } +} + +const DebugTSInterfaceHeritage = class TSInterfaceHeritage {}; + +export class TSTypePredicate { + type = "TSTypePredicate"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get parameterName() { + const internal = this.#internal; + return constructTSTypePredicateName(internal.pos + 16, internal.ast); + } + + get asserts() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionBoxTSTypeAnnotation(internal.pos + 40, internal.ast); + } + + toJSON() { + return { + type: "TSTypePredicate", + start: this.start, + end: this.end, + parameterName: this.parameterName, + asserts: this.asserts, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypePredicate.prototype); + } +} + +const DebugTSTypePredicate = class TSTypePredicate {}; + +function constructTSTypePredicateName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierName(pos + 8, ast); + case 1: + return new TSThisType(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypePredicateName`); + } +} + +export class TSModuleDeclaration { + type = "TSModuleDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return constructTSModuleDeclarationName(internal.pos + 16, internal.ast); + } + + get body() { + const internal = this.#internal; + return constructOptionTSModuleDeclarationBody(internal.pos + 72, internal.ast); + } + + get kind() { + const internal = this.#internal; + return constructTSModuleDeclarationKind(internal.pos + 88, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 89, internal.ast); + } + + toJSON() { + return { + type: "TSModuleDeclaration", + start: this.start, + end: this.end, + id: this.id, + body: this.body, + kind: this.kind, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSModuleDeclaration.prototype); + } +} + +const DebugTSModuleDeclaration = class TSModuleDeclaration {}; + +function constructTSModuleDeclarationKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "module"; + case 1: + return "namespace"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleDeclarationKind`); + } +} + +function constructTSModuleDeclarationName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new BindingIdentifier(pos + 8, ast); + case 1: + return new StringLiteral(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleDeclarationName`); + } +} + +function constructTSModuleDeclarationBody(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxTSModuleDeclaration(pos + 8, ast); + case 1: + return constructBoxTSModuleBlock(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleDeclarationBody`); + } +} + +export class TSGlobalDeclaration { + type = "TSGlobalDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal; + return new TSModuleBlock(internal.pos + 24, internal.ast); + } + + get declare() { + const internal = this.#internal; + return constructBool(internal.pos + 88, internal.ast); + } + + toJSON() { + return { + type: "TSGlobalDeclaration", + start: this.start, + end: this.end, + body: this.body, + declare: this.declare, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSGlobalDeclaration.prototype); + } +} + +const DebugTSGlobalDeclaration = class TSGlobalDeclaration {}; + +export class TSModuleBlock { + type = "TSModuleBlock"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $body: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get body() { + const internal = this.#internal, + cached = internal.$body; + if (cached !== void 0) return cached; + return (internal.$body = constructVecStatement(internal.pos + 40, internal.ast)); + } + + toJSON() { + return { + type: "TSModuleBlock", + start: this.start, + end: this.end, + body: this.body, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSModuleBlock.prototype); + } +} + +const DebugTSModuleBlock = class TSModuleBlock {}; + +export class TSTypeLiteral { + type = "TSTypeLiteral"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $members: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get members() { + const internal = this.#internal, + cached = internal.$members; + if (cached !== void 0) return cached; + return (internal.$members = constructVecTSSignature(internal.pos + 16, internal.ast)); + } + + toJSON() { + return { + type: "TSTypeLiteral", + start: this.start, + end: this.end, + members: this.members, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeLiteral.prototype); + } +} + +const DebugTSTypeLiteral = class TSTypeLiteral {}; + +export class TSInferType { + type = "TSInferType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeParameter() { + const internal = this.#internal; + return constructBoxTSTypeParameter(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSInferType", + start: this.start, + end: this.end, + typeParameter: this.typeParameter, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSInferType.prototype); + } +} + +const DebugTSInferType = class TSInferType {}; + +export class TSTypeQuery { + type = "TSTypeQuery"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get exprName() { + const internal = this.#internal; + return constructTSTypeQueryExprName(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSTypeQuery", + start: this.start, + end: this.end, + exprName: this.exprName, + typeArguments: this.typeArguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeQuery.prototype); + } +} + +const DebugTSTypeQuery = class TSTypeQuery {}; + +function constructTSTypeQueryExprName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierReference(pos + 8, ast); + case 1: + return constructBoxTSQualifiedName(pos + 8, ast); + case 2: + return constructBoxThisExpression(pos + 8, ast); + case 3: + return constructBoxTSImportType(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypeQueryExprName`); + } +} + +export class TSImportType { + type = "TSImportType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get source() { + const internal = this.#internal; + return new StringLiteral(internal.pos + 16, internal.ast); + } + + get options() { + const internal = this.#internal; + return constructOptionBoxObjectExpression(internal.pos + 64, internal.ast); + } + + get qualifier() { + const internal = this.#internal; + return constructOptionTSImportTypeQualifier(internal.pos + 72, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterInstantiation(internal.pos + 88, internal.ast); + } + + toJSON() { + return { + type: "TSImportType", + start: this.start, + end: this.end, + source: this.source, + options: this.options, + qualifier: this.qualifier, + typeArguments: this.typeArguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSImportType.prototype); + } +} + +const DebugTSImportType = class TSImportType {}; + +function constructTSImportTypeQualifier(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxIdentifierName(pos + 8, ast); + case 1: + return constructBoxTSImportTypeQualifiedName(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSImportTypeQualifier`); + } +} + +export class TSImportTypeQualifiedName { + type = "TSImportTypeQualifiedName"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get left() { + const internal = this.#internal; + return constructTSImportTypeQualifier(internal.pos + 16, internal.ast); + } + + get right() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSImportTypeQualifiedName", + start: this.start, + end: this.end, + left: this.left, + right: this.right, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSImportTypeQualifiedName.prototype); + } +} + +const DebugTSImportTypeQualifiedName = class TSImportTypeQualifiedName {}; + +export class TSFunctionType { + type = "TSFunctionType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 16, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 32, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructBoxTSTypeAnnotation(internal.pos + 40, internal.ast); + } + + toJSON() { + return { + type: "TSFunctionType", + start: this.start, + end: this.end, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSFunctionType.prototype); + } +} + +const DebugTSFunctionType = class TSFunctionType {}; + +export class TSConstructorType { + type = "TSConstructorType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get abstract() { + const internal = this.#internal; + return constructBool(internal.pos + 40, internal.ast); + } + + get typeParameters() { + const internal = this.#internal; + return constructOptionBoxTSTypeParameterDeclaration(internal.pos + 16, internal.ast); + } + + get params() { + const internal = this.#internal; + return constructBoxFormalParameters(internal.pos + 24, internal.ast); + } + + get returnType() { + const internal = this.#internal; + return constructBoxTSTypeAnnotation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSConstructorType", + start: this.start, + end: this.end, + abstract: this.abstract, + typeParameters: this.typeParameters, + params: this.params, + returnType: this.returnType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSConstructorType.prototype); + } +} + +const DebugTSConstructorType = class TSConstructorType {}; + +export class TSMappedType { + type = "TSMappedType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get key() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + get constraint() { + const internal = this.#internal; + return constructTSType(internal.pos + 48, internal.ast); + } + + get nameType() { + const internal = this.#internal; + return constructOptionTSType(internal.pos + 64, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructOptionTSType(internal.pos + 80, internal.ast); + } + + get optional() { + const internal = this.#internal; + return constructOptionTSMappedTypeModifierOperator(internal.pos + 96, internal.ast); + } + + get readonly() { + const internal = this.#internal; + return constructOptionTSMappedTypeModifierOperator(internal.pos + 97, internal.ast); + } + + toJSON() { + return { + type: "TSMappedType", + start: this.start, + end: this.end, + key: this.key, + constraint: this.constraint, + nameType: this.nameType, + typeAnnotation: this.typeAnnotation, + optional: this.optional, + readonly: this.readonly, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSMappedType.prototype); + } +} + +const DebugTSMappedType = class TSMappedType {}; + +function constructTSMappedTypeModifierOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "true"; + case 1: + return "+"; + case 2: + return "-"; + default: + throw new Error( + `Unexpected discriminant ${ast.buffer[pos]} for TSMappedTypeModifierOperator`, + ); + } +} + +export class TSTemplateLiteralType { + type = "TSTemplateLiteralType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $quasis: void 0, $types: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get quasis() { + const internal = this.#internal, + cached = internal.$quasis; + if (cached !== void 0) return cached; + return (internal.$quasis = constructVecTemplateElement(internal.pos + 16, internal.ast)); + } + + get types() { + const internal = this.#internal, + cached = internal.$types; + if (cached !== void 0) return cached; + return (internal.$types = constructVecTSType(internal.pos + 40, internal.ast)); + } + + toJSON() { + return { + type: "TSTemplateLiteralType", + start: this.start, + end: this.end, + quasis: this.quasis, + types: this.types, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTemplateLiteralType.prototype); + } +} + +const DebugTSTemplateLiteralType = class TSTemplateLiteralType {}; + +export class TSAsExpression { + type = "TSAsExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSAsExpression", + start: this.start, + end: this.end, + expression: this.expression, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSAsExpression.prototype); + } +} + +const DebugTSAsExpression = class TSAsExpression {}; + +export class TSSatisfiesExpression { + type = "TSSatisfiesExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSSatisfiesExpression", + start: this.start, + end: this.end, + expression: this.expression, + typeAnnotation: this.typeAnnotation, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSSatisfiesExpression.prototype); + } +} + +const DebugTSSatisfiesExpression = class TSSatisfiesExpression {}; + +export class TSTypeAssertion { + type = "TSTypeAssertion"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSTypeAssertion", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSTypeAssertion.prototype); + } +} + +const DebugTSTypeAssertion = class TSTypeAssertion {}; + +export class TSImportEqualsDeclaration { + type = "TSImportEqualsDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return new BindingIdentifier(internal.pos + 16, internal.ast); + } + + get moduleReference() { + const internal = this.#internal; + return constructTSModuleReference(internal.pos + 48, internal.ast); + } + + get importKind() { + const internal = this.#internal; + return constructImportOrExportKind(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "TSImportEqualsDeclaration", + start: this.start, + end: this.end, + id: this.id, + moduleReference: this.moduleReference, + importKind: this.importKind, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSImportEqualsDeclaration.prototype); + } +} + +const DebugTSImportEqualsDeclaration = class TSImportEqualsDeclaration {}; + +function constructTSModuleReference(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return constructBoxTSExternalModuleReference(pos + 8, ast); + case 1: + return constructBoxIdentifierReference(pos + 8, ast); + case 2: + return constructBoxTSQualifiedName(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleReference`); + } +} + +export class TSExternalModuleReference { + type = "TSExternalModuleReference"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return new StringLiteral(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSExternalModuleReference", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSExternalModuleReference.prototype); + } +} + +const DebugTSExternalModuleReference = class TSExternalModuleReference {}; + +export class TSNonNullExpression { + type = "TSNonNullExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSNonNullExpression", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSNonNullExpression.prototype); + } +} + +const DebugTSNonNullExpression = class TSNonNullExpression {}; + +export class Decorator { + type = "Decorator"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "Decorator", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugDecorator.prototype); + } +} + +const DebugDecorator = class Decorator {}; + +export class TSExportAssignment { + type = "TSExportAssignment"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSExportAssignment", + start: this.start, + end: this.end, + expression: this.expression, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSExportAssignment.prototype); + } +} + +const DebugTSExportAssignment = class TSExportAssignment {}; + +export class TSNamespaceExportDeclaration { + type = "TSNamespaceExportDeclaration"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get id() { + const internal = this.#internal; + return new IdentifierName(internal.pos + 16, internal.ast); + } + + toJSON() { + return { + type: "TSNamespaceExportDeclaration", + start: this.start, + end: this.end, + id: this.id, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSNamespaceExportDeclaration.prototype); + } +} + +const DebugTSNamespaceExportDeclaration = class TSNamespaceExportDeclaration {}; + +export class TSInstantiationExpression { + type = "TSInstantiationExpression"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get expression() { + const internal = this.#internal; + return constructExpression(internal.pos + 16, internal.ast); + } + + get typeArguments() { + const internal = this.#internal; + return constructBoxTSTypeParameterInstantiation(internal.pos + 32, internal.ast); + } + + toJSON() { + return { + type: "TSInstantiationExpression", + start: this.start, + end: this.end, + expression: this.expression, + typeArguments: this.typeArguments, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugTSInstantiationExpression.prototype); + } +} + +const DebugTSInstantiationExpression = class TSInstantiationExpression {}; + +function constructImportOrExportKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "value"; + case 1: + return "type"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportOrExportKind`); + } +} + +export class JSDocNullableType { + type = "JSDocNullableType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + get postfix() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "JSDocNullableType", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + postfix: this.postfix, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSDocNullableType.prototype); + } +} + +const DebugJSDocNullableType = class JSDocNullableType {}; + +export class JSDocNonNullableType { + type = "JSDocNonNullableType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get typeAnnotation() { + const internal = this.#internal; + return constructTSType(internal.pos + 16, internal.ast); + } + + get postfix() { + const internal = this.#internal; + return constructBool(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + type: "JSDocNonNullableType", + start: this.start, + end: this.end, + typeAnnotation: this.typeAnnotation, + postfix: this.postfix, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSDocNonNullableType.prototype); + } +} + +const DebugJSDocNonNullableType = class JSDocNonNullableType {}; + +export class JSDocUnknownType { + type = "JSDocUnknownType"; + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + type: "JSDocUnknownType", + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugJSDocUnknownType.prototype); + } +} + +const DebugJSDocUnknownType = class JSDocUnknownType {}; + +function constructCommentKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "Line"; + case 1: + return "Block"; + case 2: + return "Block"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for CommentKind`); + } +} + +export class Comment { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get type() { + const internal = this.#internal; + return constructCommentKind(internal.pos + 12, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + type: this.type, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugComment.prototype); + } +} + +const DebugComment = class Comment {}; + +export class SourceType { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get sourceType() { + const internal = this.#internal; + return constructModuleKind(internal.pos + 1, internal.ast); + } + + toJSON() { + return { + sourceType: this.sourceType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSourceType.prototype); + } +} + +const DebugSourceType = class SourceType {}; + +function constructModuleKind(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "script"; + case 1: + return "module"; + case 3: + return "commonjs"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ModuleKind`); + } +} + +export class Span { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugSpan.prototype); + } +} + +const DebugSpan = class Span {}; + +export class NameSpan { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $value: void 0 }; + nodes.set(pos, this); + } + + get value() { + const internal = this.#internal, + cached = internal.$value; + if (cached !== void 0) return cached; + return (internal.$value = constructStr(internal.pos + 8, internal.ast)); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + value: this.value, + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugNameSpan.prototype); + } +} + +const DebugNameSpan = class NameSpan {}; + +export class ImportEntry { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get importName() { + const internal = this.#internal; + return constructImportImportName(internal.pos + 32, internal.ast); + } + + get localName() { + const internal = this.#internal; + return new NameSpan(internal.pos + 64, internal.ast); + } + + get isType() { + const internal = this.#internal; + return constructBool(internal.pos + 88, internal.ast); + } + + toJSON() { + return { + importName: this.importName, + localName: this.localName, + isType: this.isType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugImportEntry.prototype); + } +} + +const DebugImportEntry = class ImportEntry {}; + +function constructImportImportName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new NameSpan(pos + 8, ast); + case 1: + return "namespaceObject"; + case 2: + return new Span(pos + 8, ast); + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportImportName`); + } +} + +export class ExportEntry { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get moduleRequest() { + const internal = this.#internal; + return constructOptionNameSpan(internal.pos + 16, internal.ast); + } + + get importName() { + const internal = this.#internal; + return constructExportImportName(internal.pos + 40, internal.ast); + } + + get exportName() { + const internal = this.#internal; + return constructExportExportName(internal.pos + 72, internal.ast); + } + + get localName() { + const internal = this.#internal; + return constructExportLocalName(internal.pos + 104, internal.ast); + } + + get isType() { + const internal = this.#internal; + return constructBool(internal.pos + 136, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + moduleRequest: this.moduleRequest, + importName: this.importName, + exportName: this.exportName, + localName: this.localName, + isType: this.isType, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugExportEntry.prototype); + } +} + +const DebugExportEntry = class ExportEntry {}; + +function constructExportImportName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new NameSpan(pos + 8, ast); + case 1: + return "all"; + case 2: + return "allButDefault"; + case 3: + return "null"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ExportImportName`); + } +} + +function constructExportExportName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new NameSpan(pos + 8, ast); + case 1: + return new Span(pos + 8, ast); + case 2: + return "null"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ExportExportName`); + } +} + +function constructExportLocalName(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return new NameSpan(pos + 8, ast); + case 1: + return new NameSpan(pos + 8, ast); + case 2: + return "null"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ExportLocalName`); + } +} + +export class DynamicImport { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get moduleRequest() { + const internal = this.#internal; + return new Span(internal.pos + 8, internal.ast); + } + + toJSON() { + return { + start: this.start, + end: this.end, + moduleRequest: this.moduleRequest, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugDynamicImport.prototype); + } +} + +const DebugDynamicImport = class DynamicImport {}; + +function constructAssignmentOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "="; + case 1: + return "+="; + case 2: + return "-="; + case 3: + return "*="; + case 4: + return "/="; + case 5: + return "%="; + case 6: + return "**="; + case 7: + return "<<="; + case 8: + return ">>="; + case 9: + return ">>>="; + case 10: + return "|="; + case 11: + return "^="; + case 12: + return "&="; + case 13: + return "||="; + case 14: + return "&&="; + case 15: + return "??="; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AssignmentOperator`); + } +} + +function constructBinaryOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "=="; + case 1: + return "!="; + case 2: + return "==="; + case 3: + return "!=="; + case 4: + return "<"; + case 5: + return "<="; + case 6: + return ">"; + case 7: + return ">="; + case 8: + return "+"; + case 9: + return "-"; + case 10: + return "*"; + case 11: + return "/"; + case 12: + return "%"; + case 13: + return "**"; + case 14: + return "<<"; + case 15: + return ">>"; + case 16: + return ">>>"; + case 17: + return "|"; + case 18: + return "^"; + case 19: + return "&"; + case 20: + return "in"; + case 21: + return "instanceof"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for BinaryOperator`); + } +} + +function constructLogicalOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "||"; + case 1: + return "&&"; + case 2: + return "??"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for LogicalOperator`); + } +} + +function constructUnaryOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "+"; + case 1: + return "-"; + case 2: + return "!"; + case 3: + return "~"; + case 4: + return "typeof"; + case 5: + return "void"; + case 6: + return "delete"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for UnaryOperator`); + } +} + +function constructUpdateOperator(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "++"; + case 1: + return "--"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for UpdateOperator`); + } +} + +export class RawTransferData { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + // `pos` would be same as one of fields, so add offset to ensure unique cache key + const cached = nodes.get(pos + 1); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $comments: void 0, $errors: void 0 }; + nodes.set(pos + 1, this); + } + + get program() { + const internal = this.#internal; + return new Program(internal.pos, internal.ast); + } + + get comments() { + const internal = this.#internal, + cached = internal.$comments; + if (cached !== void 0) return cached; + return (internal.$comments = constructVecComment(internal.pos + 144, internal.ast)); + } + + get module() { + const internal = this.#internal; + return new EcmaScriptModule(internal.pos + 168, internal.ast); + } + + get errors() { + const internal = this.#internal, + cached = internal.$errors; + if (cached !== void 0) return cached; + return (internal.$errors = constructVecError(internal.pos + 272, internal.ast)); + } + + toJSON() { + return { + program: this.program, + comments: this.comments, + module: this.module, + errors: this.errors, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugRawTransferData.prototype); + } +} + +const DebugRawTransferData = class RawTransferData {}; + +export class Error { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { + pos, + ast, + $message: void 0, + $labels: void 0, + $helpMessage: void 0, + $codeframe: void 0, + }; + nodes.set(pos, this); + } + + get severity() { + const internal = this.#internal; + return constructErrorSeverity(internal.pos + 72, internal.ast); + } + + get message() { + const internal = this.#internal, + cached = internal.$message; + if (cached !== void 0) return cached; + return (internal.$message = constructStr(internal.pos, internal.ast)); + } + + get labels() { + const internal = this.#internal, + cached = internal.$labels; + if (cached !== void 0) return cached; + return (internal.$labels = constructVecErrorLabel(internal.pos + 16, internal.ast)); + } + + get helpMessage() { + const internal = this.#internal, + cached = internal.$helpMessage; + if (cached !== void 0) return cached; + return (internal.$helpMessage = constructOptionStr(internal.pos + 40, internal.ast)); + } + + get codeframe() { + const internal = this.#internal, + cached = internal.$codeframe; + if (cached !== void 0) return cached; + return (internal.$codeframe = constructStr(internal.pos + 56, internal.ast)); + } + + toJSON() { + return { + severity: this.severity, + message: this.message, + labels: this.labels, + helpMessage: this.helpMessage, + codeframe: this.codeframe, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugError.prototype); + } +} + +const DebugError = class Error {}; + +function constructErrorSeverity(pos, ast) { + switch (ast.buffer[pos]) { + case 0: + return "Error"; + case 1: + return "Warning"; + case 2: + return "Advice"; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ErrorSeverity`); + } +} + +export class ErrorLabel { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $message: void 0 }; + nodes.set(pos, this); + } + + get message() { + const internal = this.#internal, + cached = internal.$message; + if (cached !== void 0) return cached; + return (internal.$message = constructOptionStr(internal.pos + 8, internal.ast)); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + toJSON() { + return { + message: this.message, + start: this.start, + end: this.end, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugErrorLabel.prototype); + } +} + +const DebugErrorLabel = class ErrorLabel {}; + +export class EcmaScriptModule { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { + pos, + ast, + $staticImports: void 0, + $staticExports: void 0, + $dynamicImports: void 0, + $importMetas: void 0, + }; + nodes.set(pos, this); + } + + get hasModuleSyntax() { + const internal = this.#internal; + return constructBool(internal.pos + 96, internal.ast); + } + + get staticImports() { + const internal = this.#internal, + cached = internal.$staticImports; + if (cached !== void 0) return cached; + return (internal.$staticImports = constructVecStaticImport(internal.pos, internal.ast)); + } + + get staticExports() { + const internal = this.#internal, + cached = internal.$staticExports; + if (cached !== void 0) return cached; + return (internal.$staticExports = constructVecStaticExport(internal.pos + 24, internal.ast)); + } + + get dynamicImports() { + const internal = this.#internal, + cached = internal.$dynamicImports; + if (cached !== void 0) return cached; + return (internal.$dynamicImports = constructVecDynamicImport(internal.pos + 48, internal.ast)); + } + + get importMetas() { + const internal = this.#internal, + cached = internal.$importMetas; + if (cached !== void 0) return cached; + return (internal.$importMetas = constructVecSpan(internal.pos + 72, internal.ast)); + } + + toJSON() { + return { + hasModuleSyntax: this.hasModuleSyntax, + staticImports: this.staticImports, + staticExports: this.staticExports, + dynamicImports: this.dynamicImports, + importMetas: this.importMetas, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugEcmaScriptModule.prototype); + } +} + +const DebugEcmaScriptModule = class EcmaScriptModule {}; + +export class StaticImport { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $entries: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get moduleRequest() { + const internal = this.#internal; + return new NameSpan(internal.pos + 8, internal.ast); + } + + get entries() { + const internal = this.#internal, + cached = internal.$entries; + if (cached !== void 0) return cached; + return (internal.$entries = constructVecImportEntry(internal.pos + 32, internal.ast)); + } + + toJSON() { + return { + start: this.start, + end: this.end, + moduleRequest: this.moduleRequest, + entries: this.entries, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugStaticImport.prototype); + } +} + +const DebugStaticImport = class StaticImport {}; + +export class StaticExport { + #internal; + + constructor(pos, ast) { + if (ast?.token !== TOKEN) constructorError(); + + const { nodes } = ast; + const cached = nodes.get(pos); + if (cached !== void 0) return cached; + + this.#internal = { pos, ast, $entries: void 0 }; + nodes.set(pos, this); + } + + get start() { + const internal = this.#internal; + return constructI32(internal.pos, internal.ast); + } + + get end() { + const internal = this.#internal; + return constructI32(internal.pos + 4, internal.ast); + } + + get entries() { + const internal = this.#internal, + cached = internal.$entries; + if (cached !== void 0) return cached; + return (internal.$entries = constructVecExportEntry(internal.pos + 8, internal.ast)); + } + + toJSON() { + return { + start: this.start, + end: this.end, + entries: this.entries, + }; + } + + [inspectSymbol]() { + return Object.setPrototypeOf(this.toJSON(), DebugStaticExport.prototype); + } +} + +const DebugStaticExport = class StaticExport {}; + +function constructStr(pos, ast) { + const pos32 = pos >> 2, + { buffer } = ast, + { int32 } = buffer, + len = int32[pos32 + 2]; + if (len === 0) return ""; + + pos = int32[pos32]; + if (ast.sourceIsAscii && pos < ast.sourceByteLen) return ast.sourceText.substr(pos, len); + + // Longer strings use `TextDecoder` + // TODO: Find best switch-over point + const end = pos + len; + if (len > 50) return decodeStr(buffer.subarray(pos, end)); + + // Shorter strings decode by hand to avoid native call + let out = "", + c; + do { + c = buffer[pos++]; + if (c < 0x80) { + out += fromCodePoint(c); + } else { + out += decodeStr(buffer.subarray(pos - 1, end)); + break; + } + } while (pos < end); + + return out; +} + +function constructVecComment(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructComment, ast); +} + +function constructComment(pos, ast) { + return new Comment(pos, ast); +} + +function constructOptionHashbang(pos, ast) { + if (ast.buffer.int32[(pos >> 2) + 4] === 0 && ast.buffer.int32[(pos >> 2) + 5] === 0) return null; + return new Hashbang(pos, ast); +} + +function constructVecDirective(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 80, constructDirective, ast); +} + +function constructDirective(pos, ast) { + return new Directive(pos, ast); +} + +function constructVecStatement(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructStatement, ast); +} + +function constructBoxBooleanLiteral(pos, ast) { + return new BooleanLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxNullLiteral(pos, ast) { + return new NullLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxNumericLiteral(pos, ast) { + return new NumericLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxBigIntLiteral(pos, ast) { + return new BigIntLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxRegExpLiteral(pos, ast) { + return new RegExpLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxStringLiteral(pos, ast) { + return new StringLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTemplateLiteral(pos, ast) { + return new TemplateLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxIdentifierReference(pos, ast) { + return new IdentifierReference(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxMetaProperty(pos, ast) { + return new MetaProperty(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxSuper(pos, ast) { + return new Super(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxArrayExpression(pos, ast) { + return new ArrayExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxArrowFunctionExpression(pos, ast) { + return new ArrowFunctionExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxAssignmentExpression(pos, ast) { + return new AssignmentExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxAwaitExpression(pos, ast) { + return new AwaitExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxBinaryExpression(pos, ast) { + return new BinaryExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxCallExpression(pos, ast) { + return new CallExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxChainExpression(pos, ast) { + return new ChainExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxClass(pos, ast) { + return new Class(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxConditionalExpression(pos, ast) { + return new ConditionalExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxFunction(pos, ast) { + return new Function(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxImportExpression(pos, ast) { + return new ImportExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxLogicalExpression(pos, ast) { + return new LogicalExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxNewExpression(pos, ast) { + return new NewExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxObjectExpression(pos, ast) { + return new ObjectExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxParenthesizedExpression(pos, ast) { + return new ParenthesizedExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxSequenceExpression(pos, ast) { + return new SequenceExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTaggedTemplateExpression(pos, ast) { + return new TaggedTemplateExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxThisExpression(pos, ast) { + return new ThisExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxUnaryExpression(pos, ast) { + return new UnaryExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxUpdateExpression(pos, ast) { + return new UpdateExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxYieldExpression(pos, ast) { + return new YieldExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxPrivateInExpression(pos, ast) { + return new PrivateInExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXElement(pos, ast) { + return new JSXElement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXFragment(pos, ast) { + return new JSXFragment(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSAsExpression(pos, ast) { + return new TSAsExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSSatisfiesExpression(pos, ast) { + return new TSSatisfiesExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeAssertion(pos, ast) { + return new TSTypeAssertion(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSNonNullExpression(pos, ast) { + return new TSNonNullExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSInstantiationExpression(pos, ast) { + return new TSInstantiationExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxV8IntrinsicExpression(pos, ast) { + return new V8IntrinsicExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecArrayExpressionElement(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 24, constructArrayExpressionElement, ast); +} + +function constructBoxSpreadElement(pos, ast) { + return new SpreadElement(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecObjectPropertyKind(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructObjectPropertyKind, ast); +} + +function constructBoxObjectProperty(pos, ast) { + return new ObjectProperty(ast.buffer.int32[pos >> 2], ast); +} + +function constructBool(pos, ast) { + return ast.buffer[pos] === 1; +} + +function constructBoxIdentifierName(pos, ast) { + return new IdentifierName(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxPrivateIdentifier(pos, ast) { + return new PrivateIdentifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecTemplateElement(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 48, constructTemplateElement, ast); +} + +function constructTemplateElement(pos, ast) { + return new TemplateElement(pos, ast); +} + +function constructVecExpression(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructExpression, ast); +} + +function constructBoxTSTypeParameterInstantiation(pos, ast) { + return new TSTypeParameterInstantiation(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxTSTypeParameterInstantiation(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxTSTypeParameterInstantiation(pos, ast); +} + +function constructOptionStr(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructStr(pos, ast); +} + +function constructBoxComputedMemberExpression(pos, ast) { + return new ComputedMemberExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxStaticMemberExpression(pos, ast) { + return new StaticMemberExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxPrivateFieldExpression(pos, ast) { + return new PrivateFieldExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecArgument(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructArgument, ast); +} + +function constructBoxArrayAssignmentTarget(pos, ast) { + return new ArrayAssignmentTarget(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxObjectAssignmentTarget(pos, ast) { + return new ObjectAssignmentTarget(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionAssignmentTargetMaybeDefault(pos, ast) { + if (ast.buffer[pos] === 51) return null; + return constructAssignmentTargetMaybeDefault(pos, ast); +} + +function constructVecOptionAssignmentTargetMaybeDefault(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray( + int32[pos32], + int32[pos32 + 2], + 16, + constructOptionAssignmentTargetMaybeDefault, + ast, + ); +} + +function constructBoxAssignmentTargetRest(pos, ast) { + return new AssignmentTargetRest(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxAssignmentTargetRest(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxAssignmentTargetRest(pos, ast); +} + +function constructVecAssignmentTargetProperty(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructAssignmentTargetProperty, ast); +} + +function constructBoxAssignmentTargetWithDefault(pos, ast) { + return new AssignmentTargetWithDefault(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxAssignmentTargetPropertyIdentifier(pos, ast) { + return new AssignmentTargetPropertyIdentifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxAssignmentTargetPropertyProperty(pos, ast) { + return new AssignmentTargetPropertyProperty(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionExpression(pos, ast) { + if (ast.buffer[pos] === 51) return null; + return constructExpression(pos, ast); +} + +function constructBoxBlockStatement(pos, ast) { + return new BlockStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxBreakStatement(pos, ast) { + return new BreakStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxContinueStatement(pos, ast) { + return new ContinueStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxDebuggerStatement(pos, ast) { + return new DebuggerStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxDoWhileStatement(pos, ast) { + return new DoWhileStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxEmptyStatement(pos, ast) { + return new EmptyStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxExpressionStatement(pos, ast) { + return new ExpressionStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxForInStatement(pos, ast) { + return new ForInStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxForOfStatement(pos, ast) { + return new ForOfStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxForStatement(pos, ast) { + return new ForStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxIfStatement(pos, ast) { + return new IfStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxLabeledStatement(pos, ast) { + return new LabeledStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxReturnStatement(pos, ast) { + return new ReturnStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxSwitchStatement(pos, ast) { + return new SwitchStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxThrowStatement(pos, ast) { + return new ThrowStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTryStatement(pos, ast) { + return new TryStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxWhileStatement(pos, ast) { + return new WhileStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxWithStatement(pos, ast) { + return new WithStatement(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxVariableDeclaration(pos, ast) { + return new VariableDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeAliasDeclaration(pos, ast) { + return new TSTypeAliasDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSInterfaceDeclaration(pos, ast) { + return new TSInterfaceDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSEnumDeclaration(pos, ast) { + return new TSEnumDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSModuleDeclaration(pos, ast) { + return new TSModuleDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSGlobalDeclaration(pos, ast) { + return new TSGlobalDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSImportEqualsDeclaration(pos, ast) { + return new TSImportEqualsDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecVariableDeclarator(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 56, constructVariableDeclarator, ast); +} + +function constructVariableDeclarator(pos, ast) { + return new VariableDeclarator(pos, ast); +} + +function constructBoxTSTypeAnnotation(pos, ast) { + return new TSTypeAnnotation(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxTSTypeAnnotation(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxTSTypeAnnotation(pos, ast); +} + +function constructOptionStatement(pos, ast) { + if (ast.buffer[pos] === 70) return null; + return constructStatement(pos, ast); +} + +function constructOptionForStatementInit(pos, ast) { + if (ast.buffer[pos] === 65) return null; + return constructForStatementInit(pos, ast); +} + +function constructOptionLabelIdentifier(pos, ast) { + if (ast.buffer.int32[(pos >> 2) + 4] === 0 && ast.buffer.int32[(pos >> 2) + 5] === 0) return null; + return new LabelIdentifier(pos, ast); +} + +function constructVecSwitchCase(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 56, constructSwitchCase, ast); +} + +function constructSwitchCase(pos, ast) { + return new SwitchCase(pos, ast); +} + +function constructBoxCatchClause(pos, ast) { + return new CatchClause(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxCatchClause(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxCatchClause(pos, ast); +} + +function constructOptionBoxBlockStatement(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxBlockStatement(pos, ast); +} + +function constructOptionCatchParameter(pos, ast) { + if (ast.buffer[pos + 16] === 4) return null; + return new CatchParameter(pos, ast); +} + +function constructBoxBindingIdentifier(pos, ast) { + return new BindingIdentifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxObjectPattern(pos, ast) { + return new ObjectPattern(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxArrayPattern(pos, ast) { + return new ArrayPattern(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxAssignmentPattern(pos, ast) { + return new AssignmentPattern(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecBindingProperty(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 48, constructBindingProperty, ast); +} + +function constructBindingProperty(pos, ast) { + return new BindingProperty(pos, ast); +} + +function constructBoxBindingRestElement(pos, ast) { + return new BindingRestElement(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxBindingRestElement(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxBindingRestElement(pos, ast); +} + +function constructOptionBindingPattern(pos, ast) { + if (ast.buffer[pos] === 4) return null; + return constructBindingPattern(pos, ast); +} + +function constructVecOptionBindingPattern(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructOptionBindingPattern, ast); +} + +function constructOptionBindingIdentifier(pos, ast) { + if (ast.buffer.int32[(pos >> 2) + 4] === 0 && ast.buffer.int32[(pos >> 2) + 5] === 0) return null; + return new BindingIdentifier(pos, ast); +} + +function constructBoxTSTypeParameterDeclaration(pos, ast) { + return new TSTypeParameterDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxTSTypeParameterDeclaration(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxTSTypeParameterDeclaration(pos, ast); +} + +function constructBoxTSThisParameter(pos, ast) { + return new TSThisParameter(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxTSThisParameter(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxTSThisParameter(pos, ast); +} + +function constructBoxFormalParameters(pos, ast) { + return new FormalParameters(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxFunctionBody(pos, ast) { + return new FunctionBody(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxFunctionBody(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxFunctionBody(pos, ast); +} + +function constructVecFormalParameter(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 72, constructFormalParameter, ast); +} + +function constructFormalParameter(pos, ast) { + return new FormalParameter(pos, ast); +} + +function constructVecDecorator(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 32, constructDecorator, ast); +} + +function constructDecorator(pos, ast) { + return new Decorator(pos, ast); +} + +function constructBoxExpression(pos, ast) { + return constructExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxExpression(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxExpression(pos, ast); +} + +function constructOptionTSAccessibility(pos, ast) { + if (ast.buffer[pos] === 3) return null; + return constructTSAccessibility(pos, ast); +} + +function constructVecTSClassImplements(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 40, constructTSClassImplements, ast); +} + +function constructTSClassImplements(pos, ast) { + return new TSClassImplements(pos, ast); +} + +function constructBoxClassBody(pos, ast) { + return new ClassBody(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecClassElement(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructClassElement, ast); +} + +function constructBoxStaticBlock(pos, ast) { + return new StaticBlock(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxMethodDefinition(pos, ast) { + return new MethodDefinition(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxPropertyDefinition(pos, ast) { + return new PropertyDefinition(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxAccessorProperty(pos, ast) { + return new AccessorProperty(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSIndexSignature(pos, ast) { + return new TSIndexSignature(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxImportDeclaration(pos, ast) { + return new ImportDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxExportAllDeclaration(pos, ast) { + return new ExportAllDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxExportDefaultDeclaration(pos, ast) { + return new ExportDefaultDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxExportNamedDeclaration(pos, ast) { + return new ExportNamedDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSExportAssignment(pos, ast) { + return new TSExportAssignment(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSNamespaceExportDeclaration(pos, ast) { + return new TSNamespaceExportDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionImportPhase(pos, ast) { + if (ast.buffer[pos] === 2) return null; + return constructImportPhase(pos, ast); +} + +function constructVecImportDeclarationSpecifier(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray( + int32[pos32], + int32[pos32 + 2], + 16, + constructImportDeclarationSpecifier, + ast, + ); +} + +function constructOptionVecImportDeclarationSpecifier(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructVecImportDeclarationSpecifier(pos, ast); +} + +function constructBoxWithClause(pos, ast) { + return new WithClause(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxWithClause(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxWithClause(pos, ast); +} + +function constructBoxImportSpecifier(pos, ast) { + return new ImportSpecifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxImportDefaultSpecifier(pos, ast) { + return new ImportDefaultSpecifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxImportNamespaceSpecifier(pos, ast) { + return new ImportNamespaceSpecifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecImportAttribute(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 120, constructImportAttribute, ast); +} + +function constructImportAttribute(pos, ast) { + return new ImportAttribute(pos, ast); +} + +function constructOptionDeclaration(pos, ast) { + if (ast.buffer[pos] === 31) return null; + return constructDeclaration(pos, ast); +} + +function constructVecExportSpecifier(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 128, constructExportSpecifier, ast); +} + +function constructExportSpecifier(pos, ast) { + return new ExportSpecifier(pos, ast); +} + +function constructOptionStringLiteral(pos, ast) { + if (ast.buffer[pos + 12] === 2) return null; + return new StringLiteral(pos, ast); +} + +function constructOptionModuleExportName(pos, ast) { + if (ast.buffer[pos] === 3) return null; + return constructModuleExportName(pos, ast); +} + +function constructF64(pos, ast) { + return ast.buffer.float64[pos >> 3]; +} + +function constructU8(pos, ast) { + return ast.buffer[pos]; +} + +function constructBoxJSXOpeningElement(pos, ast) { + return new JSXOpeningElement(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecJSXChild(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructJSXChild, ast); +} + +function constructBoxJSXClosingElement(pos, ast) { + return new JSXClosingElement(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxJSXClosingElement(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxJSXClosingElement(pos, ast); +} + +function constructVecJSXAttributeItem(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructJSXAttributeItem, ast); +} + +function constructBoxJSXIdentifier(pos, ast) { + return new JSXIdentifier(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXNamespacedName(pos, ast) { + return new JSXNamespacedName(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXMemberExpression(pos, ast) { + return new JSXMemberExpression(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXAttribute(pos, ast) { + return new JSXAttribute(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXSpreadAttribute(pos, ast) { + return new JSXSpreadAttribute(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionJSXAttributeValue(pos, ast) { + if (ast.buffer[pos] === 4) return null; + return constructJSXAttributeValue(pos, ast); +} + +function constructBoxJSXExpressionContainer(pos, ast) { + return new JSXExpressionContainer(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXText(pos, ast) { + return new JSXText(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSXSpreadChild(pos, ast) { + return new JSXSpreadChild(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecTSEnumMember(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 48, constructTSEnumMember, ast); +} + +function constructTSEnumMember(pos, ast) { + return new TSEnumMember(pos, ast); +} + +function constructBoxTSAnyKeyword(pos, ast) { + return new TSAnyKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSBigIntKeyword(pos, ast) { + return new TSBigIntKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSBooleanKeyword(pos, ast) { + return new TSBooleanKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSIntrinsicKeyword(pos, ast) { + return new TSIntrinsicKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSNeverKeyword(pos, ast) { + return new TSNeverKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSNullKeyword(pos, ast) { + return new TSNullKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSNumberKeyword(pos, ast) { + return new TSNumberKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSObjectKeyword(pos, ast) { + return new TSObjectKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSStringKeyword(pos, ast) { + return new TSStringKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSSymbolKeyword(pos, ast) { + return new TSSymbolKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSUndefinedKeyword(pos, ast) { + return new TSUndefinedKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSUnknownKeyword(pos, ast) { + return new TSUnknownKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSVoidKeyword(pos, ast) { + return new TSVoidKeyword(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSArrayType(pos, ast) { + return new TSArrayType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSConditionalType(pos, ast) { + return new TSConditionalType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSConstructorType(pos, ast) { + return new TSConstructorType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSFunctionType(pos, ast) { + return new TSFunctionType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSImportType(pos, ast) { + return new TSImportType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSIndexedAccessType(pos, ast) { + return new TSIndexedAccessType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSInferType(pos, ast) { + return new TSInferType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSIntersectionType(pos, ast) { + return new TSIntersectionType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSLiteralType(pos, ast) { + return new TSLiteralType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSMappedType(pos, ast) { + return new TSMappedType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSNamedTupleMember(pos, ast) { + return new TSNamedTupleMember(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTemplateLiteralType(pos, ast) { + return new TSTemplateLiteralType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSThisType(pos, ast) { + return new TSThisType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTupleType(pos, ast) { + return new TSTupleType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeLiteral(pos, ast) { + return new TSTypeLiteral(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeOperator(pos, ast) { + return new TSTypeOperator(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypePredicate(pos, ast) { + return new TSTypePredicate(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeQuery(pos, ast) { + return new TSTypeQuery(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeReference(pos, ast) { + return new TSTypeReference(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSUnionType(pos, ast) { + return new TSUnionType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSParenthesizedType(pos, ast) { + return new TSParenthesizedType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSDocNullableType(pos, ast) { + return new JSDocNullableType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSDocNonNullableType(pos, ast) { + return new JSDocNonNullableType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxJSDocUnknownType(pos, ast) { + return new JSDocUnknownType(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecTSType(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructTSType, ast); +} + +function constructVecTSTupleElement(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructTSTupleElement, ast); +} + +function constructBoxTSOptionalType(pos, ast) { + return new TSOptionalType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSRestType(pos, ast) { + return new TSRestType(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSQualifiedName(pos, ast) { + return new TSQualifiedName(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionTSType(pos, ast) { + if (ast.buffer[pos] === 38) return null; + return constructTSType(pos, ast); +} + +function constructVecTSTypeParameter(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 80, constructTSTypeParameter, ast); +} + +function constructTSTypeParameter(pos, ast) { + return new TSTypeParameter(pos, ast); +} + +function constructVecTSInterfaceHeritage(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 40, constructTSInterfaceHeritage, ast); +} + +function constructTSInterfaceHeritage(pos, ast) { + return new TSInterfaceHeritage(pos, ast); +} + +function constructBoxTSInterfaceBody(pos, ast) { + return new TSInterfaceBody(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecTSSignature(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructTSSignature, ast); +} + +function constructBoxTSPropertySignature(pos, ast) { + return new TSPropertySignature(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSCallSignatureDeclaration(pos, ast) { + return new TSCallSignatureDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSConstructSignatureDeclaration(pos, ast) { + return new TSConstructSignatureDeclaration(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSMethodSignature(pos, ast) { + return new TSMethodSignature(ast.buffer.int32[pos >> 2], ast); +} + +function constructVecTSIndexSignatureName(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 40, constructTSIndexSignatureName, ast); +} + +function constructTSIndexSignatureName(pos, ast) { + return new TSIndexSignatureName(pos, ast); +} + +function constructOptionTSModuleDeclarationBody(pos, ast) { + if (ast.buffer[pos] === 2) return null; + return constructTSModuleDeclarationBody(pos, ast); +} + +function constructBoxTSModuleBlock(pos, ast) { + return new TSModuleBlock(ast.buffer.int32[pos >> 2], ast); +} + +function constructBoxTSTypeParameter(pos, ast) { + return new TSTypeParameter(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionBoxObjectExpression(pos, ast) { + if (ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0) return null; + return constructBoxObjectExpression(pos, ast); +} + +function constructOptionTSImportTypeQualifier(pos, ast) { + if (ast.buffer[pos] === 2) return null; + return constructTSImportTypeQualifier(pos, ast); +} + +function constructBoxTSImportTypeQualifiedName(pos, ast) { + return new TSImportTypeQualifiedName(ast.buffer.int32[pos >> 2], ast); +} + +function constructOptionTSMappedTypeModifierOperator(pos, ast) { + if (ast.buffer[pos] === 3) return null; + return constructTSMappedTypeModifierOperator(pos, ast); +} + +function constructBoxTSExternalModuleReference(pos, ast) { + return new TSExternalModuleReference(ast.buffer.int32[pos >> 2], ast); +} + +function constructU32(pos, ast) { + return ast.buffer.int32[pos >> 2] >>> 0; +} + +function constructU64(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return (int32[pos32] >>> 0) + (int32[pos32 + 1] >>> 0) * /* 2^32 */ 4294967296; +} + +function constructOptionU64(pos, ast) { + if (ast.buffer[pos] === 0) return null; + return constructU64(pos + 8, ast); +} + +function constructI32(pos, ast) { + return ast.buffer.int32[pos >> 2]; +} + +function constructOptionNameSpan(pos, ast) { + if (ast.buffer.int32[(pos >> 2) + 2] === 0 && ast.buffer.int32[(pos >> 2) + 3] === 0) return null; + return new NameSpan(pos, ast); +} + +function constructVecError(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 80, constructError, ast); +} + +function constructError(pos, ast) { + return new Error(pos, ast); +} + +function constructVecErrorLabel(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 24, constructErrorLabel, ast); +} + +function constructErrorLabel(pos, ast) { + return new ErrorLabel(pos, ast); +} + +function constructVecStaticImport(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 56, constructStaticImport, ast); +} + +function constructStaticImport(pos, ast) { + return new StaticImport(pos, ast); +} + +function constructVecStaticExport(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 32, constructStaticExport, ast); +} + +function constructStaticExport(pos, ast) { + return new StaticExport(pos, ast); +} + +function constructVecDynamicImport(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 16, constructDynamicImport, ast); +} + +function constructDynamicImport(pos, ast) { + return new DynamicImport(pos, ast); +} + +function constructVecSpan(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 8, constructSpan, ast); +} + +function constructSpan(pos, ast) { + return new Span(pos, ast); +} + +function constructVecImportEntry(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 96, constructImportEntry, ast); +} + +function constructImportEntry(pos, ast) { + return new ImportEntry(pos, ast); +} + +function constructVecExportEntry(pos, ast) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + return new NodeArray(int32[pos32], int32[pos32 + 2], 144, constructExportEntry, ast); +} + +function constructExportEntry(pos, ast) { + return new ExportEntry(pos, ast); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/type_ids.js b/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/type_ids.js new file mode 100644 index 0000000000000000000000000000000000000000..49682a4b0f5d0b8663029f250dff7ede5096a562 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/type_ids.js @@ -0,0 +1,191 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer_lazy.rs`. + +// Mapping from node type name to node type ID +export const NODE_TYPE_IDS_MAP = new Map([ + // Leaf nodes + ["IdentifierName", 0], + ["IdentifierReference", 1], + ["BindingIdentifier", 2], + ["LabelIdentifier", 3], + ["ThisExpression", 4], + ["Elision", 5], + ["TemplateElement", 6], + ["Super", 7], + ["Hashbang", 8], + ["EmptyStatement", 9], + ["DebuggerStatement", 10], + ["PrivateIdentifier", 11], + ["BooleanLiteral", 12], + ["NullLiteral", 13], + ["NumericLiteral", 14], + ["StringLiteral", 15], + ["BigIntLiteral", 16], + ["RegExpLiteral", 17], + ["JSXOpeningFragment", 18], + ["JSXClosingFragment", 19], + ["JSXEmptyExpression", 20], + ["JSXIdentifier", 21], + ["JSXText", 22], + ["TSAnyKeyword", 23], + ["TSStringKeyword", 24], + ["TSBooleanKeyword", 25], + ["TSNumberKeyword", 26], + ["TSNeverKeyword", 27], + ["TSIntrinsicKeyword", 28], + ["TSUnknownKeyword", 29], + ["TSNullKeyword", 30], + ["TSUndefinedKeyword", 31], + ["TSVoidKeyword", 32], + ["TSSymbolKeyword", 33], + ["TSThisType", 34], + ["TSObjectKeyword", 35], + ["TSBigIntKeyword", 36], + ["JSDocUnknownType", 37], + // Non-leaf nodes + ["Program", 38], + ["ArrayExpression", 39], + ["ObjectExpression", 40], + ["ObjectProperty", 41], + ["TemplateLiteral", 42], + ["TaggedTemplateExpression", 43], + ["ComputedMemberExpression", 44], + ["StaticMemberExpression", 45], + ["PrivateFieldExpression", 46], + ["CallExpression", 47], + ["NewExpression", 48], + ["MetaProperty", 49], + ["SpreadElement", 50], + ["UpdateExpression", 51], + ["UnaryExpression", 52], + ["BinaryExpression", 53], + ["PrivateInExpression", 54], + ["LogicalExpression", 55], + ["ConditionalExpression", 56], + ["AssignmentExpression", 57], + ["ArrayAssignmentTarget", 58], + ["ObjectAssignmentTarget", 59], + ["AssignmentTargetWithDefault", 60], + ["AssignmentTargetPropertyIdentifier", 61], + ["AssignmentTargetPropertyProperty", 62], + ["SequenceExpression", 63], + ["AwaitExpression", 64], + ["ChainExpression", 65], + ["ParenthesizedExpression", 66], + ["BlockStatement", 67], + ["VariableDeclaration", 68], + ["VariableDeclarator", 69], + ["ExpressionStatement", 70], + ["IfStatement", 71], + ["DoWhileStatement", 72], + ["WhileStatement", 73], + ["ForStatement", 74], + ["ForInStatement", 75], + ["ForOfStatement", 76], + ["ContinueStatement", 77], + ["BreakStatement", 78], + ["ReturnStatement", 79], + ["WithStatement", 80], + ["SwitchStatement", 81], + ["SwitchCase", 82], + ["LabeledStatement", 83], + ["ThrowStatement", 84], + ["TryStatement", 85], + ["CatchClause", 86], + ["AssignmentPattern", 87], + ["ObjectPattern", 88], + ["BindingProperty", 89], + ["ArrayPattern", 90], + ["Function", 91], + ["FormalParameters", 92], + ["FunctionBody", 93], + ["ArrowFunctionExpression", 94], + ["YieldExpression", 95], + ["Class", 96], + ["ClassBody", 97], + ["MethodDefinition", 98], + ["PropertyDefinition", 99], + ["StaticBlock", 100], + ["AccessorProperty", 101], + ["ImportExpression", 102], + ["ImportDeclaration", 103], + ["ImportSpecifier", 104], + ["ImportDefaultSpecifier", 105], + ["ImportNamespaceSpecifier", 106], + ["ImportAttribute", 107], + ["ExportNamedDeclaration", 108], + ["ExportDefaultDeclaration", 109], + ["ExportAllDeclaration", 110], + ["ExportSpecifier", 111], + ["V8IntrinsicExpression", 112], + ["JSXElement", 113], + ["JSXOpeningElement", 114], + ["JSXClosingElement", 115], + ["JSXFragment", 116], + ["JSXNamespacedName", 117], + ["JSXMemberExpression", 118], + ["JSXExpressionContainer", 119], + ["JSXAttribute", 120], + ["JSXSpreadAttribute", 121], + ["JSXSpreadChild", 122], + ["TSEnumDeclaration", 123], + ["TSEnumBody", 124], + ["TSEnumMember", 125], + ["TSTypeAnnotation", 126], + ["TSLiteralType", 127], + ["TSConditionalType", 128], + ["TSUnionType", 129], + ["TSIntersectionType", 130], + ["TSParenthesizedType", 131], + ["TSTypeOperator", 132], + ["TSArrayType", 133], + ["TSIndexedAccessType", 134], + ["TSTupleType", 135], + ["TSNamedTupleMember", 136], + ["TSOptionalType", 137], + ["TSRestType", 138], + ["TSTypeReference", 139], + ["TSQualifiedName", 140], + ["TSTypeParameterInstantiation", 141], + ["TSTypeParameter", 142], + ["TSTypeParameterDeclaration", 143], + ["TSTypeAliasDeclaration", 144], + ["TSClassImplements", 145], + ["TSInterfaceDeclaration", 146], + ["TSInterfaceBody", 147], + ["TSPropertySignature", 148], + ["TSIndexSignature", 149], + ["TSCallSignatureDeclaration", 150], + ["TSMethodSignature", 151], + ["TSConstructSignatureDeclaration", 152], + ["TSIndexSignatureName", 153], + ["TSInterfaceHeritage", 154], + ["TSTypePredicate", 155], + ["TSModuleDeclaration", 156], + ["TSGlobalDeclaration", 157], + ["TSModuleBlock", 158], + ["TSTypeLiteral", 159], + ["TSInferType", 160], + ["TSTypeQuery", 161], + ["TSImportType", 162], + ["TSImportTypeQualifiedName", 163], + ["TSFunctionType", 164], + ["TSConstructorType", 165], + ["TSMappedType", 166], + ["TSTemplateLiteralType", 167], + ["TSAsExpression", 168], + ["TSSatisfiesExpression", 169], + ["TSTypeAssertion", 170], + ["TSImportEqualsDeclaration", 171], + ["TSExternalModuleReference", 172], + ["TSNonNullExpression", 173], + ["Decorator", 174], + ["TSExportAssignment", 175], + ["TSNamespaceExportDeclaration", 176], + ["TSInstantiationExpression", 177], + ["JSDocNullableType", 178], + ["JSDocNonNullableType", 179], +]); + +export const NODE_TYPES_COUNT = 180; +export const LEAF_NODE_TYPES_COUNT = 38; diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/walk.js b/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/walk.js new file mode 100644 index 0000000000000000000000000000000000000000..a624261269950e58f71f1361cde7c40bde009cab --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/lazy/walk.js @@ -0,0 +1,5802 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/raw_transfer_lazy.rs`. + +import { + Program, + IdentifierName, + IdentifierReference, + BindingIdentifier, + LabelIdentifier, + ThisExpression, + ArrayExpression, + Elision, + ObjectExpression, + ObjectProperty, + TemplateLiteral, + TaggedTemplateExpression, + TemplateElement, + ComputedMemberExpression, + StaticMemberExpression, + PrivateFieldExpression, + CallExpression, + NewExpression, + MetaProperty, + SpreadElement, + UpdateExpression, + UnaryExpression, + BinaryExpression, + PrivateInExpression, + LogicalExpression, + ConditionalExpression, + AssignmentExpression, + ArrayAssignmentTarget, + ObjectAssignmentTarget, + AssignmentTargetWithDefault, + AssignmentTargetPropertyIdentifier, + AssignmentTargetPropertyProperty, + SequenceExpression, + Super, + AwaitExpression, + ChainExpression, + ParenthesizedExpression, + Hashbang, + BlockStatement, + VariableDeclaration, + VariableDeclarator, + EmptyStatement, + ExpressionStatement, + IfStatement, + DoWhileStatement, + WhileStatement, + ForStatement, + ForInStatement, + ForOfStatement, + ContinueStatement, + BreakStatement, + ReturnStatement, + WithStatement, + SwitchStatement, + SwitchCase, + LabeledStatement, + ThrowStatement, + TryStatement, + CatchClause, + DebuggerStatement, + AssignmentPattern, + ObjectPattern, + BindingProperty, + ArrayPattern, + Function, + FormalParameters, + FunctionBody, + ArrowFunctionExpression, + YieldExpression, + Class, + ClassBody, + MethodDefinition, + PropertyDefinition, + PrivateIdentifier, + StaticBlock, + AccessorProperty, + ImportExpression, + ImportDeclaration, + ImportSpecifier, + ImportDefaultSpecifier, + ImportNamespaceSpecifier, + ImportAttribute, + ExportNamedDeclaration, + ExportDefaultDeclaration, + ExportAllDeclaration, + ExportSpecifier, + V8IntrinsicExpression, + BooleanLiteral, + NullLiteral, + NumericLiteral, + StringLiteral, + BigIntLiteral, + RegExpLiteral, + JSXElement, + JSXOpeningElement, + JSXClosingElement, + JSXFragment, + JSXOpeningFragment, + JSXClosingFragment, + JSXNamespacedName, + JSXMemberExpression, + JSXExpressionContainer, + JSXEmptyExpression, + JSXAttribute, + JSXSpreadAttribute, + JSXIdentifier, + JSXSpreadChild, + JSXText, + TSEnumDeclaration, + TSEnumBody, + TSEnumMember, + TSTypeAnnotation, + TSLiteralType, + TSConditionalType, + TSUnionType, + TSIntersectionType, + TSParenthesizedType, + TSTypeOperator, + TSArrayType, + TSIndexedAccessType, + TSTupleType, + TSNamedTupleMember, + TSOptionalType, + TSRestType, + TSAnyKeyword, + TSStringKeyword, + TSBooleanKeyword, + TSNumberKeyword, + TSNeverKeyword, + TSIntrinsicKeyword, + TSUnknownKeyword, + TSNullKeyword, + TSUndefinedKeyword, + TSVoidKeyword, + TSSymbolKeyword, + TSThisType, + TSObjectKeyword, + TSBigIntKeyword, + TSTypeReference, + TSQualifiedName, + TSTypeParameterInstantiation, + TSTypeParameter, + TSTypeParameterDeclaration, + TSTypeAliasDeclaration, + TSClassImplements, + TSInterfaceDeclaration, + TSInterfaceBody, + TSPropertySignature, + TSIndexSignature, + TSCallSignatureDeclaration, + TSMethodSignature, + TSConstructSignatureDeclaration, + TSIndexSignatureName, + TSInterfaceHeritage, + TSTypePredicate, + TSModuleDeclaration, + TSGlobalDeclaration, + TSModuleBlock, + TSTypeLiteral, + TSInferType, + TSTypeQuery, + TSImportType, + TSImportTypeQualifiedName, + TSFunctionType, + TSConstructorType, + TSMappedType, + TSTemplateLiteralType, + TSAsExpression, + TSSatisfiesExpression, + TSTypeAssertion, + TSImportEqualsDeclaration, + TSExternalModuleReference, + TSNonNullExpression, + Decorator, + TSExportAssignment, + TSNamespaceExportDeclaration, + TSInstantiationExpression, + JSDocNullableType, + JSDocNonNullableType, + JSDocUnknownType, +} from "./constructors.js"; + +export { walkProgram }; + +function walkProgram(pos, ast, visitors) { + const enterExit = visitors[38]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new Program(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionHashbang(pos + 56, ast, visitors); + walkVecStatement(pos + 112, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkExpression(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Expression`); + } +} + +function walkIdentifierName(pos, ast, visitors) { + const visit = visitors[0]; + if (visit !== null) visit(new IdentifierName(pos, ast)); +} + +function walkIdentifierReference(pos, ast, visitors) { + const visit = visitors[1]; + if (visit !== null) visit(new IdentifierReference(pos, ast)); +} + +function walkBindingIdentifier(pos, ast, visitors) { + const visit = visitors[2]; + if (visit !== null) visit(new BindingIdentifier(pos, ast)); +} + +function walkLabelIdentifier(pos, ast, visitors) { + const visit = visitors[3]; + if (visit !== null) visit(new LabelIdentifier(pos, ast)); +} + +function walkThisExpression(pos, ast, visitors) { + const visit = visitors[4]; + if (visit !== null) visit(new ThisExpression(pos, ast)); +} + +function walkArrayExpression(pos, ast, visitors) { + const enterExit = visitors[39]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ArrayExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkVecArrayExpressionElement(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkArrayExpressionElement(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + case 64: + walkBoxSpreadElement(pos + 8, ast, visitors); + return; + case 65: + walkElision(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ArrayExpressionElement`); + } +} + +function walkElision(pos, ast, visitors) { + const visit = visitors[5]; + if (visit !== null) visit(new Elision(pos, ast)); +} + +function walkObjectExpression(pos, ast, visitors) { + const enterExit = visitors[40]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ObjectExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkVecObjectPropertyKind(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkObjectPropertyKind(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxObjectProperty(pos + 8, ast, visitors); + return; + case 1: + walkBoxSpreadElement(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ObjectPropertyKind`); + } +} + +function walkObjectProperty(pos, ast, visitors) { + const enterExit = visitors[41]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ObjectProperty(pos, ast); + if (enter !== null) enter(node); + } + + walkPropertyKey(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkPropertyKey(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + case 64: + walkBoxIdentifierName(pos + 8, ast, visitors); + return; + case 65: + walkBoxPrivateIdentifier(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for PropertyKey`); + } +} + +function walkTemplateLiteral(pos, ast, visitors) { + const enterExit = visitors[42]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TemplateLiteral(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTemplateElement(pos + 16, ast, visitors); + walkVecExpression(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTaggedTemplateExpression(pos, ast, visitors) { + const enterExit = visitors[43]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TaggedTemplateExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + walkTemplateLiteral(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTemplateElement(pos, ast, visitors) { + const visit = visitors[6]; + if (visit !== null) visit(new TemplateElement(pos, ast)); +} + +function walkComputedMemberExpression(pos, ast, visitors) { + const enterExit = visitors[44]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ComputedMemberExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkStaticMemberExpression(pos, ast, visitors) { + const enterExit = visitors[45]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new StaticMemberExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkIdentifierName(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkPrivateFieldExpression(pos, ast, visitors) { + const enterExit = visitors[46]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new PrivateFieldExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkPrivateIdentifier(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkCallExpression(pos, ast, visitors) { + const enterExit = visitors[47]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new CallExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + walkVecArgument(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkNewExpression(pos, ast, visitors) { + const enterExit = visitors[48]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new NewExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + walkVecArgument(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkMetaProperty(pos, ast, visitors) { + const enterExit = visitors[49]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new MetaProperty(pos, ast); + if (enter !== null) enter(node); + } + + walkIdentifierName(pos + 16, ast, visitors); + walkIdentifierName(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkSpreadElement(pos, ast, visitors) { + const enterExit = visitors[50]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new SpreadElement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkArgument(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + case 64: + walkBoxSpreadElement(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Argument`); + } +} + +function walkUpdateExpression(pos, ast, visitors) { + const enterExit = visitors[51]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new UpdateExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkSimpleAssignmentTarget(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkUnaryExpression(pos, ast, visitors) { + const enterExit = visitors[52]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new UnaryExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkBinaryExpression(pos, ast, visitors) { + const enterExit = visitors[53]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new BinaryExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkPrivateInExpression(pos, ast, visitors) { + const enterExit = visitors[54]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new PrivateInExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkPrivateIdentifier(pos + 16, ast, visitors); + walkExpression(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkLogicalExpression(pos, ast, visitors) { + const enterExit = visitors[55]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new LogicalExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkConditionalExpression(pos, ast, visitors) { + const enterExit = visitors[56]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ConditionalExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + walkExpression(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkAssignmentExpression(pos, ast, visitors) { + const enterExit = visitors[57]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AssignmentExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkAssignmentTarget(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkAssignmentTarget(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 8: + walkBoxArrayAssignmentTarget(pos + 8, ast, visitors); + return; + case 9: + walkBoxObjectAssignmentTarget(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AssignmentTarget`); + } +} + +function walkSimpleAssignmentTarget(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for SimpleAssignmentTarget`); + } +} + +function walkArrayAssignmentTarget(pos, ast, visitors) { + const enterExit = visitors[58]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ArrayAssignmentTarget(pos, ast); + if (enter !== null) enter(node); + } + + walkVecOptionAssignmentTargetMaybeDefault(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkObjectAssignmentTarget(pos, ast, visitors) { + const enterExit = visitors[59]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ObjectAssignmentTarget(pos, ast); + if (enter !== null) enter(node); + } + + walkVecAssignmentTargetProperty(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkAssignmentTargetMaybeDefault(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 8: + walkBoxArrayAssignmentTarget(pos + 8, ast, visitors); + return; + case 9: + walkBoxObjectAssignmentTarget(pos + 8, ast, visitors); + return; + case 16: + walkBoxAssignmentTargetWithDefault(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + default: + throw new Error( + `Unexpected discriminant ${ast.buffer[pos]} for AssignmentTargetMaybeDefault`, + ); + } +} + +function walkAssignmentTargetWithDefault(pos, ast, visitors) { + const enterExit = visitors[60]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AssignmentTargetWithDefault(pos, ast); + if (enter !== null) enter(node); + } + + walkAssignmentTarget(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkAssignmentTargetProperty(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxAssignmentTargetPropertyIdentifier(pos + 8, ast, visitors); + return; + case 1: + walkBoxAssignmentTargetPropertyProperty(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for AssignmentTargetProperty`); + } +} + +function walkAssignmentTargetPropertyIdentifier(pos, ast, visitors) { + const enterExit = visitors[61]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AssignmentTargetPropertyIdentifier(pos, ast); + if (enter !== null) enter(node); + } + + walkIdentifierReference(pos + 16, ast, visitors); + walkOptionExpression(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkAssignmentTargetPropertyProperty(pos, ast, visitors) { + const enterExit = visitors[62]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AssignmentTargetPropertyProperty(pos, ast); + if (enter !== null) enter(node); + } + + walkPropertyKey(pos + 16, ast, visitors); + walkAssignmentTargetMaybeDefault(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkSequenceExpression(pos, ast, visitors) { + const enterExit = visitors[63]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new SequenceExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkVecExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkSuper(pos, ast, visitors) { + const visit = visitors[7]; + if (visit !== null) visit(new Super(pos, ast)); +} + +function walkAwaitExpression(pos, ast, visitors) { + const enterExit = visitors[64]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AwaitExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkChainExpression(pos, ast, visitors) { + const enterExit = visitors[65]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ChainExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkChainElement(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkChainElement(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ChainElement`); + } +} + +function walkParenthesizedExpression(pos, ast, visitors) { + const enterExit = visitors[66]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ParenthesizedExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkStatement(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBlockStatement(pos + 8, ast, visitors); + return; + case 1: + walkBoxBreakStatement(pos + 8, ast, visitors); + return; + case 2: + walkBoxContinueStatement(pos + 8, ast, visitors); + return; + case 3: + walkBoxDebuggerStatement(pos + 8, ast, visitors); + return; + case 4: + walkBoxDoWhileStatement(pos + 8, ast, visitors); + return; + case 5: + walkBoxEmptyStatement(pos + 8, ast, visitors); + return; + case 6: + walkBoxExpressionStatement(pos + 8, ast, visitors); + return; + case 7: + walkBoxForInStatement(pos + 8, ast, visitors); + return; + case 8: + walkBoxForOfStatement(pos + 8, ast, visitors); + return; + case 9: + walkBoxForStatement(pos + 8, ast, visitors); + return; + case 10: + walkBoxIfStatement(pos + 8, ast, visitors); + return; + case 11: + walkBoxLabeledStatement(pos + 8, ast, visitors); + return; + case 12: + walkBoxReturnStatement(pos + 8, ast, visitors); + return; + case 13: + walkBoxSwitchStatement(pos + 8, ast, visitors); + return; + case 14: + walkBoxThrowStatement(pos + 8, ast, visitors); + return; + case 15: + walkBoxTryStatement(pos + 8, ast, visitors); + return; + case 16: + walkBoxWhileStatement(pos + 8, ast, visitors); + return; + case 17: + walkBoxWithStatement(pos + 8, ast, visitors); + return; + case 32: + walkBoxVariableDeclaration(pos + 8, ast, visitors); + return; + case 33: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 34: + walkBoxClass(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSTypeAliasDeclaration(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSInterfaceDeclaration(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSEnumDeclaration(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSModuleDeclaration(pos + 8, ast, visitors); + return; + case 39: + walkBoxTSGlobalDeclaration(pos + 8, ast, visitors); + return; + case 40: + walkBoxTSImportEqualsDeclaration(pos + 8, ast, visitors); + return; + case 64: + walkBoxImportDeclaration(pos + 8, ast, visitors); + return; + case 65: + walkBoxExportAllDeclaration(pos + 8, ast, visitors); + return; + case 66: + walkBoxExportDefaultDeclaration(pos + 8, ast, visitors); + return; + case 67: + walkBoxExportNamedDeclaration(pos + 8, ast, visitors); + return; + case 68: + walkBoxTSExportAssignment(pos + 8, ast, visitors); + return; + case 69: + walkBoxTSNamespaceExportDeclaration(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Statement`); + } +} + +function walkHashbang(pos, ast, visitors) { + const visit = visitors[8]; + if (visit !== null) visit(new Hashbang(pos, ast)); +} + +function walkBlockStatement(pos, ast, visitors) { + const enterExit = visitors[67]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new BlockStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkVecStatement(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkDeclaration(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 32: + walkBoxVariableDeclaration(pos + 8, ast, visitors); + return; + case 33: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 34: + walkBoxClass(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSTypeAliasDeclaration(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSInterfaceDeclaration(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSEnumDeclaration(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSModuleDeclaration(pos + 8, ast, visitors); + return; + case 39: + walkBoxTSGlobalDeclaration(pos + 8, ast, visitors); + return; + case 40: + walkBoxTSImportEqualsDeclaration(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for Declaration`); + } +} + +function walkVariableDeclaration(pos, ast, visitors) { + const enterExit = visitors[68]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new VariableDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkVecVariableDeclarator(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkVariableDeclarator(pos, ast, visitors) { + const enterExit = visitors[69]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new VariableDeclarator(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingPattern(pos + 16, ast, visitors); + walkOptionExpression(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkEmptyStatement(pos, ast, visitors) { + const visit = visitors[9]; + if (visit !== null) visit(new EmptyStatement(pos, ast)); +} + +function walkExpressionStatement(pos, ast, visitors) { + const enterExit = visitors[70]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ExpressionStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkIfStatement(pos, ast, visitors) { + const enterExit = visitors[71]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new IfStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkStatement(pos + 32, ast, visitors); + walkOptionStatement(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkDoWhileStatement(pos, ast, visitors) { + const enterExit = visitors[72]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new DoWhileStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkStatement(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkWhileStatement(pos, ast, visitors) { + const enterExit = visitors[73]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new WhileStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkStatement(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkForStatement(pos, ast, visitors) { + const enterExit = visitors[74]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ForStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionForStatementInit(pos + 16, ast, visitors); + walkOptionExpression(pos + 32, ast, visitors); + walkOptionExpression(pos + 48, ast, visitors); + walkStatement(pos + 64, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkForStatementInit(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + case 64: + walkBoxVariableDeclaration(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ForStatementInit`); + } +} + +function walkForInStatement(pos, ast, visitors) { + const enterExit = visitors[75]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ForInStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkForStatementLeft(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + walkStatement(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkForStatementLeft(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 8: + walkBoxArrayAssignmentTarget(pos + 8, ast, visitors); + return; + case 9: + walkBoxObjectAssignmentTarget(pos + 8, ast, visitors); + return; + case 16: + walkBoxVariableDeclaration(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ForStatementLeft`); + } +} + +function walkForOfStatement(pos, ast, visitors) { + const enterExit = visitors[76]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ForOfStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkForStatementLeft(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + walkStatement(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkContinueStatement(pos, ast, visitors) { + const enterExit = visitors[77]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ContinueStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionLabelIdentifier(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkBreakStatement(pos, ast, visitors) { + const enterExit = visitors[78]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new BreakStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionLabelIdentifier(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkReturnStatement(pos, ast, visitors) { + const enterExit = visitors[79]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ReturnStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkWithStatement(pos, ast, visitors) { + const enterExit = visitors[80]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new WithStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkStatement(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkSwitchStatement(pos, ast, visitors) { + const enterExit = visitors[81]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new SwitchStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkVecSwitchCase(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkSwitchCase(pos, ast, visitors) { + const enterExit = visitors[82]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new SwitchCase(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionExpression(pos + 16, ast, visitors); + walkVecStatement(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkLabeledStatement(pos, ast, visitors) { + const enterExit = visitors[83]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new LabeledStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkLabelIdentifier(pos + 16, ast, visitors); + walkStatement(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkThrowStatement(pos, ast, visitors) { + const enterExit = visitors[84]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ThrowStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTryStatement(pos, ast, visitors) { + const enterExit = visitors[85]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TryStatement(pos, ast); + if (enter !== null) enter(node); + } + + walkBoxBlockStatement(pos + 16, ast, visitors); + walkOptionBoxCatchClause(pos + 24, ast, visitors); + walkOptionBoxBlockStatement(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkCatchClause(pos, ast, visitors) { + const enterExit = visitors[86]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new CatchClause(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionCatchParameter(pos + 16, ast, visitors); + walkBoxBlockStatement(pos + 56, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkCatchParameter(pos, ast, visitors) { + walkBindingPattern(pos + 16, ast, visitors); +} + +function walkDebuggerStatement(pos, ast, visitors) { + const visit = visitors[10]; + if (visit !== null) visit(new DebuggerStatement(pos, ast)); +} + +function walkBindingPattern(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBindingIdentifier(pos + 8, ast, visitors); + return; + case 1: + walkBoxObjectPattern(pos + 8, ast, visitors); + return; + case 2: + walkBoxArrayPattern(pos + 8, ast, visitors); + return; + case 3: + walkBoxAssignmentPattern(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for BindingPattern`); + } +} + +function walkAssignmentPattern(pos, ast, visitors) { + const enterExit = visitors[87]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AssignmentPattern(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingPattern(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkObjectPattern(pos, ast, visitors) { + const enterExit = visitors[88]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ObjectPattern(pos, ast); + if (enter !== null) enter(node); + } + + walkVecBindingProperty(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkBindingProperty(pos, ast, visitors) { + const enterExit = visitors[89]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new BindingProperty(pos, ast); + if (enter !== null) enter(node); + } + + walkPropertyKey(pos + 16, ast, visitors); + walkBindingPattern(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkArrayPattern(pos, ast, visitors) { + const enterExit = visitors[90]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ArrayPattern(pos, ast); + if (enter !== null) enter(node); + } + + walkVecOptionBindingPattern(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkFunction(pos, ast, visitors) { + const enterExit = visitors[91]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new Function(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionBindingIdentifier(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterDeclaration(pos + 48, ast, visitors); + walkBoxFormalParameters(pos + 64, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 72, ast, visitors); + walkOptionBoxFunctionBody(pos + 80, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkFormalParameters(pos, ast, visitors) { + const enterExit = visitors[92]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new FormalParameters(pos, ast); + if (enter !== null) enter(node); + } + + walkVecFormalParameter(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkFormalParameter(pos, ast, visitors) { + walkVecDecorator(pos + 16, ast, visitors); + walkBindingPattern(pos + 40, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 56, ast, visitors); + walkOptionBoxExpression(pos + 64, ast, visitors); +} + +function walkFunctionBody(pos, ast, visitors) { + const enterExit = visitors[93]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new FunctionBody(pos, ast); + if (enter !== null) enter(node); + } + + walkVecStatement(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkArrowFunctionExpression(pos, ast, visitors) { + const enterExit = visitors[94]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ArrowFunctionExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionBoxTSTypeParameterDeclaration(pos + 16, ast, visitors); + walkBoxFormalParameters(pos + 24, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 32, ast, visitors); + walkBoxFunctionBody(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkYieldExpression(pos, ast, visitors) { + const enterExit = visitors[95]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new YieldExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkClass(pos, ast, visitors) { + const enterExit = visitors[96]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new Class(pos, ast); + if (enter !== null) enter(node); + } + + walkVecDecorator(pos + 16, ast, visitors); + walkOptionBindingIdentifier(pos + 40, ast, visitors); + walkOptionBoxTSTypeParameterDeclaration(pos + 72, ast, visitors); + walkOptionExpression(pos + 80, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 96, ast, visitors); + walkVecTSClassImplements(pos + 104, ast, visitors); + walkBoxClassBody(pos + 128, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkClassBody(pos, ast, visitors) { + const enterExit = visitors[97]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ClassBody(pos, ast); + if (enter !== null) enter(node); + } + + walkVecClassElement(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkClassElement(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxStaticBlock(pos + 8, ast, visitors); + return; + case 1: + walkBoxMethodDefinition(pos + 8, ast, visitors); + return; + case 2: + walkBoxPropertyDefinition(pos + 8, ast, visitors); + return; + case 3: + walkBoxAccessorProperty(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSIndexSignature(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ClassElement`); + } +} + +function walkMethodDefinition(pos, ast, visitors) { + const enterExit = visitors[98]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new MethodDefinition(pos, ast); + if (enter !== null) enter(node); + } + + walkVecDecorator(pos + 16, ast, visitors); + walkPropertyKey(pos + 40, ast, visitors); + walkBoxFunction(pos + 56, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkPropertyDefinition(pos, ast, visitors) { + const enterExit = visitors[99]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new PropertyDefinition(pos, ast); + if (enter !== null) enter(node); + } + + walkVecDecorator(pos + 16, ast, visitors); + walkPropertyKey(pos + 40, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 56, ast, visitors); + walkOptionExpression(pos + 64, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkPrivateIdentifier(pos, ast, visitors) { + const visit = visitors[11]; + if (visit !== null) visit(new PrivateIdentifier(pos, ast)); +} + +function walkStaticBlock(pos, ast, visitors) { + const enterExit = visitors[100]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new StaticBlock(pos, ast); + if (enter !== null) enter(node); + } + + walkVecStatement(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkAccessorProperty(pos, ast, visitors) { + const enterExit = visitors[101]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new AccessorProperty(pos, ast); + if (enter !== null) enter(node); + } + + walkVecDecorator(pos + 16, ast, visitors); + walkPropertyKey(pos + 40, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 56, ast, visitors); + walkOptionExpression(pos + 64, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkImportExpression(pos, ast, visitors) { + const enterExit = visitors[102]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ImportExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkOptionExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkImportDeclaration(pos, ast, visitors) { + const enterExit = visitors[103]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ImportDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionVecImportDeclarationSpecifier(pos + 16, ast, visitors); + walkStringLiteral(pos + 40, ast, visitors); + walkOptionBoxWithClause(pos + 88, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkImportDeclarationSpecifier(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxImportSpecifier(pos + 8, ast, visitors); + return; + case 1: + walkBoxImportDefaultSpecifier(pos + 8, ast, visitors); + return; + case 2: + walkBoxImportNamespaceSpecifier(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportDeclarationSpecifier`); + } +} + +function walkImportSpecifier(pos, ast, visitors) { + const enterExit = visitors[104]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ImportSpecifier(pos, ast); + if (enter !== null) enter(node); + } + + walkModuleExportName(pos + 16, ast, visitors); + walkBindingIdentifier(pos + 72, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkImportDefaultSpecifier(pos, ast, visitors) { + const enterExit = visitors[105]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ImportDefaultSpecifier(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkImportNamespaceSpecifier(pos, ast, visitors) { + const enterExit = visitors[106]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ImportNamespaceSpecifier(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkWithClause(pos, ast, visitors) { + walkVecImportAttribute(pos + 16, ast, visitors); +} + +function walkImportAttribute(pos, ast, visitors) { + const enterExit = visitors[107]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ImportAttribute(pos, ast); + if (enter !== null) enter(node); + } + + walkImportAttributeKey(pos + 16, ast, visitors); + walkStringLiteral(pos + 72, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkImportAttributeKey(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkIdentifierName(pos + 8, ast, visitors); + return; + case 1: + walkStringLiteral(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ImportAttributeKey`); + } +} + +function walkExportNamedDeclaration(pos, ast, visitors) { + const enterExit = visitors[108]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ExportNamedDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionDeclaration(pos + 16, ast, visitors); + walkVecExportSpecifier(pos + 32, ast, visitors); + walkOptionStringLiteral(pos + 56, ast, visitors); + walkOptionBoxWithClause(pos + 104, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkExportDefaultDeclaration(pos, ast, visitors) { + const enterExit = visitors[109]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ExportDefaultDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkExportDefaultDeclarationKind(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkExportAllDeclaration(pos, ast, visitors) { + const enterExit = visitors[110]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ExportAllDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionModuleExportName(pos + 16, ast, visitors); + walkStringLiteral(pos + 72, ast, visitors); + walkOptionBoxWithClause(pos + 120, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkExportSpecifier(pos, ast, visitors) { + const enterExit = visitors[111]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new ExportSpecifier(pos, ast); + if (enter !== null) enter(node); + } + + walkModuleExportName(pos + 16, ast, visitors); + walkModuleExportName(pos + 72, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkExportDefaultDeclarationKind(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + case 64: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 65: + walkBoxClass(pos + 8, ast, visitors); + return; + case 66: + walkBoxTSInterfaceDeclaration(pos + 8, ast, visitors); + return; + default: + throw new Error( + `Unexpected discriminant ${ast.buffer[pos]} for ExportDefaultDeclarationKind`, + ); + } +} + +function walkModuleExportName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkIdentifierName(pos + 8, ast, visitors); + return; + case 1: + walkIdentifierReference(pos + 8, ast, visitors); + return; + case 2: + walkStringLiteral(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for ModuleExportName`); + } +} + +function walkV8IntrinsicExpression(pos, ast, visitors) { + const enterExit = visitors[112]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new V8IntrinsicExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkIdentifierName(pos + 16, ast, visitors); + walkVecArgument(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkBooleanLiteral(pos, ast, visitors) { + const visit = visitors[12]; + if (visit !== null) visit(new BooleanLiteral(pos, ast)); +} + +function walkNullLiteral(pos, ast, visitors) { + const visit = visitors[13]; + if (visit !== null) visit(new NullLiteral(pos, ast)); +} + +function walkNumericLiteral(pos, ast, visitors) { + const visit = visitors[14]; + if (visit !== null) visit(new NumericLiteral(pos, ast)); +} + +function walkStringLiteral(pos, ast, visitors) { + const visit = visitors[15]; + if (visit !== null) visit(new StringLiteral(pos, ast)); +} + +function walkBigIntLiteral(pos, ast, visitors) { + const visit = visitors[16]; + if (visit !== null) visit(new BigIntLiteral(pos, ast)); +} + +function walkRegExpLiteral(pos, ast, visitors) { + const visit = visitors[17]; + if (visit !== null) visit(new RegExpLiteral(pos, ast)); +} + +function walkJSXElement(pos, ast, visitors) { + const enterExit = visitors[113]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXElement(pos, ast); + if (enter !== null) enter(node); + } + + walkBoxJSXOpeningElement(pos + 16, ast, visitors); + walkVecJSXChild(pos + 24, ast, visitors); + walkOptionBoxJSXClosingElement(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXOpeningElement(pos, ast, visitors) { + const enterExit = visitors[114]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXOpeningElement(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXElementName(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + walkVecJSXAttributeItem(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXClosingElement(pos, ast, visitors) { + const enterExit = visitors[115]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXClosingElement(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXElementName(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXFragment(pos, ast, visitors) { + const enterExit = visitors[116]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXFragment(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXOpeningFragment(pos + 16, ast, visitors); + walkVecJSXChild(pos + 32, ast, visitors); + walkJSXClosingFragment(pos + 56, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXOpeningFragment(pos, ast, visitors) { + const visit = visitors[18]; + if (visit !== null) visit(new JSXOpeningFragment(pos, ast)); +} + +function walkJSXClosingFragment(pos, ast, visitors) { + const visit = visitors[19]; + if (visit !== null) visit(new JSXClosingFragment(pos, ast)); +} + +function walkJSXElementName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxJSXIdentifier(pos + 8, ast, visitors); + return; + case 1: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 2: + walkBoxJSXNamespacedName(pos + 8, ast, visitors); + return; + case 3: + walkBoxJSXMemberExpression(pos + 8, ast, visitors); + return; + case 4: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXElementName`); + } +} + +function walkJSXNamespacedName(pos, ast, visitors) { + const enterExit = visitors[117]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXNamespacedName(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXIdentifier(pos + 16, ast, visitors); + walkJSXIdentifier(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXMemberExpression(pos, ast, visitors) { + const enterExit = visitors[118]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXMemberExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXMemberExpressionObject(pos + 16, ast, visitors); + walkJSXIdentifier(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXMemberExpressionObject(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxJSXMemberExpression(pos + 8, ast, visitors); + return; + case 2: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXMemberExpressionObject`); + } +} + +function walkJSXExpressionContainer(pos, ast, visitors) { + const enterExit = visitors[119]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXExpressionContainer(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXExpression(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNullLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxRegExpLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 6: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 7: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 8: + walkBoxMetaProperty(pos + 8, ast, visitors); + return; + case 9: + walkBoxSuper(pos + 8, ast, visitors); + return; + case 10: + walkBoxArrayExpression(pos + 8, ast, visitors); + return; + case 11: + walkBoxArrowFunctionExpression(pos + 8, ast, visitors); + return; + case 12: + walkBoxAssignmentExpression(pos + 8, ast, visitors); + return; + case 13: + walkBoxAwaitExpression(pos + 8, ast, visitors); + return; + case 14: + walkBoxBinaryExpression(pos + 8, ast, visitors); + return; + case 15: + walkBoxCallExpression(pos + 8, ast, visitors); + return; + case 16: + walkBoxChainExpression(pos + 8, ast, visitors); + return; + case 17: + walkBoxClass(pos + 8, ast, visitors); + return; + case 18: + walkBoxConditionalExpression(pos + 8, ast, visitors); + return; + case 19: + walkBoxFunction(pos + 8, ast, visitors); + return; + case 20: + walkBoxImportExpression(pos + 8, ast, visitors); + return; + case 21: + walkBoxLogicalExpression(pos + 8, ast, visitors); + return; + case 22: + walkBoxNewExpression(pos + 8, ast, visitors); + return; + case 23: + walkBoxObjectExpression(pos + 8, ast, visitors); + return; + case 24: + walkBoxParenthesizedExpression(pos + 8, ast, visitors); + return; + case 25: + walkBoxSequenceExpression(pos + 8, ast, visitors); + return; + case 26: + walkBoxTaggedTemplateExpression(pos + 8, ast, visitors); + return; + case 27: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 28: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + case 29: + walkBoxUpdateExpression(pos + 8, ast, visitors); + return; + case 30: + walkBoxYieldExpression(pos + 8, ast, visitors); + return; + case 31: + walkBoxPrivateInExpression(pos + 8, ast, visitors); + return; + case 32: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 33: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSAsExpression(pos + 8, ast, visitors); + return; + case 35: + walkBoxTSSatisfiesExpression(pos + 8, ast, visitors); + return; + case 36: + walkBoxTSTypeAssertion(pos + 8, ast, visitors); + return; + case 37: + walkBoxTSNonNullExpression(pos + 8, ast, visitors); + return; + case 38: + walkBoxTSInstantiationExpression(pos + 8, ast, visitors); + return; + case 39: + walkBoxV8IntrinsicExpression(pos + 8, ast, visitors); + return; + case 48: + walkBoxComputedMemberExpression(pos + 8, ast, visitors); + return; + case 49: + walkBoxStaticMemberExpression(pos + 8, ast, visitors); + return; + case 50: + walkBoxPrivateFieldExpression(pos + 8, ast, visitors); + return; + case 64: + walkJSXEmptyExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXExpression`); + } +} + +function walkJSXEmptyExpression(pos, ast, visitors) { + const visit = visitors[20]; + if (visit !== null) visit(new JSXEmptyExpression(pos, ast)); +} + +function walkJSXAttributeItem(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxJSXAttribute(pos + 8, ast, visitors); + return; + case 1: + walkBoxJSXSpreadAttribute(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXAttributeItem`); + } +} + +function walkJSXAttribute(pos, ast, visitors) { + const enterExit = visitors[120]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXAttribute(pos, ast); + if (enter !== null) enter(node); + } + + walkJSXAttributeName(pos + 16, ast, visitors); + walkOptionJSXAttributeValue(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXSpreadAttribute(pos, ast, visitors) { + const enterExit = visitors[121]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXSpreadAttribute(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXAttributeName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxJSXIdentifier(pos + 8, ast, visitors); + return; + case 1: + walkBoxJSXNamespacedName(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXAttributeName`); + } +} + +function walkJSXAttributeValue(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxJSXExpressionContainer(pos + 8, ast, visitors); + return; + case 2: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 3: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXAttributeValue`); + } +} + +function walkJSXIdentifier(pos, ast, visitors) { + const visit = visitors[21]; + if (visit !== null) visit(new JSXIdentifier(pos, ast)); +} + +function walkJSXChild(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxJSXText(pos + 8, ast, visitors); + return; + case 1: + walkBoxJSXElement(pos + 8, ast, visitors); + return; + case 2: + walkBoxJSXFragment(pos + 8, ast, visitors); + return; + case 3: + walkBoxJSXExpressionContainer(pos + 8, ast, visitors); + return; + case 4: + walkBoxJSXSpreadChild(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for JSXChild`); + } +} + +function walkJSXSpreadChild(pos, ast, visitors) { + const enterExit = visitors[122]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSXSpreadChild(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSXText(pos, ast, visitors) { + const visit = visitors[22]; + if (visit !== null) visit(new JSXText(pos, ast)); +} + +function walkTSEnumDeclaration(pos, ast, visitors) { + const enterExit = visitors[123]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSEnumDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + walkTSEnumBody(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSEnumBody(pos, ast, visitors) { + const enterExit = visitors[124]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSEnumBody(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSEnumMember(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSEnumMember(pos, ast, visitors) { + const enterExit = visitors[125]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSEnumMember(pos, ast); + if (enter !== null) enter(node); + } + + walkTSEnumMemberName(pos + 16, ast, visitors); + walkOptionExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSEnumMemberName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierName(pos + 8, ast, visitors); + return; + case 1: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSEnumMemberName`); + } +} + +function walkTSTypeAnnotation(pos, ast, visitors) { + const enterExit = visitors[126]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeAnnotation(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSLiteralType(pos, ast, visitors) { + const enterExit = visitors[127]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSLiteralType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSLiteral(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSLiteral(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxBooleanLiteral(pos + 8, ast, visitors); + return; + case 1: + walkBoxNumericLiteral(pos + 8, ast, visitors); + return; + case 2: + walkBoxBigIntLiteral(pos + 8, ast, visitors); + return; + case 3: + walkBoxStringLiteral(pos + 8, ast, visitors); + return; + case 4: + walkBoxTemplateLiteral(pos + 8, ast, visitors); + return; + case 5: + walkBoxUnaryExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSLiteral`); + } +} + +function walkTSType(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxTSAnyKeyword(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSBigIntKeyword(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSBooleanKeyword(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSIntrinsicKeyword(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSNeverKeyword(pos + 8, ast, visitors); + return; + case 5: + walkBoxTSNullKeyword(pos + 8, ast, visitors); + return; + case 6: + walkBoxTSNumberKeyword(pos + 8, ast, visitors); + return; + case 7: + walkBoxTSObjectKeyword(pos + 8, ast, visitors); + return; + case 8: + walkBoxTSStringKeyword(pos + 8, ast, visitors); + return; + case 9: + walkBoxTSSymbolKeyword(pos + 8, ast, visitors); + return; + case 10: + walkBoxTSThisType(pos + 8, ast, visitors); + return; + case 11: + walkBoxTSUndefinedKeyword(pos + 8, ast, visitors); + return; + case 12: + walkBoxTSUnknownKeyword(pos + 8, ast, visitors); + return; + case 13: + walkBoxTSVoidKeyword(pos + 8, ast, visitors); + return; + case 14: + walkBoxTSArrayType(pos + 8, ast, visitors); + return; + case 15: + walkBoxTSConditionalType(pos + 8, ast, visitors); + return; + case 16: + walkBoxTSConstructorType(pos + 8, ast, visitors); + return; + case 17: + walkBoxTSFunctionType(pos + 8, ast, visitors); + return; + case 18: + walkBoxTSImportType(pos + 8, ast, visitors); + return; + case 19: + walkBoxTSIndexedAccessType(pos + 8, ast, visitors); + return; + case 20: + walkBoxTSInferType(pos + 8, ast, visitors); + return; + case 21: + walkBoxTSIntersectionType(pos + 8, ast, visitors); + return; + case 22: + walkBoxTSLiteralType(pos + 8, ast, visitors); + return; + case 23: + walkBoxTSMappedType(pos + 8, ast, visitors); + return; + case 24: + walkBoxTSNamedTupleMember(pos + 8, ast, visitors); + return; + case 26: + walkBoxTSTemplateLiteralType(pos + 8, ast, visitors); + return; + case 27: + walkBoxTSTupleType(pos + 8, ast, visitors); + return; + case 28: + walkBoxTSTypeLiteral(pos + 8, ast, visitors); + return; + case 29: + walkBoxTSTypeOperator(pos + 8, ast, visitors); + return; + case 30: + walkBoxTSTypePredicate(pos + 8, ast, visitors); + return; + case 31: + walkBoxTSTypeQuery(pos + 8, ast, visitors); + return; + case 32: + walkBoxTSTypeReference(pos + 8, ast, visitors); + return; + case 33: + walkBoxTSUnionType(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSParenthesizedType(pos + 8, ast, visitors); + return; + case 35: + walkBoxJSDocNullableType(pos + 8, ast, visitors); + return; + case 36: + walkBoxJSDocNonNullableType(pos + 8, ast, visitors); + return; + case 37: + walkBoxJSDocUnknownType(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSType`); + } +} + +function walkTSConditionalType(pos, ast, visitors) { + const enterExit = visitors[128]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSConditionalType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + walkTSType(pos + 32, ast, visitors); + walkTSType(pos + 48, ast, visitors); + walkTSType(pos + 64, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSUnionType(pos, ast, visitors) { + const enterExit = visitors[129]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSUnionType(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSIntersectionType(pos, ast, visitors) { + const enterExit = visitors[130]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSIntersectionType(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSParenthesizedType(pos, ast, visitors) { + const enterExit = visitors[131]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSParenthesizedType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeOperator(pos, ast, visitors) { + const enterExit = visitors[132]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeOperator(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSArrayType(pos, ast, visitors) { + const enterExit = visitors[133]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSArrayType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSIndexedAccessType(pos, ast, visitors) { + const enterExit = visitors[134]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSIndexedAccessType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + walkTSType(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTupleType(pos, ast, visitors) { + const enterExit = visitors[135]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTupleType(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSTupleElement(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSNamedTupleMember(pos, ast, visitors) { + const enterExit = visitors[136]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSNamedTupleMember(pos, ast); + if (enter !== null) enter(node); + } + + walkIdentifierName(pos + 16, ast, visitors); + walkTSTupleElement(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSOptionalType(pos, ast, visitors) { + const enterExit = visitors[137]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSOptionalType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSRestType(pos, ast, visitors) { + const enterExit = visitors[138]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSRestType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTupleElement(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxTSAnyKeyword(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSBigIntKeyword(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSBooleanKeyword(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSIntrinsicKeyword(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSNeverKeyword(pos + 8, ast, visitors); + return; + case 5: + walkBoxTSNullKeyword(pos + 8, ast, visitors); + return; + case 6: + walkBoxTSNumberKeyword(pos + 8, ast, visitors); + return; + case 7: + walkBoxTSObjectKeyword(pos + 8, ast, visitors); + return; + case 8: + walkBoxTSStringKeyword(pos + 8, ast, visitors); + return; + case 9: + walkBoxTSSymbolKeyword(pos + 8, ast, visitors); + return; + case 10: + walkBoxTSThisType(pos + 8, ast, visitors); + return; + case 11: + walkBoxTSUndefinedKeyword(pos + 8, ast, visitors); + return; + case 12: + walkBoxTSUnknownKeyword(pos + 8, ast, visitors); + return; + case 13: + walkBoxTSVoidKeyword(pos + 8, ast, visitors); + return; + case 14: + walkBoxTSArrayType(pos + 8, ast, visitors); + return; + case 15: + walkBoxTSConditionalType(pos + 8, ast, visitors); + return; + case 16: + walkBoxTSConstructorType(pos + 8, ast, visitors); + return; + case 17: + walkBoxTSFunctionType(pos + 8, ast, visitors); + return; + case 18: + walkBoxTSImportType(pos + 8, ast, visitors); + return; + case 19: + walkBoxTSIndexedAccessType(pos + 8, ast, visitors); + return; + case 20: + walkBoxTSInferType(pos + 8, ast, visitors); + return; + case 21: + walkBoxTSIntersectionType(pos + 8, ast, visitors); + return; + case 22: + walkBoxTSLiteralType(pos + 8, ast, visitors); + return; + case 23: + walkBoxTSMappedType(pos + 8, ast, visitors); + return; + case 24: + walkBoxTSNamedTupleMember(pos + 8, ast, visitors); + return; + case 26: + walkBoxTSTemplateLiteralType(pos + 8, ast, visitors); + return; + case 27: + walkBoxTSTupleType(pos + 8, ast, visitors); + return; + case 28: + walkBoxTSTypeLiteral(pos + 8, ast, visitors); + return; + case 29: + walkBoxTSTypeOperator(pos + 8, ast, visitors); + return; + case 30: + walkBoxTSTypePredicate(pos + 8, ast, visitors); + return; + case 31: + walkBoxTSTypeQuery(pos + 8, ast, visitors); + return; + case 32: + walkBoxTSTypeReference(pos + 8, ast, visitors); + return; + case 33: + walkBoxTSUnionType(pos + 8, ast, visitors); + return; + case 34: + walkBoxTSParenthesizedType(pos + 8, ast, visitors); + return; + case 35: + walkBoxJSDocNullableType(pos + 8, ast, visitors); + return; + case 36: + walkBoxJSDocNonNullableType(pos + 8, ast, visitors); + return; + case 37: + walkBoxJSDocUnknownType(pos + 8, ast, visitors); + return; + case 64: + walkBoxTSOptionalType(pos + 8, ast, visitors); + return; + case 65: + walkBoxTSRestType(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTupleElement`); + } +} + +function walkTSAnyKeyword(pos, ast, visitors) { + const visit = visitors[23]; + if (visit !== null) visit(new TSAnyKeyword(pos, ast)); +} + +function walkTSStringKeyword(pos, ast, visitors) { + const visit = visitors[24]; + if (visit !== null) visit(new TSStringKeyword(pos, ast)); +} + +function walkTSBooleanKeyword(pos, ast, visitors) { + const visit = visitors[25]; + if (visit !== null) visit(new TSBooleanKeyword(pos, ast)); +} + +function walkTSNumberKeyword(pos, ast, visitors) { + const visit = visitors[26]; + if (visit !== null) visit(new TSNumberKeyword(pos, ast)); +} + +function walkTSNeverKeyword(pos, ast, visitors) { + const visit = visitors[27]; + if (visit !== null) visit(new TSNeverKeyword(pos, ast)); +} + +function walkTSIntrinsicKeyword(pos, ast, visitors) { + const visit = visitors[28]; + if (visit !== null) visit(new TSIntrinsicKeyword(pos, ast)); +} + +function walkTSUnknownKeyword(pos, ast, visitors) { + const visit = visitors[29]; + if (visit !== null) visit(new TSUnknownKeyword(pos, ast)); +} + +function walkTSNullKeyword(pos, ast, visitors) { + const visit = visitors[30]; + if (visit !== null) visit(new TSNullKeyword(pos, ast)); +} + +function walkTSUndefinedKeyword(pos, ast, visitors) { + const visit = visitors[31]; + if (visit !== null) visit(new TSUndefinedKeyword(pos, ast)); +} + +function walkTSVoidKeyword(pos, ast, visitors) { + const visit = visitors[32]; + if (visit !== null) visit(new TSVoidKeyword(pos, ast)); +} + +function walkTSSymbolKeyword(pos, ast, visitors) { + const visit = visitors[33]; + if (visit !== null) visit(new TSSymbolKeyword(pos, ast)); +} + +function walkTSThisType(pos, ast, visitors) { + const visit = visitors[34]; + if (visit !== null) visit(new TSThisType(pos, ast)); +} + +function walkTSObjectKeyword(pos, ast, visitors) { + const visit = visitors[35]; + if (visit !== null) visit(new TSObjectKeyword(pos, ast)); +} + +function walkTSBigIntKeyword(pos, ast, visitors) { + const visit = visitors[36]; + if (visit !== null) visit(new TSBigIntKeyword(pos, ast)); +} + +function walkTSTypeReference(pos, ast, visitors) { + const enterExit = visitors[139]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeReference(pos, ast); + if (enter !== null) enter(node); + } + + walkTSTypeName(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSQualifiedName(pos + 8, ast, visitors); + return; + case 2: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypeName`); + } +} + +function walkTSQualifiedName(pos, ast, visitors) { + const enterExit = visitors[140]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSQualifiedName(pos, ast); + if (enter !== null) enter(node); + } + + walkTSTypeName(pos + 16, ast, visitors); + walkIdentifierName(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeParameterInstantiation(pos, ast, visitors) { + const enterExit = visitors[141]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeParameterInstantiation(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeParameter(pos, ast, visitors) { + const enterExit = visitors[142]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeParameter(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + walkOptionTSType(pos + 48, ast, visitors); + walkOptionTSType(pos + 64, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeParameterDeclaration(pos, ast, visitors) { + const enterExit = visitors[143]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeParameterDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSTypeParameter(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeAliasDeclaration(pos, ast, visitors) { + const enterExit = visitors[144]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeAliasDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterDeclaration(pos + 48, ast, visitors); + walkTSType(pos + 56, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSClassImplements(pos, ast, visitors) { + const enterExit = visitors[145]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSClassImplements(pos, ast); + if (enter !== null) enter(node); + } + + walkTSTypeName(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSInterfaceDeclaration(pos, ast, visitors) { + const enterExit = visitors[146]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSInterfaceDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterDeclaration(pos + 48, ast, visitors); + walkVecTSInterfaceHeritage(pos + 56, ast, visitors); + walkBoxTSInterfaceBody(pos + 80, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSInterfaceBody(pos, ast, visitors) { + const enterExit = visitors[147]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSInterfaceBody(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSSignature(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSPropertySignature(pos, ast, visitors) { + const enterExit = visitors[148]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSPropertySignature(pos, ast); + if (enter !== null) enter(node); + } + + walkPropertyKey(pos + 16, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSSignature(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxTSIndexSignature(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSPropertySignature(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSCallSignatureDeclaration(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSConstructSignatureDeclaration(pos + 8, ast, visitors); + return; + case 4: + walkBoxTSMethodSignature(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSSignature`); + } +} + +function walkTSIndexSignature(pos, ast, visitors) { + const enterExit = visitors[149]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSIndexSignature(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSIndexSignatureName(pos + 16, ast, visitors); + walkBoxTSTypeAnnotation(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSCallSignatureDeclaration(pos, ast, visitors) { + const enterExit = visitors[150]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSCallSignatureDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionBoxTSTypeParameterDeclaration(pos + 16, ast, visitors); + walkBoxFormalParameters(pos + 32, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSMethodSignature(pos, ast, visitors) { + const enterExit = visitors[151]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSMethodSignature(pos, ast); + if (enter !== null) enter(node); + } + + walkPropertyKey(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterDeclaration(pos + 32, ast, visitors); + walkBoxFormalParameters(pos + 48, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 56, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSConstructSignatureDeclaration(pos, ast, visitors) { + const enterExit = visitors[152]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSConstructSignatureDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionBoxTSTypeParameterDeclaration(pos + 16, ast, visitors); + walkBoxFormalParameters(pos + 24, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSIndexSignatureName(pos, ast, visitors) { + const enterExit = visitors[153]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSIndexSignatureName(pos, ast); + if (enter !== null) enter(node); + } + + walkBoxTSTypeAnnotation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSInterfaceHeritage(pos, ast, visitors) { + const enterExit = visitors[154]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSInterfaceHeritage(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypePredicate(pos, ast, visitors) { + const enterExit = visitors[155]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypePredicate(pos, ast); + if (enter !== null) enter(node); + } + + walkTSTypePredicateName(pos + 16, ast, visitors); + walkOptionBoxTSTypeAnnotation(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypePredicateName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierName(pos + 8, ast, visitors); + return; + case 1: + walkTSThisType(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypePredicateName`); + } +} + +function walkTSModuleDeclaration(pos, ast, visitors) { + const enterExit = visitors[156]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSModuleDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkTSModuleDeclarationName(pos + 16, ast, visitors); + walkOptionTSModuleDeclarationBody(pos + 72, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSModuleDeclarationName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBindingIdentifier(pos + 8, ast, visitors); + return; + case 1: + walkStringLiteral(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleDeclarationName`); + } +} + +function walkTSModuleDeclarationBody(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxTSModuleDeclaration(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSModuleBlock(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleDeclarationBody`); + } +} + +function walkTSGlobalDeclaration(pos, ast, visitors) { + const enterExit = visitors[157]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSGlobalDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkTSModuleBlock(pos + 24, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSModuleBlock(pos, ast, visitors) { + const enterExit = visitors[158]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSModuleBlock(pos, ast); + if (enter !== null) enter(node); + } + + walkVecStatement(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeLiteral(pos, ast, visitors) { + const enterExit = visitors[159]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeLiteral(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTSSignature(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSInferType(pos, ast, visitors) { + const enterExit = visitors[160]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSInferType(pos, ast); + if (enter !== null) enter(node); + } + + walkBoxTSTypeParameter(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeQuery(pos, ast, visitors) { + const enterExit = visitors[161]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeQuery(pos, ast); + if (enter !== null) enter(node); + } + + walkTSTypeQueryExprName(pos + 16, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeQueryExprName(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSQualifiedName(pos + 8, ast, visitors); + return; + case 2: + walkBoxThisExpression(pos + 8, ast, visitors); + return; + case 3: + walkBoxTSImportType(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSTypeQueryExprName`); + } +} + +function walkTSImportType(pos, ast, visitors) { + const enterExit = visitors[162]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSImportType(pos, ast); + if (enter !== null) enter(node); + } + + walkStringLiteral(pos + 16, ast, visitors); + walkOptionBoxObjectExpression(pos + 64, ast, visitors); + walkOptionTSImportTypeQualifier(pos + 72, ast, visitors); + walkOptionBoxTSTypeParameterInstantiation(pos + 88, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSImportTypeQualifier(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxIdentifierName(pos + 8, ast, visitors); + return; + case 1: + walkBoxTSImportTypeQualifiedName(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSImportTypeQualifier`); + } +} + +function walkTSImportTypeQualifiedName(pos, ast, visitors) { + const enterExit = visitors[163]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSImportTypeQualifiedName(pos, ast); + if (enter !== null) enter(node); + } + + walkTSImportTypeQualifier(pos + 16, ast, visitors); + walkIdentifierName(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSFunctionType(pos, ast, visitors) { + const enterExit = visitors[164]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSFunctionType(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionBoxTSTypeParameterDeclaration(pos + 16, ast, visitors); + walkBoxFormalParameters(pos + 32, ast, visitors); + walkBoxTSTypeAnnotation(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSConstructorType(pos, ast, visitors) { + const enterExit = visitors[165]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSConstructorType(pos, ast); + if (enter !== null) enter(node); + } + + walkOptionBoxTSTypeParameterDeclaration(pos + 16, ast, visitors); + walkBoxFormalParameters(pos + 24, ast, visitors); + walkBoxTSTypeAnnotation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSMappedType(pos, ast, visitors) { + const enterExit = visitors[166]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSMappedType(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + walkTSType(pos + 48, ast, visitors); + walkOptionTSType(pos + 64, ast, visitors); + walkOptionTSType(pos + 80, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTemplateLiteralType(pos, ast, visitors) { + const enterExit = visitors[167]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTemplateLiteralType(pos, ast); + if (enter !== null) enter(node); + } + + walkVecTemplateElement(pos + 16, ast, visitors); + walkVecTSType(pos + 40, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSAsExpression(pos, ast, visitors) { + const enterExit = visitors[168]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSAsExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkTSType(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSSatisfiesExpression(pos, ast, visitors) { + const enterExit = visitors[169]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSSatisfiesExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkTSType(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSTypeAssertion(pos, ast, visitors) { + const enterExit = visitors[170]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSTypeAssertion(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + walkExpression(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSImportEqualsDeclaration(pos, ast, visitors) { + const enterExit = visitors[171]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSImportEqualsDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkBindingIdentifier(pos + 16, ast, visitors); + walkTSModuleReference(pos + 48, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSModuleReference(pos, ast, visitors) { + switch (ast.buffer[pos]) { + case 0: + walkBoxTSExternalModuleReference(pos + 8, ast, visitors); + return; + case 1: + walkBoxIdentifierReference(pos + 8, ast, visitors); + return; + case 2: + walkBoxTSQualifiedName(pos + 8, ast, visitors); + return; + default: + throw new Error(`Unexpected discriminant ${ast.buffer[pos]} for TSModuleReference`); + } +} + +function walkTSExternalModuleReference(pos, ast, visitors) { + const enterExit = visitors[172]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSExternalModuleReference(pos, ast); + if (enter !== null) enter(node); + } + + walkStringLiteral(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSNonNullExpression(pos, ast, visitors) { + const enterExit = visitors[173]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSNonNullExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkDecorator(pos, ast, visitors) { + const enterExit = visitors[174]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new Decorator(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSExportAssignment(pos, ast, visitors) { + const enterExit = visitors[175]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSExportAssignment(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSNamespaceExportDeclaration(pos, ast, visitors) { + const enterExit = visitors[176]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSNamespaceExportDeclaration(pos, ast); + if (enter !== null) enter(node); + } + + walkIdentifierName(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkTSInstantiationExpression(pos, ast, visitors) { + const enterExit = visitors[177]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new TSInstantiationExpression(pos, ast); + if (enter !== null) enter(node); + } + + walkExpression(pos + 16, ast, visitors); + walkBoxTSTypeParameterInstantiation(pos + 32, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSDocNullableType(pos, ast, visitors) { + const enterExit = visitors[178]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSDocNullableType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSDocNonNullableType(pos, ast, visitors) { + const enterExit = visitors[179]; + let node, + enter, + exit = null; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + node = new JSDocNonNullableType(pos, ast); + if (enter !== null) enter(node); + } + + walkTSType(pos + 16, ast, visitors); + + if (exit !== null) exit(node); +} + +function walkJSDocUnknownType(pos, ast, visitors) { + const visit = visitors[37]; + if (visit !== null) visit(new JSDocUnknownType(pos, ast)); +} + +function walkOptionHashbang(pos, ast, visitors) { + if (!(ast.buffer.int32[(pos >> 2) + 4] === 0 && ast.buffer.int32[(pos >> 2) + 5] === 0)) + walkHashbang(pos, ast, visitors); +} + +function walkVecStatement(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkStatement(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxBooleanLiteral(pos, ast, visitors) { + return walkBooleanLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxNullLiteral(pos, ast, visitors) { + return walkNullLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxNumericLiteral(pos, ast, visitors) { + return walkNumericLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxBigIntLiteral(pos, ast, visitors) { + return walkBigIntLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxRegExpLiteral(pos, ast, visitors) { + return walkRegExpLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxStringLiteral(pos, ast, visitors) { + return walkStringLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTemplateLiteral(pos, ast, visitors) { + return walkTemplateLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxIdentifierReference(pos, ast, visitors) { + return walkIdentifierReference(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxMetaProperty(pos, ast, visitors) { + return walkMetaProperty(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxSuper(pos, ast, visitors) { + return walkSuper(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxArrayExpression(pos, ast, visitors) { + return walkArrayExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxArrowFunctionExpression(pos, ast, visitors) { + return walkArrowFunctionExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxAssignmentExpression(pos, ast, visitors) { + return walkAssignmentExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxAwaitExpression(pos, ast, visitors) { + return walkAwaitExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxBinaryExpression(pos, ast, visitors) { + return walkBinaryExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxCallExpression(pos, ast, visitors) { + return walkCallExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxChainExpression(pos, ast, visitors) { + return walkChainExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxClass(pos, ast, visitors) { + return walkClass(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxConditionalExpression(pos, ast, visitors) { + return walkConditionalExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxFunction(pos, ast, visitors) { + return walkFunction(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxImportExpression(pos, ast, visitors) { + return walkImportExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxLogicalExpression(pos, ast, visitors) { + return walkLogicalExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxNewExpression(pos, ast, visitors) { + return walkNewExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxObjectExpression(pos, ast, visitors) { + return walkObjectExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxParenthesizedExpression(pos, ast, visitors) { + return walkParenthesizedExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxSequenceExpression(pos, ast, visitors) { + return walkSequenceExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTaggedTemplateExpression(pos, ast, visitors) { + return walkTaggedTemplateExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxThisExpression(pos, ast, visitors) { + return walkThisExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxUnaryExpression(pos, ast, visitors) { + return walkUnaryExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxUpdateExpression(pos, ast, visitors) { + return walkUpdateExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxYieldExpression(pos, ast, visitors) { + return walkYieldExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxPrivateInExpression(pos, ast, visitors) { + return walkPrivateInExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXElement(pos, ast, visitors) { + return walkJSXElement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXFragment(pos, ast, visitors) { + return walkJSXFragment(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSAsExpression(pos, ast, visitors) { + return walkTSAsExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSSatisfiesExpression(pos, ast, visitors) { + return walkTSSatisfiesExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeAssertion(pos, ast, visitors) { + return walkTSTypeAssertion(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSNonNullExpression(pos, ast, visitors) { + return walkTSNonNullExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSInstantiationExpression(pos, ast, visitors) { + return walkTSInstantiationExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxV8IntrinsicExpression(pos, ast, visitors) { + return walkV8IntrinsicExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecArrayExpressionElement(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 24; + while (pos < endPos) { + walkArrayExpressionElement(pos, ast, visitors); + pos += 24; + } +} + +function walkBoxSpreadElement(pos, ast, visitors) { + return walkSpreadElement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecObjectPropertyKind(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkObjectPropertyKind(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxObjectProperty(pos, ast, visitors) { + return walkObjectProperty(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxIdentifierName(pos, ast, visitors) { + return walkIdentifierName(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxPrivateIdentifier(pos, ast, visitors) { + return walkPrivateIdentifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecTemplateElement(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 48; + while (pos < endPos) { + walkTemplateElement(pos, ast, visitors); + pos += 48; + } +} + +function walkVecExpression(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkExpression(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxTSTypeParameterInstantiation(pos, ast, visitors) { + return walkTSTypeParameterInstantiation(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxTSTypeParameterInstantiation(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxTSTypeParameterInstantiation(pos, ast, visitors); +} + +function walkBoxComputedMemberExpression(pos, ast, visitors) { + return walkComputedMemberExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxStaticMemberExpression(pos, ast, visitors) { + return walkStaticMemberExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxPrivateFieldExpression(pos, ast, visitors) { + return walkPrivateFieldExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecArgument(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkArgument(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxArrayAssignmentTarget(pos, ast, visitors) { + return walkArrayAssignmentTarget(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxObjectAssignmentTarget(pos, ast, visitors) { + return walkObjectAssignmentTarget(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionAssignmentTargetMaybeDefault(pos, ast, visitors) { + if (!(ast.buffer[pos] === 51)) walkAssignmentTargetMaybeDefault(pos, ast, visitors); +} + +function walkVecOptionAssignmentTargetMaybeDefault(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkOptionAssignmentTargetMaybeDefault(pos, ast, visitors); + pos += 16; + } +} + +function walkVecAssignmentTargetProperty(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkAssignmentTargetProperty(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxAssignmentTargetWithDefault(pos, ast, visitors) { + return walkAssignmentTargetWithDefault(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxAssignmentTargetPropertyIdentifier(pos, ast, visitors) { + return walkAssignmentTargetPropertyIdentifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxAssignmentTargetPropertyProperty(pos, ast, visitors) { + return walkAssignmentTargetPropertyProperty(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionExpression(pos, ast, visitors) { + if (!(ast.buffer[pos] === 51)) walkExpression(pos, ast, visitors); +} + +function walkBoxBlockStatement(pos, ast, visitors) { + return walkBlockStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxBreakStatement(pos, ast, visitors) { + return walkBreakStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxContinueStatement(pos, ast, visitors) { + return walkContinueStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxDebuggerStatement(pos, ast, visitors) { + return walkDebuggerStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxDoWhileStatement(pos, ast, visitors) { + return walkDoWhileStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxEmptyStatement(pos, ast, visitors) { + return walkEmptyStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxExpressionStatement(pos, ast, visitors) { + return walkExpressionStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxForInStatement(pos, ast, visitors) { + return walkForInStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxForOfStatement(pos, ast, visitors) { + return walkForOfStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxForStatement(pos, ast, visitors) { + return walkForStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxIfStatement(pos, ast, visitors) { + return walkIfStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxLabeledStatement(pos, ast, visitors) { + return walkLabeledStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxReturnStatement(pos, ast, visitors) { + return walkReturnStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxSwitchStatement(pos, ast, visitors) { + return walkSwitchStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxThrowStatement(pos, ast, visitors) { + return walkThrowStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTryStatement(pos, ast, visitors) { + return walkTryStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxWhileStatement(pos, ast, visitors) { + return walkWhileStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxWithStatement(pos, ast, visitors) { + return walkWithStatement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxVariableDeclaration(pos, ast, visitors) { + return walkVariableDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeAliasDeclaration(pos, ast, visitors) { + return walkTSTypeAliasDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSInterfaceDeclaration(pos, ast, visitors) { + return walkTSInterfaceDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSEnumDeclaration(pos, ast, visitors) { + return walkTSEnumDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSModuleDeclaration(pos, ast, visitors) { + return walkTSModuleDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSGlobalDeclaration(pos, ast, visitors) { + return walkTSGlobalDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSImportEqualsDeclaration(pos, ast, visitors) { + return walkTSImportEqualsDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecVariableDeclarator(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 56; + while (pos < endPos) { + walkVariableDeclarator(pos, ast, visitors); + pos += 56; + } +} + +function walkBoxTSTypeAnnotation(pos, ast, visitors) { + return walkTSTypeAnnotation(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxTSTypeAnnotation(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxTSTypeAnnotation(pos, ast, visitors); +} + +function walkOptionStatement(pos, ast, visitors) { + if (!(ast.buffer[pos] === 70)) walkStatement(pos, ast, visitors); +} + +function walkOptionForStatementInit(pos, ast, visitors) { + if (!(ast.buffer[pos] === 65)) walkForStatementInit(pos, ast, visitors); +} + +function walkOptionLabelIdentifier(pos, ast, visitors) { + if (!(ast.buffer.int32[(pos >> 2) + 4] === 0 && ast.buffer.int32[(pos >> 2) + 5] === 0)) + walkLabelIdentifier(pos, ast, visitors); +} + +function walkVecSwitchCase(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 56; + while (pos < endPos) { + walkSwitchCase(pos, ast, visitors); + pos += 56; + } +} + +function walkBoxCatchClause(pos, ast, visitors) { + return walkCatchClause(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxCatchClause(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxCatchClause(pos, ast, visitors); +} + +function walkOptionBoxBlockStatement(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxBlockStatement(pos, ast, visitors); +} + +function walkOptionCatchParameter(pos, ast, visitors) { + if (!(ast.buffer[pos + 16] === 4)) walkCatchParameter(pos, ast, visitors); +} + +function walkBoxBindingIdentifier(pos, ast, visitors) { + return walkBindingIdentifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxObjectPattern(pos, ast, visitors) { + return walkObjectPattern(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxArrayPattern(pos, ast, visitors) { + return walkArrayPattern(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxAssignmentPattern(pos, ast, visitors) { + return walkAssignmentPattern(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecBindingProperty(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 48; + while (pos < endPos) { + walkBindingProperty(pos, ast, visitors); + pos += 48; + } +} + +function walkOptionBindingPattern(pos, ast, visitors) { + if (!(ast.buffer[pos] === 4)) walkBindingPattern(pos, ast, visitors); +} + +function walkVecOptionBindingPattern(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkOptionBindingPattern(pos, ast, visitors); + pos += 16; + } +} + +function walkOptionBindingIdentifier(pos, ast, visitors) { + if (!(ast.buffer.int32[(pos >> 2) + 4] === 0 && ast.buffer.int32[(pos >> 2) + 5] === 0)) + walkBindingIdentifier(pos, ast, visitors); +} + +function walkBoxTSTypeParameterDeclaration(pos, ast, visitors) { + return walkTSTypeParameterDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxTSTypeParameterDeclaration(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxTSTypeParameterDeclaration(pos, ast, visitors); +} + +function walkBoxFormalParameters(pos, ast, visitors) { + return walkFormalParameters(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxFunctionBody(pos, ast, visitors) { + return walkFunctionBody(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxFunctionBody(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxFunctionBody(pos, ast, visitors); +} + +function walkVecFormalParameter(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 72; + while (pos < endPos) { + walkFormalParameter(pos, ast, visitors); + pos += 72; + } +} + +function walkVecDecorator(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 32; + while (pos < endPos) { + walkDecorator(pos, ast, visitors); + pos += 32; + } +} + +function walkBoxExpression(pos, ast, visitors) { + return walkExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxExpression(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxExpression(pos, ast, visitors); +} + +function walkVecTSClassImplements(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 40; + while (pos < endPos) { + walkTSClassImplements(pos, ast, visitors); + pos += 40; + } +} + +function walkBoxClassBody(pos, ast, visitors) { + return walkClassBody(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecClassElement(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkClassElement(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxStaticBlock(pos, ast, visitors) { + return walkStaticBlock(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxMethodDefinition(pos, ast, visitors) { + return walkMethodDefinition(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxPropertyDefinition(pos, ast, visitors) { + return walkPropertyDefinition(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxAccessorProperty(pos, ast, visitors) { + return walkAccessorProperty(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSIndexSignature(pos, ast, visitors) { + return walkTSIndexSignature(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxImportDeclaration(pos, ast, visitors) { + return walkImportDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxExportAllDeclaration(pos, ast, visitors) { + return walkExportAllDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxExportDefaultDeclaration(pos, ast, visitors) { + return walkExportDefaultDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxExportNamedDeclaration(pos, ast, visitors) { + return walkExportNamedDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSExportAssignment(pos, ast, visitors) { + return walkTSExportAssignment(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSNamespaceExportDeclaration(pos, ast, visitors) { + return walkTSNamespaceExportDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecImportDeclarationSpecifier(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkImportDeclarationSpecifier(pos, ast, visitors); + pos += 16; + } +} + +function walkOptionVecImportDeclarationSpecifier(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkVecImportDeclarationSpecifier(pos, ast, visitors); +} + +function walkBoxWithClause(pos, ast, visitors) { + return walkWithClause(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxWithClause(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxWithClause(pos, ast, visitors); +} + +function walkBoxImportSpecifier(pos, ast, visitors) { + return walkImportSpecifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxImportDefaultSpecifier(pos, ast, visitors) { + return walkImportDefaultSpecifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxImportNamespaceSpecifier(pos, ast, visitors) { + return walkImportNamespaceSpecifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecImportAttribute(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 120; + while (pos < endPos) { + walkImportAttribute(pos, ast, visitors); + pos += 120; + } +} + +function walkOptionDeclaration(pos, ast, visitors) { + if (!(ast.buffer[pos] === 31)) walkDeclaration(pos, ast, visitors); +} + +function walkVecExportSpecifier(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 128; + while (pos < endPos) { + walkExportSpecifier(pos, ast, visitors); + pos += 128; + } +} + +function walkOptionStringLiteral(pos, ast, visitors) { + if (!(ast.buffer[pos + 12] === 2)) walkStringLiteral(pos, ast, visitors); +} + +function walkOptionModuleExportName(pos, ast, visitors) { + if (!(ast.buffer[pos] === 3)) walkModuleExportName(pos, ast, visitors); +} + +function walkBoxJSXOpeningElement(pos, ast, visitors) { + return walkJSXOpeningElement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecJSXChild(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkJSXChild(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxJSXClosingElement(pos, ast, visitors) { + return walkJSXClosingElement(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxJSXClosingElement(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxJSXClosingElement(pos, ast, visitors); +} + +function walkVecJSXAttributeItem(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkJSXAttributeItem(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxJSXIdentifier(pos, ast, visitors) { + return walkJSXIdentifier(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXNamespacedName(pos, ast, visitors) { + return walkJSXNamespacedName(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXMemberExpression(pos, ast, visitors) { + return walkJSXMemberExpression(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXAttribute(pos, ast, visitors) { + return walkJSXAttribute(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXSpreadAttribute(pos, ast, visitors) { + return walkJSXSpreadAttribute(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionJSXAttributeValue(pos, ast, visitors) { + if (!(ast.buffer[pos] === 4)) walkJSXAttributeValue(pos, ast, visitors); +} + +function walkBoxJSXExpressionContainer(pos, ast, visitors) { + return walkJSXExpressionContainer(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXText(pos, ast, visitors) { + return walkJSXText(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSXSpreadChild(pos, ast, visitors) { + return walkJSXSpreadChild(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecTSEnumMember(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 48; + while (pos < endPos) { + walkTSEnumMember(pos, ast, visitors); + pos += 48; + } +} + +function walkBoxTSAnyKeyword(pos, ast, visitors) { + return walkTSAnyKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSBigIntKeyword(pos, ast, visitors) { + return walkTSBigIntKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSBooleanKeyword(pos, ast, visitors) { + return walkTSBooleanKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSIntrinsicKeyword(pos, ast, visitors) { + return walkTSIntrinsicKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSNeverKeyword(pos, ast, visitors) { + return walkTSNeverKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSNullKeyword(pos, ast, visitors) { + return walkTSNullKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSNumberKeyword(pos, ast, visitors) { + return walkTSNumberKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSObjectKeyword(pos, ast, visitors) { + return walkTSObjectKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSStringKeyword(pos, ast, visitors) { + return walkTSStringKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSSymbolKeyword(pos, ast, visitors) { + return walkTSSymbolKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSUndefinedKeyword(pos, ast, visitors) { + return walkTSUndefinedKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSUnknownKeyword(pos, ast, visitors) { + return walkTSUnknownKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSVoidKeyword(pos, ast, visitors) { + return walkTSVoidKeyword(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSArrayType(pos, ast, visitors) { + return walkTSArrayType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSConditionalType(pos, ast, visitors) { + return walkTSConditionalType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSConstructorType(pos, ast, visitors) { + return walkTSConstructorType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSFunctionType(pos, ast, visitors) { + return walkTSFunctionType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSImportType(pos, ast, visitors) { + return walkTSImportType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSIndexedAccessType(pos, ast, visitors) { + return walkTSIndexedAccessType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSInferType(pos, ast, visitors) { + return walkTSInferType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSIntersectionType(pos, ast, visitors) { + return walkTSIntersectionType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSLiteralType(pos, ast, visitors) { + return walkTSLiteralType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSMappedType(pos, ast, visitors) { + return walkTSMappedType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSNamedTupleMember(pos, ast, visitors) { + return walkTSNamedTupleMember(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTemplateLiteralType(pos, ast, visitors) { + return walkTSTemplateLiteralType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSThisType(pos, ast, visitors) { + return walkTSThisType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTupleType(pos, ast, visitors) { + return walkTSTupleType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeLiteral(pos, ast, visitors) { + return walkTSTypeLiteral(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeOperator(pos, ast, visitors) { + return walkTSTypeOperator(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypePredicate(pos, ast, visitors) { + return walkTSTypePredicate(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeQuery(pos, ast, visitors) { + return walkTSTypeQuery(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeReference(pos, ast, visitors) { + return walkTSTypeReference(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSUnionType(pos, ast, visitors) { + return walkTSUnionType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSParenthesizedType(pos, ast, visitors) { + return walkTSParenthesizedType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSDocNullableType(pos, ast, visitors) { + return walkJSDocNullableType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSDocNonNullableType(pos, ast, visitors) { + return walkJSDocNonNullableType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxJSDocUnknownType(pos, ast, visitors) { + return walkJSDocUnknownType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecTSType(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkTSType(pos, ast, visitors); + pos += 16; + } +} + +function walkVecTSTupleElement(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkTSTupleElement(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxTSOptionalType(pos, ast, visitors) { + return walkTSOptionalType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSRestType(pos, ast, visitors) { + return walkTSRestType(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSQualifiedName(pos, ast, visitors) { + return walkTSQualifiedName(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionTSType(pos, ast, visitors) { + if (!(ast.buffer[pos] === 38)) walkTSType(pos, ast, visitors); +} + +function walkVecTSTypeParameter(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 80; + while (pos < endPos) { + walkTSTypeParameter(pos, ast, visitors); + pos += 80; + } +} + +function walkVecTSInterfaceHeritage(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 40; + while (pos < endPos) { + walkTSInterfaceHeritage(pos, ast, visitors); + pos += 40; + } +} + +function walkBoxTSInterfaceBody(pos, ast, visitors) { + return walkTSInterfaceBody(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecTSSignature(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 16; + while (pos < endPos) { + walkTSSignature(pos, ast, visitors); + pos += 16; + } +} + +function walkBoxTSPropertySignature(pos, ast, visitors) { + return walkTSPropertySignature(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSCallSignatureDeclaration(pos, ast, visitors) { + return walkTSCallSignatureDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSConstructSignatureDeclaration(pos, ast, visitors) { + return walkTSConstructSignatureDeclaration(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSMethodSignature(pos, ast, visitors) { + return walkTSMethodSignature(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkVecTSIndexSignatureName(pos, ast, visitors) { + const { int32 } = ast.buffer, + pos32 = pos >> 2; + pos = int32[pos32]; + const endPos = pos + int32[pos32 + 2] * 40; + while (pos < endPos) { + walkTSIndexSignatureName(pos, ast, visitors); + pos += 40; + } +} + +function walkOptionTSModuleDeclarationBody(pos, ast, visitors) { + if (!(ast.buffer[pos] === 2)) walkTSModuleDeclarationBody(pos, ast, visitors); +} + +function walkBoxTSModuleBlock(pos, ast, visitors) { + return walkTSModuleBlock(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSTypeParameter(pos, ast, visitors) { + return walkTSTypeParameter(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkOptionBoxObjectExpression(pos, ast, visitors) { + if (!(ast.buffer.int32[pos >> 2] === 0 && ast.buffer.int32[(pos >> 2) + 1] === 0)) + walkBoxObjectExpression(pos, ast, visitors); +} + +function walkOptionTSImportTypeQualifier(pos, ast, visitors) { + if (!(ast.buffer[pos] === 2)) walkTSImportTypeQualifier(pos, ast, visitors); +} + +function walkBoxTSImportTypeQualifiedName(pos, ast, visitors) { + return walkTSImportTypeQualifiedName(ast.buffer.int32[pos >> 2], ast, visitors); +} + +function walkBoxTSExternalModuleReference(pos, ast, visitors) { + return walkTSExternalModuleReference(ast.buffer.int32[pos >> 2], ast, visitors); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/visit/keys.js b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/keys.js new file mode 100644 index 0000000000000000000000000000000000000000..8c9d47af976904fec662b77c3357ffa374636be9 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/keys.js @@ -0,0 +1,220 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/estree_visit.rs`. + +const { freeze } = Object; + +const $EMPTY = freeze([]), + DECORATORS__KEY__TYPE_ANNOTATION__VALUE = freeze([ + "decorators", + "key", + "typeAnnotation", + "value", + ]), + LEFT__RIGHT = freeze(["left", "right"]), + ARGUMENT = freeze(["argument"]), + BODY = freeze(["body"]), + LABEL = freeze(["label"]), + CALLEE__TYPE_ARGUMENTS__ARGUMENTS = freeze(["callee", "typeArguments", "arguments"]), + EXPRESSION = freeze(["expression"]), + DECORATORS__ID__TYPE_PARAMETERS__SUPER_CLASS__SUPER_TYPE_ARGUMENTS__IMPLEMENTS__BODY = freeze([ + "decorators", + "id", + "typeParameters", + "superClass", + "superTypeArguments", + "implements", + "body", + ]), + TEST__CONSEQUENT__ALTERNATE = freeze(["test", "consequent", "alternate"]), + LEFT__RIGHT__BODY = freeze(["left", "right", "body"]), + ID__TYPE_PARAMETERS__PARAMS__RETURN_TYPE__BODY = freeze([ + "id", + "typeParameters", + "params", + "returnType", + "body", + ]), + KEY__VALUE = freeze(["key", "value"]), + LOCAL = freeze(["local"]), + OBJECT__PROPERTY = freeze(["object", "property"]), + DECORATORS__KEY__TYPE_ANNOTATION = freeze(["decorators", "key", "typeAnnotation"]), + EXPRESSION__TYPE_ANNOTATION = freeze(["expression", "typeAnnotation"]), + TYPE_PARAMETERS__PARAMS__RETURN_TYPE = freeze(["typeParameters", "params", "returnType"]), + EXPRESSION__TYPE_ARGUMENTS = freeze(["expression", "typeArguments"]), + MEMBERS = freeze(["members"]), + ID__BODY = freeze(["id", "body"]), + TYPES = freeze(["types"]), + TYPE_ANNOTATION = freeze(["typeAnnotation"]), + PARAMS = freeze(["params"]); + +export default freeze({ + // Leaf nodes + DebuggerStatement: $EMPTY, + EmptyStatement: $EMPTY, + Literal: $EMPTY, + PrivateIdentifier: $EMPTY, + Super: $EMPTY, + TemplateElement: $EMPTY, + ThisExpression: $EMPTY, + JSXClosingFragment: $EMPTY, + JSXEmptyExpression: $EMPTY, + JSXIdentifier: $EMPTY, + JSXOpeningFragment: $EMPTY, + JSXText: $EMPTY, + TSAnyKeyword: $EMPTY, + TSBigIntKeyword: $EMPTY, + TSBooleanKeyword: $EMPTY, + TSIntrinsicKeyword: $EMPTY, + TSJSDocUnknownType: $EMPTY, + TSNeverKeyword: $EMPTY, + TSNullKeyword: $EMPTY, + TSNumberKeyword: $EMPTY, + TSObjectKeyword: $EMPTY, + TSStringKeyword: $EMPTY, + TSSymbolKeyword: $EMPTY, + TSThisType: $EMPTY, + TSUndefinedKeyword: $EMPTY, + TSUnknownKeyword: $EMPTY, + TSVoidKeyword: $EMPTY, + // Non-leaf nodes + AccessorProperty: DECORATORS__KEY__TYPE_ANNOTATION__VALUE, + ArrayExpression: freeze(["elements"]), + ArrayPattern: freeze(["decorators", "elements", "typeAnnotation"]), + ArrowFunctionExpression: freeze(["typeParameters", "params", "returnType", "body"]), + AssignmentExpression: LEFT__RIGHT, + AssignmentPattern: freeze(["decorators", "left", "right", "typeAnnotation"]), + AwaitExpression: ARGUMENT, + BinaryExpression: LEFT__RIGHT, + BlockStatement: BODY, + BreakStatement: LABEL, + CallExpression: CALLEE__TYPE_ARGUMENTS__ARGUMENTS, + CatchClause: freeze(["param", "body"]), + ChainExpression: EXPRESSION, + ClassBody: BODY, + ClassDeclaration: + DECORATORS__ID__TYPE_PARAMETERS__SUPER_CLASS__SUPER_TYPE_ARGUMENTS__IMPLEMENTS__BODY, + ClassExpression: + DECORATORS__ID__TYPE_PARAMETERS__SUPER_CLASS__SUPER_TYPE_ARGUMENTS__IMPLEMENTS__BODY, + ConditionalExpression: TEST__CONSEQUENT__ALTERNATE, + ContinueStatement: LABEL, + Decorator: EXPRESSION, + DoWhileStatement: freeze(["body", "test"]), + ExportAllDeclaration: freeze(["exported", "source", "attributes"]), + ExportDefaultDeclaration: freeze(["declaration"]), + ExportNamedDeclaration: freeze(["declaration", "specifiers", "source", "attributes"]), + ExportSpecifier: freeze(["local", "exported"]), + ExpressionStatement: EXPRESSION, + ForInStatement: LEFT__RIGHT__BODY, + ForOfStatement: LEFT__RIGHT__BODY, + ForStatement: freeze(["init", "test", "update", "body"]), + FunctionDeclaration: ID__TYPE_PARAMETERS__PARAMS__RETURN_TYPE__BODY, + FunctionExpression: ID__TYPE_PARAMETERS__PARAMS__RETURN_TYPE__BODY, + Identifier: freeze(["decorators", "typeAnnotation"]), + IfStatement: TEST__CONSEQUENT__ALTERNATE, + ImportAttribute: KEY__VALUE, + ImportDeclaration: freeze(["specifiers", "source", "attributes"]), + ImportDefaultSpecifier: LOCAL, + ImportExpression: freeze(["source", "options"]), + ImportNamespaceSpecifier: LOCAL, + ImportSpecifier: freeze(["imported", "local"]), + LabeledStatement: freeze(["label", "body"]), + LogicalExpression: LEFT__RIGHT, + MemberExpression: OBJECT__PROPERTY, + MetaProperty: freeze(["meta", "property"]), + MethodDefinition: freeze(["decorators", "key", "value"]), + NewExpression: CALLEE__TYPE_ARGUMENTS__ARGUMENTS, + ObjectExpression: freeze(["properties"]), + ObjectPattern: freeze(["decorators", "properties", "typeAnnotation"]), + ParenthesizedExpression: EXPRESSION, + Program: BODY, + Property: KEY__VALUE, + PropertyDefinition: DECORATORS__KEY__TYPE_ANNOTATION__VALUE, + RestElement: freeze(["decorators", "argument", "typeAnnotation"]), + ReturnStatement: ARGUMENT, + SequenceExpression: freeze(["expressions"]), + SpreadElement: ARGUMENT, + StaticBlock: BODY, + SwitchCase: freeze(["test", "consequent"]), + SwitchStatement: freeze(["discriminant", "cases"]), + TaggedTemplateExpression: freeze(["tag", "typeArguments", "quasi"]), + TemplateLiteral: freeze(["quasis", "expressions"]), + ThrowStatement: ARGUMENT, + TryStatement: freeze(["block", "handler", "finalizer"]), + UnaryExpression: ARGUMENT, + UpdateExpression: ARGUMENT, + V8IntrinsicExpression: freeze(["name", "arguments"]), + VariableDeclaration: freeze(["declarations"]), + VariableDeclarator: freeze(["id", "init"]), + WhileStatement: freeze(["test", "body"]), + WithStatement: freeze(["object", "body"]), + YieldExpression: ARGUMENT, + JSXAttribute: freeze(["name", "value"]), + JSXClosingElement: freeze(["name"]), + JSXElement: freeze(["openingElement", "children", "closingElement"]), + JSXExpressionContainer: EXPRESSION, + JSXFragment: freeze(["openingFragment", "children", "closingFragment"]), + JSXMemberExpression: OBJECT__PROPERTY, + JSXNamespacedName: freeze(["namespace", "name"]), + JSXOpeningElement: freeze(["name", "typeArguments", "attributes"]), + JSXSpreadAttribute: ARGUMENT, + JSXSpreadChild: EXPRESSION, + TSAbstractAccessorProperty: DECORATORS__KEY__TYPE_ANNOTATION, + TSAbstractMethodDefinition: KEY__VALUE, + TSAbstractPropertyDefinition: DECORATORS__KEY__TYPE_ANNOTATION, + TSArrayType: freeze(["elementType"]), + TSAsExpression: EXPRESSION__TYPE_ANNOTATION, + TSCallSignatureDeclaration: TYPE_PARAMETERS__PARAMS__RETURN_TYPE, + TSClassImplements: EXPRESSION__TYPE_ARGUMENTS, + TSConditionalType: freeze(["checkType", "extendsType", "trueType", "falseType"]), + TSConstructSignatureDeclaration: TYPE_PARAMETERS__PARAMS__RETURN_TYPE, + TSConstructorType: TYPE_PARAMETERS__PARAMS__RETURN_TYPE, + TSDeclareFunction: ID__TYPE_PARAMETERS__PARAMS__RETURN_TYPE__BODY, + TSEmptyBodyFunctionExpression: freeze(["id", "typeParameters", "params", "returnType"]), + TSEnumBody: MEMBERS, + TSEnumDeclaration: ID__BODY, + TSEnumMember: freeze(["id", "initializer"]), + TSExportAssignment: EXPRESSION, + TSExternalModuleReference: EXPRESSION, + TSFunctionType: TYPE_PARAMETERS__PARAMS__RETURN_TYPE, + TSImportEqualsDeclaration: freeze(["id", "moduleReference"]), + TSImportType: freeze(["source", "options", "qualifier", "typeArguments"]), + TSIndexSignature: freeze(["parameters", "typeAnnotation"]), + TSIndexedAccessType: freeze(["objectType", "indexType"]), + TSInferType: freeze(["typeParameter"]), + TSInstantiationExpression: EXPRESSION__TYPE_ARGUMENTS, + TSInterfaceBody: BODY, + TSInterfaceDeclaration: freeze(["id", "typeParameters", "extends", "body"]), + TSInterfaceHeritage: EXPRESSION__TYPE_ARGUMENTS, + TSIntersectionType: TYPES, + TSJSDocNonNullableType: TYPE_ANNOTATION, + TSJSDocNullableType: TYPE_ANNOTATION, + TSLiteralType: freeze(["literal"]), + TSMappedType: freeze(["key", "constraint", "nameType", "typeAnnotation"]), + TSMethodSignature: freeze(["key", "typeParameters", "params", "returnType"]), + TSModuleBlock: BODY, + TSModuleDeclaration: ID__BODY, + TSNamedTupleMember: freeze(["label", "elementType"]), + TSNamespaceExportDeclaration: freeze(["id"]), + TSNonNullExpression: EXPRESSION, + TSOptionalType: TYPE_ANNOTATION, + TSParameterProperty: freeze(["decorators", "parameter"]), + TSParenthesizedType: TYPE_ANNOTATION, + TSPropertySignature: freeze(["key", "typeAnnotation"]), + TSQualifiedName: LEFT__RIGHT, + TSRestType: TYPE_ANNOTATION, + TSSatisfiesExpression: EXPRESSION__TYPE_ANNOTATION, + TSTemplateLiteralType: freeze(["quasis", "types"]), + TSTupleType: freeze(["elementTypes"]), + TSTypeAliasDeclaration: freeze(["id", "typeParameters", "typeAnnotation"]), + TSTypeAnnotation: TYPE_ANNOTATION, + TSTypeAssertion: freeze(["typeAnnotation", "expression"]), + TSTypeLiteral: MEMBERS, + TSTypeOperator: TYPE_ANNOTATION, + TSTypeParameter: freeze(["name", "constraint", "default"]), + TSTypeParameterDeclaration: PARAMS, + TSTypeParameterInstantiation: PARAMS, + TSTypePredicate: freeze(["parameterName", "typeAnnotation"]), + TSTypeQuery: freeze(["exprName", "typeArguments"]), + TSTypeReference: freeze(["typeName", "typeArguments"]), + TSUnionType: TYPES, +}); diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/visit/type_ids.js b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/type_ids.js new file mode 100644 index 0000000000000000000000000000000000000000..d7e0791ba5004d57df5aaf59fa19ca338fafd595 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/type_ids.js @@ -0,0 +1,177 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/estree_visit.rs`. + +/** Mapping from node type name to node type ID */ +export const NODE_TYPE_IDS_MAP = new Map([ + ["DebuggerStatement", 0], + ["EmptyStatement", 1], + ["Literal", 2], + ["PrivateIdentifier", 3], + ["Super", 4], + ["TemplateElement", 5], + ["ThisExpression", 6], + ["JSXClosingFragment", 7], + ["JSXEmptyExpression", 8], + ["JSXIdentifier", 9], + ["JSXOpeningFragment", 10], + ["JSXText", 11], + ["TSAnyKeyword", 12], + ["TSBigIntKeyword", 13], + ["TSBooleanKeyword", 14], + ["TSIntrinsicKeyword", 15], + ["TSJSDocUnknownType", 16], + ["TSNeverKeyword", 17], + ["TSNullKeyword", 18], + ["TSNumberKeyword", 19], + ["TSObjectKeyword", 20], + ["TSStringKeyword", 21], + ["TSSymbolKeyword", 22], + ["TSThisType", 23], + ["TSUndefinedKeyword", 24], + ["TSUnknownKeyword", 25], + ["TSVoidKeyword", 26], + ["AccessorProperty", 27], + ["ArrayExpression", 28], + ["ArrayPattern", 29], + ["ArrowFunctionExpression", 30], + ["AssignmentExpression", 31], + ["AssignmentPattern", 32], + ["AwaitExpression", 33], + ["BinaryExpression", 34], + ["BlockStatement", 35], + ["BreakStatement", 36], + ["CallExpression", 37], + ["CatchClause", 38], + ["ChainExpression", 39], + ["ClassBody", 40], + ["ClassDeclaration", 41], + ["ClassExpression", 42], + ["ConditionalExpression", 43], + ["ContinueStatement", 44], + ["Decorator", 45], + ["DoWhileStatement", 46], + ["ExportAllDeclaration", 47], + ["ExportDefaultDeclaration", 48], + ["ExportNamedDeclaration", 49], + ["ExportSpecifier", 50], + ["ExpressionStatement", 51], + ["ForInStatement", 52], + ["ForOfStatement", 53], + ["ForStatement", 54], + ["FunctionDeclaration", 55], + ["FunctionExpression", 56], + ["Identifier", 57], + ["IfStatement", 58], + ["ImportAttribute", 59], + ["ImportDeclaration", 60], + ["ImportDefaultSpecifier", 61], + ["ImportExpression", 62], + ["ImportNamespaceSpecifier", 63], + ["ImportSpecifier", 64], + ["LabeledStatement", 65], + ["LogicalExpression", 66], + ["MemberExpression", 67], + ["MetaProperty", 68], + ["MethodDefinition", 69], + ["NewExpression", 70], + ["ObjectExpression", 71], + ["ObjectPattern", 72], + ["ParenthesizedExpression", 73], + ["Program", 74], + ["Property", 75], + ["PropertyDefinition", 76], + ["RestElement", 77], + ["ReturnStatement", 78], + ["SequenceExpression", 79], + ["SpreadElement", 80], + ["StaticBlock", 81], + ["SwitchCase", 82], + ["SwitchStatement", 83], + ["TaggedTemplateExpression", 84], + ["TemplateLiteral", 85], + ["ThrowStatement", 86], + ["TryStatement", 87], + ["UnaryExpression", 88], + ["UpdateExpression", 89], + ["V8IntrinsicExpression", 90], + ["VariableDeclaration", 91], + ["VariableDeclarator", 92], + ["WhileStatement", 93], + ["WithStatement", 94], + ["YieldExpression", 95], + ["JSXAttribute", 96], + ["JSXClosingElement", 97], + ["JSXElement", 98], + ["JSXExpressionContainer", 99], + ["JSXFragment", 100], + ["JSXMemberExpression", 101], + ["JSXNamespacedName", 102], + ["JSXOpeningElement", 103], + ["JSXSpreadAttribute", 104], + ["JSXSpreadChild", 105], + ["TSAbstractAccessorProperty", 106], + ["TSAbstractMethodDefinition", 107], + ["TSAbstractPropertyDefinition", 108], + ["TSArrayType", 109], + ["TSAsExpression", 110], + ["TSCallSignatureDeclaration", 111], + ["TSClassImplements", 112], + ["TSConditionalType", 113], + ["TSConstructSignatureDeclaration", 114], + ["TSConstructorType", 115], + ["TSDeclareFunction", 116], + ["TSEmptyBodyFunctionExpression", 117], + ["TSEnumBody", 118], + ["TSEnumDeclaration", 119], + ["TSEnumMember", 120], + ["TSExportAssignment", 121], + ["TSExternalModuleReference", 122], + ["TSFunctionType", 123], + ["TSImportEqualsDeclaration", 124], + ["TSImportType", 125], + ["TSIndexSignature", 126], + ["TSIndexedAccessType", 127], + ["TSInferType", 128], + ["TSInstantiationExpression", 129], + ["TSInterfaceBody", 130], + ["TSInterfaceDeclaration", 131], + ["TSInterfaceHeritage", 132], + ["TSIntersectionType", 133], + ["TSJSDocNonNullableType", 134], + ["TSJSDocNullableType", 135], + ["TSLiteralType", 136], + ["TSMappedType", 137], + ["TSMethodSignature", 138], + ["TSModuleBlock", 139], + ["TSModuleDeclaration", 140], + ["TSNamedTupleMember", 141], + ["TSNamespaceExportDeclaration", 142], + ["TSNonNullExpression", 143], + ["TSOptionalType", 144], + ["TSParameterProperty", 145], + ["TSParenthesizedType", 146], + ["TSPropertySignature", 147], + ["TSQualifiedName", 148], + ["TSRestType", 149], + ["TSSatisfiesExpression", 150], + ["TSTemplateLiteralType", 151], + ["TSTupleType", 152], + ["TSTypeAliasDeclaration", 153], + ["TSTypeAnnotation", 154], + ["TSTypeAssertion", 155], + ["TSTypeLiteral", 156], + ["TSTypeOperator", 157], + ["TSTypeParameter", 158], + ["TSTypeParameterDeclaration", 159], + ["TSTypeParameterInstantiation", 160], + ["TSTypePredicate", 161], + ["TSTypeQuery", 162], + ["TSTypeReference", 163], + ["TSUnionType", 164], +]); + +/** Count of all node types (both leaf and non-leaf nodes) */ +export const NODE_TYPES_COUNT = 165; + +/** Count of leaf node types */ +export const LEAF_NODE_TYPES_COUNT = 27; diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/visit/visitor.d.ts b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/visitor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c870be7a4e98d9f55ef1cee11811e00633806828 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/visitor.d.ts @@ -0,0 +1,387 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/estree_visit.rs`. + +import * as ESTree from "@oxc-project/types"; + +export interface VisitorObject { + DebuggerStatement?: (node: ESTree.DebuggerStatement) => void; + "DebuggerStatement:exit"?: (node: ESTree.DebuggerStatement) => void; + EmptyStatement?: (node: ESTree.EmptyStatement) => void; + "EmptyStatement:exit"?: (node: ESTree.EmptyStatement) => void; + Literal?: ( + node: + | ESTree.BooleanLiteral + | ESTree.NullLiteral + | ESTree.NumericLiteral + | ESTree.StringLiteral + | ESTree.BigIntLiteral + | ESTree.RegExpLiteral, + ) => void; + "Literal:exit"?: ( + node: + | ESTree.BooleanLiteral + | ESTree.NullLiteral + | ESTree.NumericLiteral + | ESTree.StringLiteral + | ESTree.BigIntLiteral + | ESTree.RegExpLiteral, + ) => void; + PrivateIdentifier?: (node: ESTree.PrivateIdentifier) => void; + "PrivateIdentifier:exit"?: (node: ESTree.PrivateIdentifier) => void; + Super?: (node: ESTree.Super) => void; + "Super:exit"?: (node: ESTree.Super) => void; + TemplateElement?: (node: ESTree.TemplateElement) => void; + "TemplateElement:exit"?: (node: ESTree.TemplateElement) => void; + ThisExpression?: (node: ESTree.ThisExpression) => void; + "ThisExpression:exit"?: (node: ESTree.ThisExpression) => void; + JSXClosingFragment?: (node: ESTree.JSXClosingFragment) => void; + "JSXClosingFragment:exit"?: (node: ESTree.JSXClosingFragment) => void; + JSXEmptyExpression?: (node: ESTree.JSXEmptyExpression) => void; + "JSXEmptyExpression:exit"?: (node: ESTree.JSXEmptyExpression) => void; + JSXIdentifier?: (node: ESTree.JSXIdentifier) => void; + "JSXIdentifier:exit"?: (node: ESTree.JSXIdentifier) => void; + JSXOpeningFragment?: (node: ESTree.JSXOpeningFragment) => void; + "JSXOpeningFragment:exit"?: (node: ESTree.JSXOpeningFragment) => void; + JSXText?: (node: ESTree.JSXText) => void; + "JSXText:exit"?: (node: ESTree.JSXText) => void; + TSAnyKeyword?: (node: ESTree.TSAnyKeyword) => void; + "TSAnyKeyword:exit"?: (node: ESTree.TSAnyKeyword) => void; + TSBigIntKeyword?: (node: ESTree.TSBigIntKeyword) => void; + "TSBigIntKeyword:exit"?: (node: ESTree.TSBigIntKeyword) => void; + TSBooleanKeyword?: (node: ESTree.TSBooleanKeyword) => void; + "TSBooleanKeyword:exit"?: (node: ESTree.TSBooleanKeyword) => void; + TSIntrinsicKeyword?: (node: ESTree.TSIntrinsicKeyword) => void; + "TSIntrinsicKeyword:exit"?: (node: ESTree.TSIntrinsicKeyword) => void; + TSJSDocUnknownType?: (node: ESTree.JSDocUnknownType) => void; + "TSJSDocUnknownType:exit"?: (node: ESTree.JSDocUnknownType) => void; + TSNeverKeyword?: (node: ESTree.TSNeverKeyword) => void; + "TSNeverKeyword:exit"?: (node: ESTree.TSNeverKeyword) => void; + TSNullKeyword?: (node: ESTree.TSNullKeyword) => void; + "TSNullKeyword:exit"?: (node: ESTree.TSNullKeyword) => void; + TSNumberKeyword?: (node: ESTree.TSNumberKeyword) => void; + "TSNumberKeyword:exit"?: (node: ESTree.TSNumberKeyword) => void; + TSObjectKeyword?: (node: ESTree.TSObjectKeyword) => void; + "TSObjectKeyword:exit"?: (node: ESTree.TSObjectKeyword) => void; + TSStringKeyword?: (node: ESTree.TSStringKeyword) => void; + "TSStringKeyword:exit"?: (node: ESTree.TSStringKeyword) => void; + TSSymbolKeyword?: (node: ESTree.TSSymbolKeyword) => void; + "TSSymbolKeyword:exit"?: (node: ESTree.TSSymbolKeyword) => void; + TSThisType?: (node: ESTree.TSThisType) => void; + "TSThisType:exit"?: (node: ESTree.TSThisType) => void; + TSUndefinedKeyword?: (node: ESTree.TSUndefinedKeyword) => void; + "TSUndefinedKeyword:exit"?: (node: ESTree.TSUndefinedKeyword) => void; + TSUnknownKeyword?: (node: ESTree.TSUnknownKeyword) => void; + "TSUnknownKeyword:exit"?: (node: ESTree.TSUnknownKeyword) => void; + TSVoidKeyword?: (node: ESTree.TSVoidKeyword) => void; + "TSVoidKeyword:exit"?: (node: ESTree.TSVoidKeyword) => void; + AccessorProperty?: (node: ESTree.AccessorProperty) => void; + "AccessorProperty:exit"?: (node: ESTree.AccessorProperty) => void; + ArrayExpression?: (node: ESTree.ArrayExpression) => void; + "ArrayExpression:exit"?: (node: ESTree.ArrayExpression) => void; + ArrayPattern?: (node: ESTree.ArrayPattern) => void; + "ArrayPattern:exit"?: (node: ESTree.ArrayPattern) => void; + ArrowFunctionExpression?: (node: ESTree.ArrowFunctionExpression) => void; + "ArrowFunctionExpression:exit"?: (node: ESTree.ArrowFunctionExpression) => void; + AssignmentExpression?: (node: ESTree.AssignmentExpression) => void; + "AssignmentExpression:exit"?: (node: ESTree.AssignmentExpression) => void; + AssignmentPattern?: (node: ESTree.AssignmentPattern) => void; + "AssignmentPattern:exit"?: (node: ESTree.AssignmentPattern) => void; + AwaitExpression?: (node: ESTree.AwaitExpression) => void; + "AwaitExpression:exit"?: (node: ESTree.AwaitExpression) => void; + BinaryExpression?: (node: ESTree.BinaryExpression) => void; + "BinaryExpression:exit"?: (node: ESTree.BinaryExpression) => void; + BlockStatement?: (node: ESTree.BlockStatement) => void; + "BlockStatement:exit"?: (node: ESTree.BlockStatement) => void; + BreakStatement?: (node: ESTree.BreakStatement) => void; + "BreakStatement:exit"?: (node: ESTree.BreakStatement) => void; + CallExpression?: (node: ESTree.CallExpression) => void; + "CallExpression:exit"?: (node: ESTree.CallExpression) => void; + CatchClause?: (node: ESTree.CatchClause) => void; + "CatchClause:exit"?: (node: ESTree.CatchClause) => void; + ChainExpression?: (node: ESTree.ChainExpression) => void; + "ChainExpression:exit"?: (node: ESTree.ChainExpression) => void; + ClassBody?: (node: ESTree.ClassBody) => void; + "ClassBody:exit"?: (node: ESTree.ClassBody) => void; + ClassDeclaration?: (node: ESTree.Class) => void; + "ClassDeclaration:exit"?: (node: ESTree.Class) => void; + ClassExpression?: (node: ESTree.Class) => void; + "ClassExpression:exit"?: (node: ESTree.Class) => void; + ConditionalExpression?: (node: ESTree.ConditionalExpression) => void; + "ConditionalExpression:exit"?: (node: ESTree.ConditionalExpression) => void; + ContinueStatement?: (node: ESTree.ContinueStatement) => void; + "ContinueStatement:exit"?: (node: ESTree.ContinueStatement) => void; + Decorator?: (node: ESTree.Decorator) => void; + "Decorator:exit"?: (node: ESTree.Decorator) => void; + DoWhileStatement?: (node: ESTree.DoWhileStatement) => void; + "DoWhileStatement:exit"?: (node: ESTree.DoWhileStatement) => void; + ExportAllDeclaration?: (node: ESTree.ExportAllDeclaration) => void; + "ExportAllDeclaration:exit"?: (node: ESTree.ExportAllDeclaration) => void; + ExportDefaultDeclaration?: (node: ESTree.ExportDefaultDeclaration) => void; + "ExportDefaultDeclaration:exit"?: (node: ESTree.ExportDefaultDeclaration) => void; + ExportNamedDeclaration?: (node: ESTree.ExportNamedDeclaration) => void; + "ExportNamedDeclaration:exit"?: (node: ESTree.ExportNamedDeclaration) => void; + ExportSpecifier?: (node: ESTree.ExportSpecifier) => void; + "ExportSpecifier:exit"?: (node: ESTree.ExportSpecifier) => void; + ExpressionStatement?: (node: ESTree.ExpressionStatement) => void; + "ExpressionStatement:exit"?: (node: ESTree.ExpressionStatement) => void; + ForInStatement?: (node: ESTree.ForInStatement) => void; + "ForInStatement:exit"?: (node: ESTree.ForInStatement) => void; + ForOfStatement?: (node: ESTree.ForOfStatement) => void; + "ForOfStatement:exit"?: (node: ESTree.ForOfStatement) => void; + ForStatement?: (node: ESTree.ForStatement) => void; + "ForStatement:exit"?: (node: ESTree.ForStatement) => void; + FunctionDeclaration?: (node: ESTree.Function) => void; + "FunctionDeclaration:exit"?: (node: ESTree.Function) => void; + FunctionExpression?: (node: ESTree.Function) => void; + "FunctionExpression:exit"?: (node: ESTree.Function) => void; + Identifier?: ( + node: + | ESTree.IdentifierName + | ESTree.IdentifierReference + | ESTree.BindingIdentifier + | ESTree.LabelIdentifier + | ESTree.TSThisParameter + | ESTree.TSIndexSignatureName, + ) => void; + "Identifier:exit"?: ( + node: + | ESTree.IdentifierName + | ESTree.IdentifierReference + | ESTree.BindingIdentifier + | ESTree.LabelIdentifier + | ESTree.TSThisParameter + | ESTree.TSIndexSignatureName, + ) => void; + IfStatement?: (node: ESTree.IfStatement) => void; + "IfStatement:exit"?: (node: ESTree.IfStatement) => void; + ImportAttribute?: (node: ESTree.ImportAttribute) => void; + "ImportAttribute:exit"?: (node: ESTree.ImportAttribute) => void; + ImportDeclaration?: (node: ESTree.ImportDeclaration) => void; + "ImportDeclaration:exit"?: (node: ESTree.ImportDeclaration) => void; + ImportDefaultSpecifier?: (node: ESTree.ImportDefaultSpecifier) => void; + "ImportDefaultSpecifier:exit"?: (node: ESTree.ImportDefaultSpecifier) => void; + ImportExpression?: (node: ESTree.ImportExpression) => void; + "ImportExpression:exit"?: (node: ESTree.ImportExpression) => void; + ImportNamespaceSpecifier?: (node: ESTree.ImportNamespaceSpecifier) => void; + "ImportNamespaceSpecifier:exit"?: (node: ESTree.ImportNamespaceSpecifier) => void; + ImportSpecifier?: (node: ESTree.ImportSpecifier) => void; + "ImportSpecifier:exit"?: (node: ESTree.ImportSpecifier) => void; + LabeledStatement?: (node: ESTree.LabeledStatement) => void; + "LabeledStatement:exit"?: (node: ESTree.LabeledStatement) => void; + LogicalExpression?: (node: ESTree.LogicalExpression) => void; + "LogicalExpression:exit"?: (node: ESTree.LogicalExpression) => void; + MemberExpression?: (node: ESTree.MemberExpression) => void; + "MemberExpression:exit"?: (node: ESTree.MemberExpression) => void; + MetaProperty?: (node: ESTree.MetaProperty) => void; + "MetaProperty:exit"?: (node: ESTree.MetaProperty) => void; + MethodDefinition?: (node: ESTree.MethodDefinition) => void; + "MethodDefinition:exit"?: (node: ESTree.MethodDefinition) => void; + NewExpression?: (node: ESTree.NewExpression) => void; + "NewExpression:exit"?: (node: ESTree.NewExpression) => void; + ObjectExpression?: (node: ESTree.ObjectExpression) => void; + "ObjectExpression:exit"?: (node: ESTree.ObjectExpression) => void; + ObjectPattern?: (node: ESTree.ObjectPattern) => void; + "ObjectPattern:exit"?: (node: ESTree.ObjectPattern) => void; + ParenthesizedExpression?: (node: ESTree.ParenthesizedExpression) => void; + "ParenthesizedExpression:exit"?: (node: ESTree.ParenthesizedExpression) => void; + Program?: (node: ESTree.Program) => void; + "Program:exit"?: (node: ESTree.Program) => void; + Property?: ( + node: + | ESTree.ObjectProperty + | ESTree.AssignmentTargetProperty + | ESTree.AssignmentTargetPropertyProperty + | ESTree.BindingProperty, + ) => void; + "Property:exit"?: ( + node: + | ESTree.ObjectProperty + | ESTree.AssignmentTargetProperty + | ESTree.AssignmentTargetPropertyProperty + | ESTree.BindingProperty, + ) => void; + PropertyDefinition?: (node: ESTree.PropertyDefinition) => void; + "PropertyDefinition:exit"?: (node: ESTree.PropertyDefinition) => void; + RestElement?: ( + node: ESTree.AssignmentTargetRest | ESTree.BindingRestElement | ESTree.FormalParameterRest, + ) => void; + "RestElement:exit"?: ( + node: ESTree.AssignmentTargetRest | ESTree.BindingRestElement | ESTree.FormalParameterRest, + ) => void; + ReturnStatement?: (node: ESTree.ReturnStatement) => void; + "ReturnStatement:exit"?: (node: ESTree.ReturnStatement) => void; + SequenceExpression?: (node: ESTree.SequenceExpression) => void; + "SequenceExpression:exit"?: (node: ESTree.SequenceExpression) => void; + SpreadElement?: (node: ESTree.SpreadElement) => void; + "SpreadElement:exit"?: (node: ESTree.SpreadElement) => void; + StaticBlock?: (node: ESTree.StaticBlock) => void; + "StaticBlock:exit"?: (node: ESTree.StaticBlock) => void; + SwitchCase?: (node: ESTree.SwitchCase) => void; + "SwitchCase:exit"?: (node: ESTree.SwitchCase) => void; + SwitchStatement?: (node: ESTree.SwitchStatement) => void; + "SwitchStatement:exit"?: (node: ESTree.SwitchStatement) => void; + TaggedTemplateExpression?: (node: ESTree.TaggedTemplateExpression) => void; + "TaggedTemplateExpression:exit"?: (node: ESTree.TaggedTemplateExpression) => void; + TemplateLiteral?: (node: ESTree.TemplateLiteral) => void; + "TemplateLiteral:exit"?: (node: ESTree.TemplateLiteral) => void; + ThrowStatement?: (node: ESTree.ThrowStatement) => void; + "ThrowStatement:exit"?: (node: ESTree.ThrowStatement) => void; + TryStatement?: (node: ESTree.TryStatement) => void; + "TryStatement:exit"?: (node: ESTree.TryStatement) => void; + UnaryExpression?: (node: ESTree.UnaryExpression) => void; + "UnaryExpression:exit"?: (node: ESTree.UnaryExpression) => void; + UpdateExpression?: (node: ESTree.UpdateExpression) => void; + "UpdateExpression:exit"?: (node: ESTree.UpdateExpression) => void; + V8IntrinsicExpression?: (node: ESTree.V8IntrinsicExpression) => void; + "V8IntrinsicExpression:exit"?: (node: ESTree.V8IntrinsicExpression) => void; + VariableDeclaration?: (node: ESTree.VariableDeclaration) => void; + "VariableDeclaration:exit"?: (node: ESTree.VariableDeclaration) => void; + VariableDeclarator?: (node: ESTree.VariableDeclarator) => void; + "VariableDeclarator:exit"?: (node: ESTree.VariableDeclarator) => void; + WhileStatement?: (node: ESTree.WhileStatement) => void; + "WhileStatement:exit"?: (node: ESTree.WhileStatement) => void; + WithStatement?: (node: ESTree.WithStatement) => void; + "WithStatement:exit"?: (node: ESTree.WithStatement) => void; + YieldExpression?: (node: ESTree.YieldExpression) => void; + "YieldExpression:exit"?: (node: ESTree.YieldExpression) => void; + JSXAttribute?: (node: ESTree.JSXAttribute) => void; + "JSXAttribute:exit"?: (node: ESTree.JSXAttribute) => void; + JSXClosingElement?: (node: ESTree.JSXClosingElement) => void; + "JSXClosingElement:exit"?: (node: ESTree.JSXClosingElement) => void; + JSXElement?: (node: ESTree.JSXElement) => void; + "JSXElement:exit"?: (node: ESTree.JSXElement) => void; + JSXExpressionContainer?: (node: ESTree.JSXExpressionContainer) => void; + "JSXExpressionContainer:exit"?: (node: ESTree.JSXExpressionContainer) => void; + JSXFragment?: (node: ESTree.JSXFragment) => void; + "JSXFragment:exit"?: (node: ESTree.JSXFragment) => void; + JSXMemberExpression?: (node: ESTree.JSXMemberExpression) => void; + "JSXMemberExpression:exit"?: (node: ESTree.JSXMemberExpression) => void; + JSXNamespacedName?: (node: ESTree.JSXNamespacedName) => void; + "JSXNamespacedName:exit"?: (node: ESTree.JSXNamespacedName) => void; + JSXOpeningElement?: (node: ESTree.JSXOpeningElement) => void; + "JSXOpeningElement:exit"?: (node: ESTree.JSXOpeningElement) => void; + JSXSpreadAttribute?: (node: ESTree.JSXSpreadAttribute) => void; + "JSXSpreadAttribute:exit"?: (node: ESTree.JSXSpreadAttribute) => void; + JSXSpreadChild?: (node: ESTree.JSXSpreadChild) => void; + "JSXSpreadChild:exit"?: (node: ESTree.JSXSpreadChild) => void; + TSAbstractAccessorProperty?: (node: ESTree.AccessorProperty) => void; + "TSAbstractAccessorProperty:exit"?: (node: ESTree.AccessorProperty) => void; + TSAbstractMethodDefinition?: (node: ESTree.MethodDefinition) => void; + "TSAbstractMethodDefinition:exit"?: (node: ESTree.MethodDefinition) => void; + TSAbstractPropertyDefinition?: (node: ESTree.PropertyDefinition) => void; + "TSAbstractPropertyDefinition:exit"?: (node: ESTree.PropertyDefinition) => void; + TSArrayType?: (node: ESTree.TSArrayType) => void; + "TSArrayType:exit"?: (node: ESTree.TSArrayType) => void; + TSAsExpression?: (node: ESTree.TSAsExpression) => void; + "TSAsExpression:exit"?: (node: ESTree.TSAsExpression) => void; + TSCallSignatureDeclaration?: (node: ESTree.TSCallSignatureDeclaration) => void; + "TSCallSignatureDeclaration:exit"?: (node: ESTree.TSCallSignatureDeclaration) => void; + TSClassImplements?: (node: ESTree.TSClassImplements) => void; + "TSClassImplements:exit"?: (node: ESTree.TSClassImplements) => void; + TSConditionalType?: (node: ESTree.TSConditionalType) => void; + "TSConditionalType:exit"?: (node: ESTree.TSConditionalType) => void; + TSConstructSignatureDeclaration?: (node: ESTree.TSConstructSignatureDeclaration) => void; + "TSConstructSignatureDeclaration:exit"?: (node: ESTree.TSConstructSignatureDeclaration) => void; + TSConstructorType?: (node: ESTree.TSConstructorType) => void; + "TSConstructorType:exit"?: (node: ESTree.TSConstructorType) => void; + TSDeclareFunction?: (node: ESTree.Function) => void; + "TSDeclareFunction:exit"?: (node: ESTree.Function) => void; + TSEmptyBodyFunctionExpression?: (node: ESTree.Function) => void; + "TSEmptyBodyFunctionExpression:exit"?: (node: ESTree.Function) => void; + TSEnumBody?: (node: ESTree.TSEnumBody) => void; + "TSEnumBody:exit"?: (node: ESTree.TSEnumBody) => void; + TSEnumDeclaration?: (node: ESTree.TSEnumDeclaration) => void; + "TSEnumDeclaration:exit"?: (node: ESTree.TSEnumDeclaration) => void; + TSEnumMember?: (node: ESTree.TSEnumMember) => void; + "TSEnumMember:exit"?: (node: ESTree.TSEnumMember) => void; + TSExportAssignment?: (node: ESTree.TSExportAssignment) => void; + "TSExportAssignment:exit"?: (node: ESTree.TSExportAssignment) => void; + TSExternalModuleReference?: (node: ESTree.TSExternalModuleReference) => void; + "TSExternalModuleReference:exit"?: (node: ESTree.TSExternalModuleReference) => void; + TSFunctionType?: (node: ESTree.TSFunctionType) => void; + "TSFunctionType:exit"?: (node: ESTree.TSFunctionType) => void; + TSImportEqualsDeclaration?: (node: ESTree.TSImportEqualsDeclaration) => void; + "TSImportEqualsDeclaration:exit"?: (node: ESTree.TSImportEqualsDeclaration) => void; + TSImportType?: (node: ESTree.TSImportType) => void; + "TSImportType:exit"?: (node: ESTree.TSImportType) => void; + TSIndexSignature?: (node: ESTree.TSIndexSignature) => void; + "TSIndexSignature:exit"?: (node: ESTree.TSIndexSignature) => void; + TSIndexedAccessType?: (node: ESTree.TSIndexedAccessType) => void; + "TSIndexedAccessType:exit"?: (node: ESTree.TSIndexedAccessType) => void; + TSInferType?: (node: ESTree.TSInferType) => void; + "TSInferType:exit"?: (node: ESTree.TSInferType) => void; + TSInstantiationExpression?: (node: ESTree.TSInstantiationExpression) => void; + "TSInstantiationExpression:exit"?: (node: ESTree.TSInstantiationExpression) => void; + TSInterfaceBody?: (node: ESTree.TSInterfaceBody) => void; + "TSInterfaceBody:exit"?: (node: ESTree.TSInterfaceBody) => void; + TSInterfaceDeclaration?: (node: ESTree.TSInterfaceDeclaration) => void; + "TSInterfaceDeclaration:exit"?: (node: ESTree.TSInterfaceDeclaration) => void; + TSInterfaceHeritage?: (node: ESTree.TSInterfaceHeritage) => void; + "TSInterfaceHeritage:exit"?: (node: ESTree.TSInterfaceHeritage) => void; + TSIntersectionType?: (node: ESTree.TSIntersectionType) => void; + "TSIntersectionType:exit"?: (node: ESTree.TSIntersectionType) => void; + TSJSDocNonNullableType?: (node: ESTree.JSDocNonNullableType) => void; + "TSJSDocNonNullableType:exit"?: (node: ESTree.JSDocNonNullableType) => void; + TSJSDocNullableType?: (node: ESTree.JSDocNullableType) => void; + "TSJSDocNullableType:exit"?: (node: ESTree.JSDocNullableType) => void; + TSLiteralType?: (node: ESTree.TSLiteralType) => void; + "TSLiteralType:exit"?: (node: ESTree.TSLiteralType) => void; + TSMappedType?: (node: ESTree.TSMappedType) => void; + "TSMappedType:exit"?: (node: ESTree.TSMappedType) => void; + TSMethodSignature?: (node: ESTree.TSMethodSignature) => void; + "TSMethodSignature:exit"?: (node: ESTree.TSMethodSignature) => void; + TSModuleBlock?: (node: ESTree.TSModuleBlock) => void; + "TSModuleBlock:exit"?: (node: ESTree.TSModuleBlock) => void; + TSModuleDeclaration?: (node: ESTree.TSModuleDeclaration | ESTree.TSGlobalDeclaration) => void; + "TSModuleDeclaration:exit"?: ( + node: ESTree.TSModuleDeclaration | ESTree.TSGlobalDeclaration, + ) => void; + TSNamedTupleMember?: (node: ESTree.TSNamedTupleMember) => void; + "TSNamedTupleMember:exit"?: (node: ESTree.TSNamedTupleMember) => void; + TSNamespaceExportDeclaration?: (node: ESTree.TSNamespaceExportDeclaration) => void; + "TSNamespaceExportDeclaration:exit"?: (node: ESTree.TSNamespaceExportDeclaration) => void; + TSNonNullExpression?: (node: ESTree.TSNonNullExpression) => void; + "TSNonNullExpression:exit"?: (node: ESTree.TSNonNullExpression) => void; + TSOptionalType?: (node: ESTree.TSOptionalType) => void; + "TSOptionalType:exit"?: (node: ESTree.TSOptionalType) => void; + TSParameterProperty?: (node: ESTree.TSParameterProperty) => void; + "TSParameterProperty:exit"?: (node: ESTree.TSParameterProperty) => void; + TSParenthesizedType?: (node: ESTree.TSParenthesizedType) => void; + "TSParenthesizedType:exit"?: (node: ESTree.TSParenthesizedType) => void; + TSPropertySignature?: (node: ESTree.TSPropertySignature) => void; + "TSPropertySignature:exit"?: (node: ESTree.TSPropertySignature) => void; + TSQualifiedName?: (node: ESTree.TSQualifiedName) => void; + "TSQualifiedName:exit"?: (node: ESTree.TSQualifiedName) => void; + TSRestType?: (node: ESTree.TSRestType) => void; + "TSRestType:exit"?: (node: ESTree.TSRestType) => void; + TSSatisfiesExpression?: (node: ESTree.TSSatisfiesExpression) => void; + "TSSatisfiesExpression:exit"?: (node: ESTree.TSSatisfiesExpression) => void; + TSTemplateLiteralType?: (node: ESTree.TSTemplateLiteralType) => void; + "TSTemplateLiteralType:exit"?: (node: ESTree.TSTemplateLiteralType) => void; + TSTupleType?: (node: ESTree.TSTupleType) => void; + "TSTupleType:exit"?: (node: ESTree.TSTupleType) => void; + TSTypeAliasDeclaration?: (node: ESTree.TSTypeAliasDeclaration) => void; + "TSTypeAliasDeclaration:exit"?: (node: ESTree.TSTypeAliasDeclaration) => void; + TSTypeAnnotation?: (node: ESTree.TSTypeAnnotation) => void; + "TSTypeAnnotation:exit"?: (node: ESTree.TSTypeAnnotation) => void; + TSTypeAssertion?: (node: ESTree.TSTypeAssertion) => void; + "TSTypeAssertion:exit"?: (node: ESTree.TSTypeAssertion) => void; + TSTypeLiteral?: (node: ESTree.TSTypeLiteral) => void; + "TSTypeLiteral:exit"?: (node: ESTree.TSTypeLiteral) => void; + TSTypeOperator?: (node: ESTree.TSTypeOperator) => void; + "TSTypeOperator:exit"?: (node: ESTree.TSTypeOperator) => void; + TSTypeParameter?: (node: ESTree.TSTypeParameter) => void; + "TSTypeParameter:exit"?: (node: ESTree.TSTypeParameter) => void; + TSTypeParameterDeclaration?: (node: ESTree.TSTypeParameterDeclaration) => void; + "TSTypeParameterDeclaration:exit"?: (node: ESTree.TSTypeParameterDeclaration) => void; + TSTypeParameterInstantiation?: (node: ESTree.TSTypeParameterInstantiation) => void; + "TSTypeParameterInstantiation:exit"?: (node: ESTree.TSTypeParameterInstantiation) => void; + TSTypePredicate?: (node: ESTree.TSTypePredicate) => void; + "TSTypePredicate:exit"?: (node: ESTree.TSTypePredicate) => void; + TSTypeQuery?: (node: ESTree.TSTypeQuery) => void; + "TSTypeQuery:exit"?: (node: ESTree.TSTypeQuery) => void; + TSTypeReference?: (node: ESTree.TSTypeReference) => void; + "TSTypeReference:exit"?: (node: ESTree.TSTypeReference) => void; + TSUnionType?: (node: ESTree.TSUnionType) => void; + "TSUnionType:exit"?: (node: ESTree.TSUnionType) => void; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/generated/visit/walk.js b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/walk.js new file mode 100644 index 0000000000000000000000000000000000000000..672c51aff7eec1df5daa061d557325884ea113ba --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/generated/visit/walk.js @@ -0,0 +1,2455 @@ +// Auto-generated code, DO NOT EDIT DIRECTLY! +// To edit this generated file you have to edit `tasks/ast_tools/src/generators/estree_visit.rs`. + +export { walkProgram }; + +function walkNode(node, visitors) { + if (node == null) return; + if (Array.isArray(node)) { + let len = node.length; + for (let i = 0; i < len; i++) walkNode(node[i], visitors); + } else + switch (node.type) { + case "DebuggerStatement": + walkDebuggerStatement(node, visitors); + break; + case "EmptyStatement": + walkEmptyStatement(node, visitors); + break; + case "Literal": + walkLiteral(node, visitors); + break; + case "PrivateIdentifier": + walkPrivateIdentifier(node, visitors); + break; + case "Super": + walkSuper(node, visitors); + break; + case "TemplateElement": + walkTemplateElement(node, visitors); + break; + case "ThisExpression": + walkThisExpression(node, visitors); + break; + case "JSXClosingFragment": + walkJSXClosingFragment(node, visitors); + break; + case "JSXEmptyExpression": + walkJSXEmptyExpression(node, visitors); + break; + case "JSXIdentifier": + walkJSXIdentifier(node, visitors); + break; + case "JSXOpeningFragment": + walkJSXOpeningFragment(node, visitors); + break; + case "JSXText": + walkJSXText(node, visitors); + break; + case "TSAnyKeyword": + walkTSAnyKeyword(node, visitors); + break; + case "TSBigIntKeyword": + walkTSBigIntKeyword(node, visitors); + break; + case "TSBooleanKeyword": + walkTSBooleanKeyword(node, visitors); + break; + case "TSIntrinsicKeyword": + walkTSIntrinsicKeyword(node, visitors); + break; + case "TSJSDocUnknownType": + walkTSJSDocUnknownType(node, visitors); + break; + case "TSNeverKeyword": + walkTSNeverKeyword(node, visitors); + break; + case "TSNullKeyword": + walkTSNullKeyword(node, visitors); + break; + case "TSNumberKeyword": + walkTSNumberKeyword(node, visitors); + break; + case "TSObjectKeyword": + walkTSObjectKeyword(node, visitors); + break; + case "TSStringKeyword": + walkTSStringKeyword(node, visitors); + break; + case "TSSymbolKeyword": + walkTSSymbolKeyword(node, visitors); + break; + case "TSThisType": + walkTSThisType(node, visitors); + break; + case "TSUndefinedKeyword": + walkTSUndefinedKeyword(node, visitors); + break; + case "TSUnknownKeyword": + walkTSUnknownKeyword(node, visitors); + break; + case "TSVoidKeyword": + walkTSVoidKeyword(node, visitors); + break; + case "AccessorProperty": + walkAccessorProperty(node, visitors); + break; + case "ArrayExpression": + walkArrayExpression(node, visitors); + break; + case "ArrayPattern": + walkArrayPattern(node, visitors); + break; + case "ArrowFunctionExpression": + walkArrowFunctionExpression(node, visitors); + break; + case "AssignmentExpression": + walkAssignmentExpression(node, visitors); + break; + case "AssignmentPattern": + walkAssignmentPattern(node, visitors); + break; + case "AwaitExpression": + walkAwaitExpression(node, visitors); + break; + case "BinaryExpression": + walkBinaryExpression(node, visitors); + break; + case "BlockStatement": + walkBlockStatement(node, visitors); + break; + case "BreakStatement": + walkBreakStatement(node, visitors); + break; + case "CallExpression": + walkCallExpression(node, visitors); + break; + case "CatchClause": + walkCatchClause(node, visitors); + break; + case "ChainExpression": + walkChainExpression(node, visitors); + break; + case "ClassBody": + walkClassBody(node, visitors); + break; + case "ClassDeclaration": + walkClassDeclaration(node, visitors); + break; + case "ClassExpression": + walkClassExpression(node, visitors); + break; + case "ConditionalExpression": + walkConditionalExpression(node, visitors); + break; + case "ContinueStatement": + walkContinueStatement(node, visitors); + break; + case "Decorator": + walkDecorator(node, visitors); + break; + case "DoWhileStatement": + walkDoWhileStatement(node, visitors); + break; + case "ExportAllDeclaration": + walkExportAllDeclaration(node, visitors); + break; + case "ExportDefaultDeclaration": + walkExportDefaultDeclaration(node, visitors); + break; + case "ExportNamedDeclaration": + walkExportNamedDeclaration(node, visitors); + break; + case "ExportSpecifier": + walkExportSpecifier(node, visitors); + break; + case "ExpressionStatement": + walkExpressionStatement(node, visitors); + break; + case "ForInStatement": + walkForInStatement(node, visitors); + break; + case "ForOfStatement": + walkForOfStatement(node, visitors); + break; + case "ForStatement": + walkForStatement(node, visitors); + break; + case "FunctionDeclaration": + walkFunctionDeclaration(node, visitors); + break; + case "FunctionExpression": + walkFunctionExpression(node, visitors); + break; + case "Identifier": + walkIdentifier(node, visitors); + break; + case "IfStatement": + walkIfStatement(node, visitors); + break; + case "ImportAttribute": + walkImportAttribute(node, visitors); + break; + case "ImportDeclaration": + walkImportDeclaration(node, visitors); + break; + case "ImportDefaultSpecifier": + walkImportDefaultSpecifier(node, visitors); + break; + case "ImportExpression": + walkImportExpression(node, visitors); + break; + case "ImportNamespaceSpecifier": + walkImportNamespaceSpecifier(node, visitors); + break; + case "ImportSpecifier": + walkImportSpecifier(node, visitors); + break; + case "LabeledStatement": + walkLabeledStatement(node, visitors); + break; + case "LogicalExpression": + walkLogicalExpression(node, visitors); + break; + case "MemberExpression": + walkMemberExpression(node, visitors); + break; + case "MetaProperty": + walkMetaProperty(node, visitors); + break; + case "MethodDefinition": + walkMethodDefinition(node, visitors); + break; + case "NewExpression": + walkNewExpression(node, visitors); + break; + case "ObjectExpression": + walkObjectExpression(node, visitors); + break; + case "ObjectPattern": + walkObjectPattern(node, visitors); + break; + case "ParenthesizedExpression": + walkParenthesizedExpression(node, visitors); + break; + case "Program": + walkProgram(node, visitors); + break; + case "Property": + walkProperty(node, visitors); + break; + case "PropertyDefinition": + walkPropertyDefinition(node, visitors); + break; + case "RestElement": + walkRestElement(node, visitors); + break; + case "ReturnStatement": + walkReturnStatement(node, visitors); + break; + case "SequenceExpression": + walkSequenceExpression(node, visitors); + break; + case "SpreadElement": + walkSpreadElement(node, visitors); + break; + case "StaticBlock": + walkStaticBlock(node, visitors); + break; + case "SwitchCase": + walkSwitchCase(node, visitors); + break; + case "SwitchStatement": + walkSwitchStatement(node, visitors); + break; + case "TaggedTemplateExpression": + walkTaggedTemplateExpression(node, visitors); + break; + case "TemplateLiteral": + walkTemplateLiteral(node, visitors); + break; + case "ThrowStatement": + walkThrowStatement(node, visitors); + break; + case "TryStatement": + walkTryStatement(node, visitors); + break; + case "UnaryExpression": + walkUnaryExpression(node, visitors); + break; + case "UpdateExpression": + walkUpdateExpression(node, visitors); + break; + case "V8IntrinsicExpression": + walkV8IntrinsicExpression(node, visitors); + break; + case "VariableDeclaration": + walkVariableDeclaration(node, visitors); + break; + case "VariableDeclarator": + walkVariableDeclarator(node, visitors); + break; + case "WhileStatement": + walkWhileStatement(node, visitors); + break; + case "WithStatement": + walkWithStatement(node, visitors); + break; + case "YieldExpression": + walkYieldExpression(node, visitors); + break; + case "JSXAttribute": + walkJSXAttribute(node, visitors); + break; + case "JSXClosingElement": + walkJSXClosingElement(node, visitors); + break; + case "JSXElement": + walkJSXElement(node, visitors); + break; + case "JSXExpressionContainer": + walkJSXExpressionContainer(node, visitors); + break; + case "JSXFragment": + walkJSXFragment(node, visitors); + break; + case "JSXMemberExpression": + walkJSXMemberExpression(node, visitors); + break; + case "JSXNamespacedName": + walkJSXNamespacedName(node, visitors); + break; + case "JSXOpeningElement": + walkJSXOpeningElement(node, visitors); + break; + case "JSXSpreadAttribute": + walkJSXSpreadAttribute(node, visitors); + break; + case "JSXSpreadChild": + walkJSXSpreadChild(node, visitors); + break; + case "TSAbstractAccessorProperty": + walkTSAbstractAccessorProperty(node, visitors); + break; + case "TSAbstractMethodDefinition": + walkTSAbstractMethodDefinition(node, visitors); + break; + case "TSAbstractPropertyDefinition": + walkTSAbstractPropertyDefinition(node, visitors); + break; + case "TSArrayType": + walkTSArrayType(node, visitors); + break; + case "TSAsExpression": + walkTSAsExpression(node, visitors); + break; + case "TSCallSignatureDeclaration": + walkTSCallSignatureDeclaration(node, visitors); + break; + case "TSClassImplements": + walkTSClassImplements(node, visitors); + break; + case "TSConditionalType": + walkTSConditionalType(node, visitors); + break; + case "TSConstructSignatureDeclaration": + walkTSConstructSignatureDeclaration(node, visitors); + break; + case "TSConstructorType": + walkTSConstructorType(node, visitors); + break; + case "TSDeclareFunction": + walkTSDeclareFunction(node, visitors); + break; + case "TSEmptyBodyFunctionExpression": + walkTSEmptyBodyFunctionExpression(node, visitors); + break; + case "TSEnumBody": + walkTSEnumBody(node, visitors); + break; + case "TSEnumDeclaration": + walkTSEnumDeclaration(node, visitors); + break; + case "TSEnumMember": + walkTSEnumMember(node, visitors); + break; + case "TSExportAssignment": + walkTSExportAssignment(node, visitors); + break; + case "TSExternalModuleReference": + walkTSExternalModuleReference(node, visitors); + break; + case "TSFunctionType": + walkTSFunctionType(node, visitors); + break; + case "TSImportEqualsDeclaration": + walkTSImportEqualsDeclaration(node, visitors); + break; + case "TSImportType": + walkTSImportType(node, visitors); + break; + case "TSIndexSignature": + walkTSIndexSignature(node, visitors); + break; + case "TSIndexedAccessType": + walkTSIndexedAccessType(node, visitors); + break; + case "TSInferType": + walkTSInferType(node, visitors); + break; + case "TSInstantiationExpression": + walkTSInstantiationExpression(node, visitors); + break; + case "TSInterfaceBody": + walkTSInterfaceBody(node, visitors); + break; + case "TSInterfaceDeclaration": + walkTSInterfaceDeclaration(node, visitors); + break; + case "TSInterfaceHeritage": + walkTSInterfaceHeritage(node, visitors); + break; + case "TSIntersectionType": + walkTSIntersectionType(node, visitors); + break; + case "TSJSDocNonNullableType": + walkTSJSDocNonNullableType(node, visitors); + break; + case "TSJSDocNullableType": + walkTSJSDocNullableType(node, visitors); + break; + case "TSLiteralType": + walkTSLiteralType(node, visitors); + break; + case "TSMappedType": + walkTSMappedType(node, visitors); + break; + case "TSMethodSignature": + walkTSMethodSignature(node, visitors); + break; + case "TSModuleBlock": + walkTSModuleBlock(node, visitors); + break; + case "TSModuleDeclaration": + walkTSModuleDeclaration(node, visitors); + break; + case "TSNamedTupleMember": + walkTSNamedTupleMember(node, visitors); + break; + case "TSNamespaceExportDeclaration": + walkTSNamespaceExportDeclaration(node, visitors); + break; + case "TSNonNullExpression": + walkTSNonNullExpression(node, visitors); + break; + case "TSOptionalType": + walkTSOptionalType(node, visitors); + break; + case "TSParameterProperty": + walkTSParameterProperty(node, visitors); + break; + case "TSParenthesizedType": + walkTSParenthesizedType(node, visitors); + break; + case "TSPropertySignature": + walkTSPropertySignature(node, visitors); + break; + case "TSQualifiedName": + walkTSQualifiedName(node, visitors); + break; + case "TSRestType": + walkTSRestType(node, visitors); + break; + case "TSSatisfiesExpression": + walkTSSatisfiesExpression(node, visitors); + break; + case "TSTemplateLiteralType": + walkTSTemplateLiteralType(node, visitors); + break; + case "TSTupleType": + walkTSTupleType(node, visitors); + break; + case "TSTypeAliasDeclaration": + walkTSTypeAliasDeclaration(node, visitors); + break; + case "TSTypeAnnotation": + walkTSTypeAnnotation(node, visitors); + break; + case "TSTypeAssertion": + walkTSTypeAssertion(node, visitors); + break; + case "TSTypeLiteral": + walkTSTypeLiteral(node, visitors); + break; + case "TSTypeOperator": + walkTSTypeOperator(node, visitors); + break; + case "TSTypeParameter": + walkTSTypeParameter(node, visitors); + break; + case "TSTypeParameterDeclaration": + walkTSTypeParameterDeclaration(node, visitors); + break; + case "TSTypeParameterInstantiation": + walkTSTypeParameterInstantiation(node, visitors); + break; + case "TSTypePredicate": + walkTSTypePredicate(node, visitors); + break; + case "TSTypeQuery": + walkTSTypeQuery(node, visitors); + break; + case "TSTypeReference": + walkTSTypeReference(node, visitors); + break; + case "TSUnionType": + walkTSUnionType(node, visitors); + break; + } +} + +function walkDebuggerStatement(node, visitors) { + let visit = visitors[0]; + visit !== null && visit(node); +} + +function walkEmptyStatement(node, visitors) { + let visit = visitors[1]; + visit !== null && visit(node); +} + +function walkLiteral(node, visitors) { + let visit = visitors[2]; + visit !== null && visit(node); +} + +function walkPrivateIdentifier(node, visitors) { + let visit = visitors[3]; + visit !== null && visit(node); +} + +function walkSuper(node, visitors) { + let visit = visitors[4]; + visit !== null && visit(node); +} + +function walkTemplateElement(node, visitors) { + let visit = visitors[5]; + visit !== null && visit(node); +} + +function walkThisExpression(node, visitors) { + let visit = visitors[6]; + visit !== null && visit(node); +} + +function walkJSXClosingFragment(node, visitors) { + let visit = visitors[7]; + visit !== null && visit(node); +} + +function walkJSXEmptyExpression(node, visitors) { + let visit = visitors[8]; + visit !== null && visit(node); +} + +function walkJSXIdentifier(node, visitors) { + let visit = visitors[9]; + visit !== null && visit(node); +} + +function walkJSXOpeningFragment(node, visitors) { + let visit = visitors[10]; + visit !== null && visit(node); +} + +function walkJSXText(node, visitors) { + let visit = visitors[11]; + visit !== null && visit(node); +} + +function walkTSAnyKeyword(node, visitors) { + let visit = visitors[12]; + visit !== null && visit(node); +} + +function walkTSBigIntKeyword(node, visitors) { + let visit = visitors[13]; + visit !== null && visit(node); +} + +function walkTSBooleanKeyword(node, visitors) { + let visit = visitors[14]; + visit !== null && visit(node); +} + +function walkTSIntrinsicKeyword(node, visitors) { + let visit = visitors[15]; + visit !== null && visit(node); +} + +function walkTSJSDocUnknownType(node, visitors) { + let visit = visitors[16]; + visit !== null && visit(node); +} + +function walkTSNeverKeyword(node, visitors) { + let visit = visitors[17]; + visit !== null && visit(node); +} + +function walkTSNullKeyword(node, visitors) { + let visit = visitors[18]; + visit !== null && visit(node); +} + +function walkTSNumberKeyword(node, visitors) { + let visit = visitors[19]; + visit !== null && visit(node); +} + +function walkTSObjectKeyword(node, visitors) { + let visit = visitors[20]; + visit !== null && visit(node); +} + +function walkTSStringKeyword(node, visitors) { + let visit = visitors[21]; + visit !== null && visit(node); +} + +function walkTSSymbolKeyword(node, visitors) { + let visit = visitors[22]; + visit !== null && visit(node); +} + +function walkTSThisType(node, visitors) { + let visit = visitors[23]; + visit !== null && visit(node); +} + +function walkTSUndefinedKeyword(node, visitors) { + let visit = visitors[24]; + visit !== null && visit(node); +} + +function walkTSUnknownKeyword(node, visitors) { + let visit = visitors[25]; + visit !== null && visit(node); +} + +function walkTSVoidKeyword(node, visitors) { + let visit = visitors[26]; + visit !== null && visit(node); +} + +function walkAccessorProperty(node, visitors) { + let enterExit = visitors[27], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.key, visitors); + walkNode(node.typeAnnotation, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkArrayExpression(node, visitors) { + let enterExit = visitors[28], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.elements, visitors); + exit !== null && exit(node); +} + +function walkArrayPattern(node, visitors) { + let enterExit = visitors[29], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.elements, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkArrowFunctionExpression(node, visitors) { + let enterExit = visitors[30], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkAssignmentExpression(node, visitors) { + let enterExit = visitors[31], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.left, visitors); + walkNode(node.right, visitors); + exit !== null && exit(node); +} + +function walkAssignmentPattern(node, visitors) { + let enterExit = visitors[32], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.left, visitors); + walkNode(node.right, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkAwaitExpression(node, visitors) { + let enterExit = visitors[33], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkBinaryExpression(node, visitors) { + let enterExit = visitors[34], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.left, visitors); + walkNode(node.right, visitors); + exit !== null && exit(node); +} + +function walkBlockStatement(node, visitors) { + let enterExit = visitors[35], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkBreakStatement(node, visitors) { + let enterExit = visitors[36], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.label, visitors); + exit !== null && exit(node); +} + +function walkCallExpression(node, visitors) { + let enterExit = visitors[37], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.callee, visitors); + walkNode(node.typeArguments, visitors); + walkNode(node.arguments, visitors); + exit !== null && exit(node); +} + +function walkCatchClause(node, visitors) { + let enterExit = visitors[38], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.param, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkChainExpression(node, visitors) { + let enterExit = visitors[39], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkClassBody(node, visitors) { + let enterExit = visitors[40], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkClassDeclaration(node, visitors) { + let enterExit = visitors[41], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.superClass, visitors); + walkNode(node.superTypeArguments, visitors); + walkNode(node.implements, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkClassExpression(node, visitors) { + let enterExit = visitors[42], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.superClass, visitors); + walkNode(node.superTypeArguments, visitors); + walkNode(node.implements, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkConditionalExpression(node, visitors) { + let enterExit = visitors[43], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.test, visitors); + walkNode(node.consequent, visitors); + walkNode(node.alternate, visitors); + exit !== null && exit(node); +} + +function walkContinueStatement(node, visitors) { + let enterExit = visitors[44], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.label, visitors); + exit !== null && exit(node); +} + +function walkDecorator(node, visitors) { + let enterExit = visitors[45], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkDoWhileStatement(node, visitors) { + let enterExit = visitors[46], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + walkNode(node.test, visitors); + exit !== null && exit(node); +} + +function walkExportAllDeclaration(node, visitors) { + let enterExit = visitors[47], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.exported, visitors); + walkNode(node.source, visitors); + walkNode(node.attributes, visitors); + exit !== null && exit(node); +} + +function walkExportDefaultDeclaration(node, visitors) { + let enterExit = visitors[48], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.declaration, visitors); + exit !== null && exit(node); +} + +function walkExportNamedDeclaration(node, visitors) { + let enterExit = visitors[49], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.declaration, visitors); + walkNode(node.specifiers, visitors); + walkNode(node.source, visitors); + walkNode(node.attributes, visitors); + exit !== null && exit(node); +} + +function walkExportSpecifier(node, visitors) { + let enterExit = visitors[50], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.local, visitors); + walkNode(node.exported, visitors); + exit !== null && exit(node); +} + +function walkExpressionStatement(node, visitors) { + let enterExit = visitors[51], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkForInStatement(node, visitors) { + let enterExit = visitors[52], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.left, visitors); + walkNode(node.right, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkForOfStatement(node, visitors) { + let enterExit = visitors[53], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.left, visitors); + walkNode(node.right, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkForStatement(node, visitors) { + let enterExit = visitors[54], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.init, visitors); + walkNode(node.test, visitors); + walkNode(node.update, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkFunctionDeclaration(node, visitors) { + let enterExit = visitors[55], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkFunctionExpression(node, visitors) { + let enterExit = visitors[56], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkIdentifier(node, visitors) { + let enterExit = visitors[57], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkIfStatement(node, visitors) { + let enterExit = visitors[58], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.test, visitors); + walkNode(node.consequent, visitors); + walkNode(node.alternate, visitors); + exit !== null && exit(node); +} + +function walkImportAttribute(node, visitors) { + let enterExit = visitors[59], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.key, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkImportDeclaration(node, visitors) { + let enterExit = visitors[60], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.specifiers, visitors); + walkNode(node.source, visitors); + walkNode(node.attributes, visitors); + exit !== null && exit(node); +} + +function walkImportDefaultSpecifier(node, visitors) { + let enterExit = visitors[61], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.local, visitors); + exit !== null && exit(node); +} + +function walkImportExpression(node, visitors) { + let enterExit = visitors[62], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.source, visitors); + walkNode(node.options, visitors); + exit !== null && exit(node); +} + +function walkImportNamespaceSpecifier(node, visitors) { + let enterExit = visitors[63], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.local, visitors); + exit !== null && exit(node); +} + +function walkImportSpecifier(node, visitors) { + let enterExit = visitors[64], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.imported, visitors); + walkNode(node.local, visitors); + exit !== null && exit(node); +} + +function walkLabeledStatement(node, visitors) { + let enterExit = visitors[65], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.label, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkLogicalExpression(node, visitors) { + let enterExit = visitors[66], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.left, visitors); + walkNode(node.right, visitors); + exit !== null && exit(node); +} + +function walkMemberExpression(node, visitors) { + let enterExit = visitors[67], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.object, visitors); + walkNode(node.property, visitors); + exit !== null && exit(node); +} + +function walkMetaProperty(node, visitors) { + let enterExit = visitors[68], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.meta, visitors); + walkNode(node.property, visitors); + exit !== null && exit(node); +} + +function walkMethodDefinition(node, visitors) { + let enterExit = visitors[69], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.key, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkNewExpression(node, visitors) { + let enterExit = visitors[70], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.callee, visitors); + walkNode(node.typeArguments, visitors); + walkNode(node.arguments, visitors); + exit !== null && exit(node); +} + +function walkObjectExpression(node, visitors) { + let enterExit = visitors[71], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.properties, visitors); + exit !== null && exit(node); +} + +function walkObjectPattern(node, visitors) { + let enterExit = visitors[72], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.properties, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkParenthesizedExpression(node, visitors) { + let enterExit = visitors[73], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkProgram(node, visitors) { + let enterExit = visitors[74], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkProperty(node, visitors) { + let enterExit = visitors[75], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.key, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkPropertyDefinition(node, visitors) { + let enterExit = visitors[76], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.key, visitors); + walkNode(node.typeAnnotation, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkRestElement(node, visitors) { + let enterExit = visitors[77], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.argument, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkReturnStatement(node, visitors) { + let enterExit = visitors[78], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkSequenceExpression(node, visitors) { + let enterExit = visitors[79], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expressions, visitors); + exit !== null && exit(node); +} + +function walkSpreadElement(node, visitors) { + let enterExit = visitors[80], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkStaticBlock(node, visitors) { + let enterExit = visitors[81], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkSwitchCase(node, visitors) { + let enterExit = visitors[82], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.test, visitors); + walkNode(node.consequent, visitors); + exit !== null && exit(node); +} + +function walkSwitchStatement(node, visitors) { + let enterExit = visitors[83], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.discriminant, visitors); + walkNode(node.cases, visitors); + exit !== null && exit(node); +} + +function walkTaggedTemplateExpression(node, visitors) { + let enterExit = visitors[84], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.tag, visitors); + walkNode(node.typeArguments, visitors); + walkNode(node.quasi, visitors); + exit !== null && exit(node); +} + +function walkTemplateLiteral(node, visitors) { + let enterExit = visitors[85], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.quasis, visitors); + walkNode(node.expressions, visitors); + exit !== null && exit(node); +} + +function walkThrowStatement(node, visitors) { + let enterExit = visitors[86], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkTryStatement(node, visitors) { + let enterExit = visitors[87], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.block, visitors); + walkNode(node.handler, visitors); + walkNode(node.finalizer, visitors); + exit !== null && exit(node); +} + +function walkUnaryExpression(node, visitors) { + let enterExit = visitors[88], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkUpdateExpression(node, visitors) { + let enterExit = visitors[89], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkV8IntrinsicExpression(node, visitors) { + let enterExit = visitors[90], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.name, visitors); + walkNode(node.arguments, visitors); + exit !== null && exit(node); +} + +function walkVariableDeclaration(node, visitors) { + let enterExit = visitors[91], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.declarations, visitors); + exit !== null && exit(node); +} + +function walkVariableDeclarator(node, visitors) { + let enterExit = visitors[92], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.init, visitors); + exit !== null && exit(node); +} + +function walkWhileStatement(node, visitors) { + let enterExit = visitors[93], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.test, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkWithStatement(node, visitors) { + let enterExit = visitors[94], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.object, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkYieldExpression(node, visitors) { + let enterExit = visitors[95], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkJSXAttribute(node, visitors) { + let enterExit = visitors[96], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.name, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkJSXClosingElement(node, visitors) { + let enterExit = visitors[97], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.name, visitors); + exit !== null && exit(node); +} + +function walkJSXElement(node, visitors) { + let enterExit = visitors[98], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.openingElement, visitors); + walkNode(node.children, visitors); + walkNode(node.closingElement, visitors); + exit !== null && exit(node); +} + +function walkJSXExpressionContainer(node, visitors) { + let enterExit = visitors[99], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkJSXFragment(node, visitors) { + let enterExit = visitors[100], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.openingFragment, visitors); + walkNode(node.children, visitors); + walkNode(node.closingFragment, visitors); + exit !== null && exit(node); +} + +function walkJSXMemberExpression(node, visitors) { + let enterExit = visitors[101], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.object, visitors); + walkNode(node.property, visitors); + exit !== null && exit(node); +} + +function walkJSXNamespacedName(node, visitors) { + let enterExit = visitors[102], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.namespace, visitors); + walkNode(node.name, visitors); + exit !== null && exit(node); +} + +function walkJSXOpeningElement(node, visitors) { + let enterExit = visitors[103], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.name, visitors); + walkNode(node.typeArguments, visitors); + walkNode(node.attributes, visitors); + exit !== null && exit(node); +} + +function walkJSXSpreadAttribute(node, visitors) { + let enterExit = visitors[104], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.argument, visitors); + exit !== null && exit(node); +} + +function walkJSXSpreadChild(node, visitors) { + let enterExit = visitors[105], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkTSAbstractAccessorProperty(node, visitors) { + let enterExit = visitors[106], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.key, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSAbstractMethodDefinition(node, visitors) { + let enterExit = visitors[107], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.key, visitors); + walkNode(node.value, visitors); + exit !== null && exit(node); +} + +function walkTSAbstractPropertyDefinition(node, visitors) { + let enterExit = visitors[108], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.key, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSArrayType(node, visitors) { + let enterExit = visitors[109], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.elementType, visitors); + exit !== null && exit(node); +} + +function walkTSAsExpression(node, visitors) { + let enterExit = visitors[110], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSCallSignatureDeclaration(node, visitors) { + let enterExit = visitors[111], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + exit !== null && exit(node); +} + +function walkTSClassImplements(node, visitors) { + let enterExit = visitors[112], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + walkNode(node.typeArguments, visitors); + exit !== null && exit(node); +} + +function walkTSConditionalType(node, visitors) { + let enterExit = visitors[113], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.checkType, visitors); + walkNode(node.extendsType, visitors); + walkNode(node.trueType, visitors); + walkNode(node.falseType, visitors); + exit !== null && exit(node); +} + +function walkTSConstructSignatureDeclaration(node, visitors) { + let enterExit = visitors[114], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + exit !== null && exit(node); +} + +function walkTSConstructorType(node, visitors) { + let enterExit = visitors[115], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + exit !== null && exit(node); +} + +function walkTSDeclareFunction(node, visitors) { + let enterExit = visitors[116], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkTSEmptyBodyFunctionExpression(node, visitors) { + let enterExit = visitors[117], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + exit !== null && exit(node); +} + +function walkTSEnumBody(node, visitors) { + let enterExit = visitors[118], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.members, visitors); + exit !== null && exit(node); +} + +function walkTSEnumDeclaration(node, visitors) { + let enterExit = visitors[119], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkTSEnumMember(node, visitors) { + let enterExit = visitors[120], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.initializer, visitors); + exit !== null && exit(node); +} + +function walkTSExportAssignment(node, visitors) { + let enterExit = visitors[121], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkTSExternalModuleReference(node, visitors) { + let enterExit = visitors[122], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkTSFunctionType(node, visitors) { + let enterExit = visitors[123], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + exit !== null && exit(node); +} + +function walkTSImportEqualsDeclaration(node, visitors) { + let enterExit = visitors[124], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.moduleReference, visitors); + exit !== null && exit(node); +} + +function walkTSImportType(node, visitors) { + let enterExit = visitors[125], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.source, visitors); + walkNode(node.options, visitors); + walkNode(node.qualifier, visitors); + walkNode(node.typeArguments, visitors); + exit !== null && exit(node); +} + +function walkTSIndexSignature(node, visitors) { + let enterExit = visitors[126], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.parameters, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSIndexedAccessType(node, visitors) { + let enterExit = visitors[127], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.objectType, visitors); + walkNode(node.indexType, visitors); + exit !== null && exit(node); +} + +function walkTSInferType(node, visitors) { + let enterExit = visitors[128], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeParameter, visitors); + exit !== null && exit(node); +} + +function walkTSInstantiationExpression(node, visitors) { + let enterExit = visitors[129], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + walkNode(node.typeArguments, visitors); + exit !== null && exit(node); +} + +function walkTSInterfaceBody(node, visitors) { + let enterExit = visitors[130], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkTSInterfaceDeclaration(node, visitors) { + let enterExit = visitors[131], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.extends, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkTSInterfaceHeritage(node, visitors) { + let enterExit = visitors[132], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + walkNode(node.typeArguments, visitors); + exit !== null && exit(node); +} + +function walkTSIntersectionType(node, visitors) { + let enterExit = visitors[133], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.types, visitors); + exit !== null && exit(node); +} + +function walkTSJSDocNonNullableType(node, visitors) { + let enterExit = visitors[134], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSJSDocNullableType(node, visitors) { + let enterExit = visitors[135], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSLiteralType(node, visitors) { + let enterExit = visitors[136], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.literal, visitors); + exit !== null && exit(node); +} + +function walkTSMappedType(node, visitors) { + let enterExit = visitors[137], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.key, visitors); + walkNode(node.constraint, visitors); + walkNode(node.nameType, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSMethodSignature(node, visitors) { + let enterExit = visitors[138], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.key, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.params, visitors); + walkNode(node.returnType, visitors); + exit !== null && exit(node); +} + +function walkTSModuleBlock(node, visitors) { + let enterExit = visitors[139], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkTSModuleDeclaration(node, visitors) { + let enterExit = visitors[140], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.body, visitors); + exit !== null && exit(node); +} + +function walkTSNamedTupleMember(node, visitors) { + let enterExit = visitors[141], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.label, visitors); + walkNode(node.elementType, visitors); + exit !== null && exit(node); +} + +function walkTSNamespaceExportDeclaration(node, visitors) { + let enterExit = visitors[142], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + exit !== null && exit(node); +} + +function walkTSNonNullExpression(node, visitors) { + let enterExit = visitors[143], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkTSOptionalType(node, visitors) { + let enterExit = visitors[144], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSParameterProperty(node, visitors) { + let enterExit = visitors[145], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.decorators, visitors); + walkNode(node.parameter, visitors); + exit !== null && exit(node); +} + +function walkTSParenthesizedType(node, visitors) { + let enterExit = visitors[146], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSPropertySignature(node, visitors) { + let enterExit = visitors[147], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.key, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSQualifiedName(node, visitors) { + let enterExit = visitors[148], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.left, visitors); + walkNode(node.right, visitors); + exit !== null && exit(node); +} + +function walkTSRestType(node, visitors) { + let enterExit = visitors[149], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSSatisfiesExpression(node, visitors) { + let enterExit = visitors[150], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.expression, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSTemplateLiteralType(node, visitors) { + let enterExit = visitors[151], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.quasis, visitors); + walkNode(node.types, visitors); + exit !== null && exit(node); +} + +function walkTSTupleType(node, visitors) { + let enterExit = visitors[152], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.elementTypes, visitors); + exit !== null && exit(node); +} + +function walkTSTypeAliasDeclaration(node, visitors) { + let enterExit = visitors[153], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.id, visitors); + walkNode(node.typeParameters, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSTypeAnnotation(node, visitors) { + let enterExit = visitors[154], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSTypeAssertion(node, visitors) { + let enterExit = visitors[155], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + walkNode(node.expression, visitors); + exit !== null && exit(node); +} + +function walkTSTypeLiteral(node, visitors) { + let enterExit = visitors[156], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.members, visitors); + exit !== null && exit(node); +} + +function walkTSTypeOperator(node, visitors) { + let enterExit = visitors[157], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSTypeParameter(node, visitors) { + let enterExit = visitors[158], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.name, visitors); + walkNode(node.constraint, visitors); + walkNode(node.default, visitors); + exit !== null && exit(node); +} + +function walkTSTypeParameterDeclaration(node, visitors) { + let enterExit = visitors[159], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.params, visitors); + exit !== null && exit(node); +} + +function walkTSTypeParameterInstantiation(node, visitors) { + let enterExit = visitors[160], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.params, visitors); + exit !== null && exit(node); +} + +function walkTSTypePredicate(node, visitors) { + let enterExit = visitors[161], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.parameterName, visitors); + walkNode(node.typeAnnotation, visitors); + exit !== null && exit(node); +} + +function walkTSTypeQuery(node, visitors) { + let enterExit = visitors[162], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.exprName, visitors); + walkNode(node.typeArguments, visitors); + exit !== null && exit(node); +} + +function walkTSTypeReference(node, visitors) { + let enterExit = visitors[163], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.typeName, visitors); + walkNode(node.typeArguments, visitors); + exit !== null && exit(node); +} + +function walkTSUnionType(node, visitors) { + let enterExit = visitors[164], + exit = null, + enter; + if (enterExit !== null) { + ({ enter, exit } = enterExit); + enter !== null && enter(node); + } + walkNode(node.types, visitors); + exit !== null && exit(node); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/index.d.ts b/tools/ui/node_modules/oxc-parser/src-js/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..342ea8a132fd52660b53b67e0541cc9511f34fe2 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/index.d.ts @@ -0,0 +1,312 @@ +/* auto-generated by NAPI-RS */ +/* eslint-disable */ + +import type { Program } from "@oxc-project/types"; +import type { VisitorObject } from "./generated/visit/visitor.d.ts"; + +export * from "@oxc-project/types"; + +export { VisitorObject }; + +export const visitorKeys: Record; + +export class Visitor { + constructor(visitor: VisitorObject); + visit(program: Program): void; +} +export interface Comment { + type: 'Line' | 'Block' + value: string + start: number + end: number +} + +export interface ErrorLabel { + message: string | null + start: number + end: number +} + +export interface OxcError { + severity: Severity + message: string + labels: Array + helpMessage: string | null + codeframe: string | null +} + +export declare const enum Severity { + Error = 'Error', + Warning = 'Warning', + Advice = 'Advice' +} +export declare class ParseResult { + get program(): import("@oxc-project/types").Program + get module(): EcmaScriptModule + get comments(): Array + get errors(): Array +} + +export interface DynamicImport { + start: number + end: number + moduleRequest: Span +} + +export interface EcmaScriptModule { + /** + * Has ESM syntax. + * + * i.e. `import` and `export` statements, and `import.meta`. + * + * Dynamic imports `import('foo')` are ignored since they can be used in non-ESM files. + */ + hasModuleSyntax: boolean + /** Import statements. */ + staticImports: Array + /** Export statements. */ + staticExports: Array + /** Dynamic import expressions. */ + dynamicImports: Array + /** Span positions` of `import.meta` */ + importMetas: Array +} + +export interface ExportExportName { + kind: ExportExportNameKind + name: string | null + start: number | null + end: number | null +} + +export declare const enum ExportExportNameKind { + /** `export { name } */ + Name = 'Name', + /** `export default expression` */ + Default = 'Default', + /** `export * from "mod" */ + None = 'None' +} + +export interface ExportImportName { + kind: ExportImportNameKind + name: string | null + start: number | null + end: number | null +} + +export declare const enum ExportImportNameKind { + /** `export { name } */ + Name = 'Name', + /** `export * as ns from "mod"` */ + All = 'All', + /** `export * from "mod"` */ + AllButDefault = 'AllButDefault', + /** Does not have a specifier. */ + None = 'None' +} + +export interface ExportLocalName { + kind: ExportLocalNameKind + name: string | null + start: number | null + end: number | null +} + +export declare const enum ExportLocalNameKind { + /** `export { name } */ + Name = 'Name', + /** `export default expression` */ + Default = 'Default', + /** + * If the exported value is not locally accessible from within the module. + * `export default function () {}` + */ + None = 'None' +} + +export interface ImportName { + kind: ImportNameKind + name: string | null + start: number | null + end: number | null +} + +export declare const enum ImportNameKind { + /** `import { x } from "mod"` */ + Name = 'Name', + /** `import * as ns from "mod"` */ + NamespaceObject = 'NamespaceObject', + /** `import defaultExport from "mod"` */ + Default = 'Default' +} + +/** + * Parse JS/TS source asynchronously on a separate thread. + * + * Note that not all of the workload can happen on a separate thread. + * Parsing on Rust side does happen in a separate thread, but deserialization of the AST to JS objects + * has to happen on current thread. This synchronous deserialization work typically outweighs + * the asynchronous parsing by a factor of between 3 and 20. + * + * i.e. the majority of the workload cannot be parallelized by using this method. + * + * Generally `parseSync` is preferable to use as it does not have the overhead of spawning a thread. + * If you need to parallelize parsing multiple files, it is recommended to use worker threads. + */ +export declare function parse(filename: string, sourceText: string, options?: ParserOptions | undefined | null): Promise + +export interface ParserOptions { + /** Treat the source text as `js`, `jsx`, `ts`, `tsx` or `dts`. */ + lang?: 'js' | 'jsx' | 'ts' | 'tsx' | 'dts' + /** Treat the source text as `script` or `module` code. */ + sourceType?: 'script' | 'module' | 'commonjs' | 'unambiguous' | undefined + /** + * Return an AST which includes TypeScript-related properties, or excludes them. + * + * `'js'` is default for JS / JSX files. + * `'ts'` is default for TS / TSX files. + * The type of the file is determined from `lang` option, or extension of provided `filename`. + */ + astType?: 'js' | 'ts' + /** + * Controls whether the `range` property is included on AST nodes. + * The `range` property is a `[number, number]` which indicates the start/end offsets + * of the node in the file contents. + * + * @default false + */ + range?: boolean + /** + * Emit `ParenthesizedExpression` and `TSParenthesizedType` in AST. + * + * If this option is true, parenthesized expressions are represented by + * (non-standard) `ParenthesizedExpression` and `TSParenthesizedType` nodes that + * have a single `expression` property containing the expression inside parentheses. + * + * @default true + */ + preserveParens?: boolean + /** + * Produce semantic errors with an additional AST pass. + * Semantic errors depend on symbols and scopes, where the parser does not construct. + * This adds a small performance overhead. + * + * @default false + */ + showSemanticErrors?: boolean +} + +/** + * Parse JS/TS source synchronously on current thread. + * + * This is generally preferable over `parse` (async) as it does not have the overhead + * of spawning a thread, and the majority of the workload cannot be parallelized anyway + * (see `parse` documentation for details). + * + * If you need to parallelize parsing multiple files, it is recommended to use worker threads + * with `parseSync` rather than using `parse`. + */ +export declare function parseSync(filename: string, sourceText: string, options?: ParserOptions | undefined | null): ParseResult + +/** Returns `true` if raw transfer is supported on this platform. */ +export declare function rawTransferSupported(): boolean + +export interface Span { + start: number + end: number +} + +export interface StaticExport { + start: number + end: number + entries: Array +} + +export interface StaticExportEntry { + start: number + end: number + moduleRequest: ValueSpan | null + /** The name under which the desired binding is exported by the module`. */ + importName: ExportImportName + /** The name used to export this binding by this module. */ + exportName: ExportExportName + /** The name that is used to locally access the exported value from within the importing module. */ + localName: ExportLocalName + /** + * Whether the export is a TypeScript `export type`. + * + * Examples: + * + * ```ts + * export type * from 'mod'; + * export type * as ns from 'mod'; + * export type { foo }; + * export { type foo }: + * export type { foo } from 'mod'; + * ``` + */ + isType: boolean +} + +export interface StaticImport { + /** Start of import statement. */ + start: number + /** End of import statement. */ + end: number + /** + * Import source. + * + * ```js + * import { foo } from "mod"; + * // ^^^ + * ``` + */ + moduleRequest: ValueSpan + /** + * Import specifiers. + * + * Empty for `import "mod"`. + */ + entries: Array +} + +export interface StaticImportEntry { + /** + * The name under which the desired binding is exported by the module. + * + * ```js + * import { foo } from "mod"; + * // ^^^ + * import { foo as bar } from "mod"; + * // ^^^ + * ``` + */ + importName: ImportName + /** + * The name that is used to locally access the imported value from within the importing module. + * ```js + * import { foo } from "mod"; + * // ^^^ + * import { foo as bar } from "mod"; + * // ^^^ + * ``` + */ + localName: ValueSpan + /** + * Whether this binding is for a TypeScript type-only import. + * + * `true` for the following imports: + * ```ts + * import type { foo } from "mod"; + * import { type foo } from "mod"; + * ``` + */ + isType: boolean +} + +export interface ValueSpan { + value: string + start: number + end: number +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/index.js b/tools/ui/node_modules/oxc-parser/src-js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9b1d9be03270926ef066cf4b41f81d3fccd9f0c5 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/index.js @@ -0,0 +1,108 @@ +import { createRequire } from "node:module"; +import { parse as parseBinding, parseSync as parseSyncBinding } from "./bindings.js"; +import { wrap } from "./wrap.js"; + +export { default as visitorKeys } from "./generated/visit/keys.js"; +export { Visitor } from "./visit/index.js"; + +export { + ExportExportNameKind, + ExportImportNameKind, + ExportLocalNameKind, + ImportNameKind, + ParseResult, + Severity, +} from "./bindings.js"; +export { rawTransferSupported } from "./raw-transfer/supported.js"; + +const require = createRequire(import.meta.url); + +// Lazily loaded as needed +let parseSyncRaw = null, + parseRaw, + parseSyncLazy = null, + parseLazy, + LazyVisitor; + +/** + * Lazy-load code related to raw transfer. + * @returns {undefined} + */ +function loadRawTransfer() { + if (parseSyncRaw === null) { + ({ parseSyncRaw, parse: parseRaw } = require("./raw-transfer/eager.js")); + } +} + +/** + * Lazy-load code related to raw transfer lazy deserialization. + * @returns {undefined} + */ +function loadRawTransferLazy() { + if (parseSyncLazy === null) { + ({ parseSyncLazy, parse: parseLazy, Visitor: LazyVisitor } = require("./raw-transfer/lazy.js")); + } +} + +/** + * Parse JS/TS source synchronously on current thread. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object|undefined} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors` + * @throws {Error} - If `experimentalRawTransfer` or `experimentalLazy` option is enabled, + * and raw transfer is not supported on this platform + */ +export function parseSync(filename, sourceText, options) { + if (options?.experimentalRawTransfer) { + loadRawTransfer(); + return parseSyncRaw(filename, sourceText, options); + } + if (options?.experimentalLazy) { + loadRawTransferLazy(); + return parseSyncLazy(filename, sourceText, options); + } + return wrap(parseSyncBinding(filename, sourceText, options)); +} + +/** + * Parse JS/TS source asynchronously on a separate thread. + * + * Note that not all of the workload can happen on a separate thread. + * Parsing on Rust side does happen in a separate thread, but deserialization of the AST to JS objects + * has to happen on current thread. This synchronous deserialization work typically outweighs + * the asynchronous parsing by a factor of between 3 and 20. + * + * i.e. the majority of the workload cannot be parallelized by using this method. + * + * Generally `parseSync` is preferable to use as it does not have the overhead of spawning a thread. + * If you need to parallelize parsing multiple files, it is recommended to use worker threads. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object|undefined} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors` + * @throws {Error} - If `experimentalRawTransfer` or `experimentalLazy` option is enabled, + * and raw transfer is not supported on this platform + */ +export async function parse(filename, sourceText, options) { + if (options?.experimentalRawTransfer) { + loadRawTransfer(); + return await parseRaw(filename, sourceText, options); + } + if (options?.experimentalLazy) { + loadRawTransferLazy(); + return await parseLazy(filename, sourceText, options); + } + return wrap(await parseBinding(filename, sourceText, options)); +} + +/** + * Get `Visitor` class to construct visitors with. + * @returns {function} - `Visitor` class + */ +export function experimentalGetLazyVisitor() { + loadRawTransferLazy(); + return LazyVisitor; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/common.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/common.js new file mode 100644 index 0000000000000000000000000000000000000000..8d5246a5e2f94d9b5a79b817c0b945b18ede5b12 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/common.js @@ -0,0 +1,276 @@ +import os from "node:os"; +import { BUFFER_ALIGN, BUFFER_SIZE, IS_TS_FLAG_POS } from "../generated/constants.js"; +import { + getBufferOffset, + parseRaw as parseRawBinding, + parseRawSync as parseRawSyncBinding, +} from "../bindings.js"; +import { rawTransferSupported } from "./supported.js"; + +// Throw an error if running on a platform which raw transfer doesn't support. +// +// Note: This module is lazy-loaded only when user calls `parseSync` or `parseAsync` with +// `experimentalRawTransfer` or `experimentalLazy` options, or calls `experimentalGetLazyVisitor`. +if (!rawTransferSupported()) { + throw new Error( + "`experimentalRawTransfer` and `experimentalLazy` options are not supported " + + "on 32-bit or big-endian systems, versions of NodeJS prior to v22.0.0, " + + "versions of Deno prior to v2.0.0, or other runtimes", + ); +} + +/** + * Parse JS/TS source synchronously on current thread using raw transfer. + * + * Convert the buffer returned by Rust to a JS object with provided `convert` function. + * + * This function contains logic shared by both `parseSyncRaw` and `parseSyncLazy`. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object} options - Parsing options + * @param {function} convert - Function to convert the buffer returned from Rust into a JS object + * @returns {Object} - The return value of `convert` + */ +export function parseSyncRawImpl(filename, sourceText, options, convert) { + const { buffer, sourceByteLen } = prepareRaw(sourceText); + parseRawSyncBinding(filename, buffer, sourceByteLen, options); + return convert(buffer, sourceText, sourceByteLen, options); +} + +// User should not schedule more async tasks than there are available CPUs, as it hurts performance, +// but it's a common mistake in async JS code to do exactly that. +// +// That anti-pattern looks like this when applied to Oxc: +// +// ```js +// const asts = await Promise.all( +// files.map( +// async (filename) => { +// const sourceText = await fs.readFile(filename, 'utf8'); +// const ast = await oxc.parseAsync(filename, sourceText); +// return ast; +// } +// ) +// ); +// ``` +// +// In most cases, that'd just result in a bit of degraded performance, and higher memory use because +// of loading sources into memory prematurely. +// +// However, raw transfer uses a 6 GiB buffer for each parsing operation. +// Most of the memory pages in those buffers are never touched, so this does not consume a huge amount +// of physical memory, but it does still consume virtual memory. +// +// If we allowed creating a large number of 6 GiB buffers simultaneously, it would quickly consume +// virtual memory space and risk memory exhaustion. The code above would exhaust all of bottom half +// (heap) of 48-bit virtual memory space if `files.length >= 21_845`. This is not a number which +// is unrealistic in real world code. +// +// To guard against this possibility, we implement a simple queue. +// No more than `os.availableParallelism()` files can be parsed simultaneously, and any further calls to +// `parseAsyncRaw` will be put in a queue, to execute once other tasks complete. +// +// Fallback to `os.cpus().length` on versions of NodeJS prior to v18.14.0, which do not support +// `os.availableParallelism`. +let availableCores = os.availableParallelism ? os.availableParallelism() : os.cpus().length; +const queue = []; + +/** + * Parse JS/TS source asynchronously using raw transfer. + * + * Convert the buffer returned by Rust to a JS object with provided `convert` function. + * + * Queues up parsing operations if more calls than number of CPU cores (see above). + * + * This function contains logic shared by both `parseAsyncRaw` and `parseAsyncLazy`. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object} options - Parsing options + * @param {function} convert - Function to convert the buffer returned from Rust into a JS object + * @returns {Object} - The return value of `convert` + */ +export async function parseAsyncRawImpl(filename, sourceText, options, convert) { + // Wait for a free CPU core if all CPUs are currently busy. + // + // Note: `availableCores` is NOT decremented if have to wait in the queue first, + // and NOT incremented when parsing completes and it runs next task in the queue. + // + // This is to avoid a race condition if `parseAsyncRaw` is called during the microtick in between + // `resolve` being called below, and the promise resolving here. In that case the new task could + // start running, and then the promise resolves, and the queued task also starts running. + // We'd then have `availableParallelism() + 1` tasks running simultaneously. Potentially, this could + // happen repeatedly, with the number of tasks running simultaneously ever-increasing. + if (availableCores === 0) { + // All CPU cores are busy. Put this task in queue and wait for capacity to become available. + await new Promise((resolve, _) => { + queue.push(resolve); + }); + } else { + // A CPU core is available. Mark core as busy, and run parsing now. + availableCores--; + } + + // Parse + const { buffer, sourceByteLen } = prepareRaw(sourceText); + await parseRawBinding(filename, buffer, sourceByteLen, options); + const data = convert(buffer, sourceText, sourceByteLen, options); + + // Free the CPU core + if (queue.length > 0) { + // Some further tasks waiting in queue. Run the next one. + // Do not increment `availableCores` (see above). + const resolve = queue.shift(); + resolve(); + } else { + // No tasks waiting in queue. This CPU is now free. + availableCores++; + } + + return data; +} + +const ARRAY_BUFFER_SIZE = BUFFER_SIZE + BUFFER_ALIGN; +const ONE_GIB = 1 << 30; + +// We keep a cache of buffers for raw transfer, so we can reuse them as much as possible. +// +// When processing multiple files, it's ideal if can reuse an existing buffer, as it's more likely to +// be warm in CPU cache, it avoids allocations, and it saves work for the garbage collector. +// +// However, we also don't want to keep a load of large buffers around indefinitely using up memory, +// if they're not going to be used again. +// +// We have no knowledge of what pattern over time user may process files in (could be lots in quick +// succession, or more occasionally in a long-running process). So we try to use flexible caching +// strategy which is adaptable to many usage patterns. +// +// We use a 2-tier cache. +// Tier 1 uses strong references, tier 2 uses weak references. +// +// When parsing is complete and the buffer is no longer in use, push it to `buffers` (tier 1 cache). +// Set a timer to clear the cache when no activity for 10 seconds. +// +// When the timer expires, move all the buffers from tier 1 cache into `oldBuffers` (tier 2). +// They are stored there as `WeakRef`s, so the garbage collector is free to reclaim them. +// +// On the next call to `parseSync` or `parseAsync`, promote any buffers in tier 2 cache which were not +// already garbage collected back into tier 1 cache. This is on assumption that parsing one file +// indicates parsing as a whole is an ongoing process, and there will likely be further calls to +// `parseSync` / `parseAsync` in future. +// +// The weak tier 2 cache is because V8 does not necessarily free memory as soon as it's able to be +// freed. We don't want to block it from freeing memory, but if it's not done that yet, there's no +// point creating a new buffer, when one already exists. +const CLEAR_BUFFERS_TIMEOUT = 10_000; // 10 seconds +const buffers = [], + oldBuffers = []; +let clearBuffersTimeout = null; + +const textEncoder = new TextEncoder(); + +/** + * Get a buffer (from cache if possible), and copy source text into it. + * + * @param {string} sourceText - Source text of file + * @returns {Object} - Object of form `{ buffer, sourceByteLen }`. + * - `buffer`: `Uint8Array` containing the AST in raw form. + * - `sourceByteLen`: Length of source text in UTF-8 bytes + * (which may not be equal to `sourceText.length` if source contains non-ASCII characters). + */ +export function prepareRaw(sourceText) { + // Cancel timeout for clearing buffers + if (clearBuffersTimeout !== null) { + clearTimeout(clearBuffersTimeout); + clearBuffersTimeout = null; + } + + // Revive any discarded buffers which have not yet been garbage collected + if (oldBuffers.length > 0) { + const revivedBuffers = []; + for (let oldBuffer of oldBuffers) { + oldBuffer = oldBuffer.deref(); + if (oldBuffer !== undefined) revivedBuffers.push(oldBuffer); + } + oldBuffers.length = 0; + if (revivedBuffers.length > 0) buffers.unshift(...revivedBuffers); + } + + // Reuse existing buffer, or create a new one + const buffer = buffers.length > 0 ? buffers.pop() : createBuffer(); + + // Write source into start of buffer. + // `TextEncoder` cannot write into a `Uint8Array` larger than 1 GiB, + // so create a view into buffer of this size to write into. + const sourceBuffer = new Uint8Array(buffer.buffer, buffer.byteOffset, ONE_GIB); + const { read, written: sourceByteLen } = textEncoder.encodeInto(sourceText, sourceBuffer); + if (read !== sourceText.length) throw new Error("Failed to write source text into buffer"); + + return { buffer, sourceByteLen }; +} + +/** + * Get if AST should be parsed as JS or TS. + * Rust side sets a `bool` in this position in buffer which is `true` if TS. + * + * @param {Uint8Array} buffer - Buffer containing AST in raw form + * @returns {boolean} - `true` if AST is JS, `false` if TS + */ +export function isJsAst(buffer) { + return buffer[IS_TS_FLAG_POS] === 0; +} + +/** + * Return buffer to cache, to be reused. + * Set a timer to clear buffers. + * + * @param {Uint8Array} buffer - Buffer + * @returns {undefined} + */ +export function returnBufferToCache(buffer) { + buffers.push(buffer); + + if (clearBuffersTimeout !== null) clearTimeout(clearBuffersTimeout); + clearBuffersTimeout = setTimeout(clearBuffersCache, CLEAR_BUFFERS_TIMEOUT); + clearBuffersTimeout.unref(); +} + +/** + * Downgrade buffers in tier 1 cache (`buffers`) to tier 2 (`oldBuffers`) + * so they can be garbage collected. + * + * @returns {undefined} + */ +function clearBuffersCache() { + clearBuffersTimeout = null; + + for (const buffer of buffers) { + oldBuffers.push(new WeakRef(buffer)); + } + buffers.length = 0; +} + +/** + * Create a `Uint8Array` which is 2 GiB in size, with its start aligned on 4 GiB. + * + * Achieve this by creating a 6 GiB `ArrayBuffer`, getting the offset within it that's aligned to 4 GiB, + * chopping off that number of bytes from the start, and shortening to 2 GiB. + * + * It's always possible to obtain a 2 GiB slice aligned on 4 GiB within a 6 GiB buffer, + * no matter how the 6 GiB buffer is aligned. + * + * Note: On systems with virtual memory, this only consumes 6 GiB of *virtual* memory. + * It does not consume physical memory until data is actually written to the `Uint8Array`. + * Physical memory consumed corresponds to the quantity of data actually written. + * + * @returns {Uint8Array} - Buffer + */ +function createBuffer() { + const arrayBuffer = new ArrayBuffer(ARRAY_BUFFER_SIZE); + const offset = getBufferOffset(new Uint8Array(arrayBuffer)); + const buffer = new Uint8Array(arrayBuffer, offset, BUFFER_SIZE); + buffer.int32 = new Int32Array(arrayBuffer, offset, BUFFER_SIZE / 4); + buffer.float64 = new Float64Array(arrayBuffer, offset, BUFFER_SIZE / 8); + return buffer; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/eager.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/eager.js new file mode 100644 index 0000000000000000000000000000000000000000..303fa79ca6c14dd507d32df03b4648df5f4edf21 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/eager.js @@ -0,0 +1,254 @@ +import { createRequire } from "node:module"; +import { TOKENS_OFFSET_POS_32, TOKENS_LEN_POS_32 } from "../generated/constants.js"; +import { isJsAst, parseAsyncRawImpl, parseSyncRawImpl, returnBufferToCache } from "./common.js"; + +const require = createRequire(import.meta.url); + +/** + * Parse JS/TS source synchronously on current thread, using raw transfer to speed up deserialization. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors` + */ +export function parseSyncRaw(filename, sourceText, options) { + return parseSyncRawImpl(filename, sourceText, options, deserialize); +} + +/** + * Parse JS/TS source asynchronously, using raw transfer to speed up deserialization. + * + * Note that not all of the workload can happen on a separate thread. + * Parsing on Rust side does happen in a separate thread, but deserialization of the AST to JS objects + * has to happen on current thread. This synchronous deserialization work typically outweighs + * the asynchronous parsing by a factor of around 3. + * + * i.e. the majority of the workload cannot be parallelized by using this method. + * + * Generally `parseSyncRaw` is preferable to use as it does not have the overhead of spawning a thread. + * If you need to parallelize parsing multiple files, it is recommended to use worker threads. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors` + */ +export function parse(filename, sourceText, options) { + return parseAsyncRawImpl(filename, sourceText, options, deserialize); +} + +// Deserializers are large files, so lazy-loaded. +// `deserialize` functions are stored in this array once loaded. +// Index into these arrays is `isJs * 1 + range * 2 + experimentalParent * 4`. +const deserializers = [null, null, null, null, null, null, null, null]; +const deserializerNames = [ + "ts", + "js", + "ts_range", + "js_range", + "ts_parent", + "js_parent", + "ts_range_parent", + "js_range_parent", +]; + +/** + * Deserialize whole AST from buffer. + * + * @param {Uint8Array} buffer - Buffer containing AST in raw form + * @param {string} sourceText - Source for the file + * @param {number} sourceByteLen - Length of source text in UTF-8 bytes + * @param {Object} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors` + */ +function deserialize(buffer, sourceText, sourceByteLen, options) { + const isJs = isJsAst(buffer), + range = !!options.range, + parent = !!options.experimentalParent; + + // Lazy load deserializer, and deserialize buffer to JS objects + const deserializerIndex = +isJs | (+range << 1) | (+parent << 2); + let deserializeThis = deserializers[deserializerIndex]; + if (deserializeThis === null) { + deserializeThis = deserializers[deserializerIndex] = require( + `../generated/deserialize/${deserializerNames[deserializerIndex]}.js`, + ).deserialize; + } + + const data = deserializeThis(buffer, sourceText, sourceByteLen); + + // Add a line comment for hashbang if JS. + // Do not add comment if TS, to match `@typescript-eslint/parser`. + // See https://github.com/oxc-project/oxc/blob/ea784f5f082e4c53c98afde9bf983afd0b95e44e/napi/parser/src/lib.rs#L106-L130 + if (isJs) { + const { hashbang } = data.program; + if (hashbang !== null) { + data.comments.unshift( + range + ? { + type: "Line", + value: hashbang.value, + start: hashbang.start, + end: hashbang.end, + range: hashbang.range, + } + : { type: "Line", value: hashbang.value, start: hashbang.start, end: hashbang.end }, + ); + } + } + + // Deserialize tokens + const tokens = options.experimentalTokens ? deserializeTokens(buffer, sourceText, isJs) : null; + + // Return buffer to cache, to be reused + returnBufferToCache(buffer); + + // We cannot lazily deserialize in the getters, because the buffer might be re-used to parse + // another file before the getter is called + if (tokens !== null) { + return { + get program() { + return data.program; + }, + get module() { + return data.module; + }, + get comments() { + return data.comments; + }, + get tokens() { + return tokens; + }, + get errors() { + return data.errors; + }, + }; + } + + return { + get program() { + return data.program; + }, + get module() { + return data.module; + }, + get comments() { + return data.comments; + }, + get errors() { + return data.errors; + }, + }; +} + +// `ESTreeKind` discriminants (set by Rust side) +const PRIVATE_IDENTIFIER_KIND = 2; +const REGEXP_KIND = 8; + +// Indexed by `ESTreeKind` discriminant (matches `ESTreeKind` enum in `estree_kind.rs`) +const TOKEN_TYPES = [ + "Identifier", + "Keyword", + "PrivateIdentifier", + "Punctuator", + "Numeric", + "String", + "Boolean", + "Null", + "RegularExpression", + "Template", + "JSXText", + "JSXIdentifier", +]; + +// Mask for active bits in `ESTreeKind` discriminants +const TOKEN_KIND_MASK = 15; + +// Details of Rust `Token` type +const TOKEN_SIZE = 16; + +/** + * Deserialize tokens from buffer. + * @param {Uint8Array} buffer - Buffer containing AST in raw form + * @param {string} sourceText - Source for the file + * @param {boolean} isJs - `true` if parsing in JS mode + * @returns {Object[]} - Array of token objects + */ +function deserializeTokens(buffer, sourceText, isJs) { + const { int32 } = buffer; + + let pos = int32[TOKENS_OFFSET_POS_32]; + const len = int32[TOKENS_LEN_POS_32]; + const endPos = pos + len * TOKEN_SIZE; + + const tokens = []; + while (pos < endPos) { + tokens.push(deserializeToken(pos, int32, sourceText, isJs)); + pos += TOKEN_SIZE; + } + return tokens; +} + +/** + * Deserialize a token from buffer at position `pos`. + * @param {number} pos - Position in buffer containing Rust `Token` type + * @param {Int32Array} int32 - Buffer containing AST in raw form as an `Int32Array` + * @param {string} sourceText - Source for the file + * @param {boolean} isJs - `true` if parsing in JS mode + * @returns {Object} - Token object + */ +function deserializeToken(pos, int32, sourceText, isJs) { + const pos32 = pos >> 2, + start = int32[pos32], + end = int32[pos32 + 1], + kindAndFlags = int32[pos32 + 2]; + + let value = sourceText.slice(start, end); + + // `Kind` is byte at index 8 in `Token`. + // `Kind` has 12 variants numbered from 0 to 11. + // We have to mask the bottom byte (`& 0xFF`), so may as well mask off bits which can't be set in `Kind` at same time. + // This may allow V8 to generate more efficient code for `TOKEN_TYPES[kind]`. + const kind = kindAndFlags & TOKEN_KIND_MASK; + + if (kind === REGEXP_KIND) { + const patternEnd = value.lastIndexOf("/"); + return { + type: "RegularExpression", + value, + regex: { + pattern: value.slice(1, patternEnd), + flags: value.slice(patternEnd + 1), + }, + start, + end, + }; + } + + // Strip leading `#` from private identifiers + if (kind === PRIVATE_IDENTIFIER_KIND) value = value.slice(1); + + // Unescape identifiers, keywords, and private identifiers in JS mode. + // `is_escaped` flag is in byte 10 of `Token`, and is a `bool`. + if (isJs && kind <= PRIVATE_IDENTIFIER_KIND && (kindAndFlags & 0x10000) !== 0) { + value = unescapeIdentifier(value); + } + + return { type: TOKEN_TYPES[kind], value, start, end }; +} + +/** + * Unescape an identifier. + * + * We do this on JS side, because escaped identifiers are so extremely rare that this function + * is never called in practice anyway. + * + * @param {string} name - Identifier name to unescape + * @returns {string} - Unescaped identifier name + */ +function unescapeIdentifier(name) { + return name.replace(/\\u(?:\{([0-9a-fA-F]+)\}|([0-9a-fA-F]{4}))/g, (_, hex1, hex2) => + String.fromCodePoint(parseInt(hex1 ?? hex2, 16)), + ); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/lazy-common.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/lazy-common.js new file mode 100644 index 0000000000000000000000000000000000000000..dd5938ffd2192e8fe61e195d9c39f12fd9eb52d1 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/lazy-common.js @@ -0,0 +1,11 @@ +// Unique token which is not exposed publicly. +// Used to prevent user calling class constructors. +export const TOKEN = {}; + +/** + * Throw error when restricted class constructor is called by user code. + * @throws {Error} + */ +export function constructorError() { + throw new Error("Constructor is for internal use only"); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/lazy.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/lazy.js new file mode 100644 index 0000000000000000000000000000000000000000..9ce6d492940f340b44023d60322783c852a300c2 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/lazy.js @@ -0,0 +1,153 @@ +import { DATA_POINTER_POS_32, PROGRAM_OFFSET } from "../generated/constants.js"; +import { RawTransferData } from "../generated/lazy/constructors.js"; +import { walkProgram } from "../generated/lazy/walk.js"; +import { parseAsyncRawImpl, parseSyncRawImpl, returnBufferToCache } from "./common.js"; +import { TOKEN } from "./lazy-common.js"; +import { getVisitorsArr } from "./visitor.js"; +export { Visitor } from "./visitor.js"; + +/** + * Parse JS/TS source synchronously on current thread. + * + * The data in buffer is not deserialized. Is deserialized to JS objects lazily, when accessing the + * properties of objects. + * + * e.g. `program` in returned object is an instance of `Program` class, with getters for `start`, `end`, + * `body` etc. + * + * Returned object contains a `visit` function which can be used to visit the AST with a `Visitor` + * (`Visitor` class can be obtained by calling `experimentalGetLazyVisitor()`). + * + * Returned object contains a `dispose` method. When finished with this AST, it's advisable to call + * `dispose`, to return the buffer to the cache, so it can be reused. + * Garbage collector should do this anyway at some point, but on an unpredictable schedule, + * so it's preferable to call `dispose` manually, to ensure the buffer can be reused immediately. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors`, + * and `dispose` and `visit` methods + */ +export function parseSyncLazy(filename, sourceText, options) { + return parseSyncRawImpl(filename, sourceText, options, construct); +} + +/** + * Parse JS/TS source asynchronously on a separate thread. + * + * The data in buffer is not deserialized. Is deserialized to JS objects lazily, when accessing the + * properties of objects. + * + * e.g. `program` in returned object is an instance of `Program` class, with getters for `start`, `end`, + * `body` etc. + * + * Because this function does not deserialize the AST, unlike `parse`, very little work happens + * on current thread in this function. Deserialization work only occurs when properties of the objects + * are accessed. + * + * Returned object contains a `visit` function which can be used to visit the AST with a `Visitor` + * (`Visitor` class can be obtained by calling `experimentalGetLazyVisitor()`). + * + * Returned object contains a `dispose` method. When finished with this AST, it's advisable to call + * `dispose`, to return the buffer to the cache, so it can be reused. + * Garbage collector should do this anyway at some point, but on an unpredictable schedule, + * so it's preferable to call `dispose` manually, to ensure the buffer can be reused immediately. + * + * @param {string} filename - Filename + * @param {string} sourceText - Source text of file + * @param {Object} options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors`, + * and `dispose` and `visit` methods + */ +export function parse(filename, sourceText, options) { + return parseAsyncRawImpl(filename, sourceText, options, construct); +} + +// Registry for buffers which are held by lazily-deserialized ASTs. +// Returns buffer to cache when the `ast` wrapper is garbage collected. +// +// Check for existence of `FinalizationRegistry`, to avoid errors on old versions of NodeJS +// which don't support it. e.g. Prettier supports NodeJS v14. +// Raw transfer is disabled on NodeJS before v22, so it doesn't matter if this is `null` on old NodeJS +// - it'll never be accessed in that case. +const bufferRecycleRegistry = + typeof FinalizationRegistry === "undefined" + ? null + : new FinalizationRegistry(returnBufferToCache); + +/** + * Get an object with getters which lazy deserialize AST and other data from buffer. + * + * Object also includes `dispose` and `visit` functions. + * + * @param {Uint8Array} buffer - Buffer containing AST in raw form + * @param {string} sourceText - Source for the file + * @param {number} sourceByteLen - Length of source text in UTF-8 bytes + * @param {Object} _options - Parsing options + * @returns {Object} - Object with property getters for `program`, `module`, `comments`, and `errors`, + * and `dispose` and `visit` methods + */ +function construct(buffer, sourceText, sourceByteLen, _options) { + // Create AST object + const sourceIsAscii = sourceText.length === sourceByteLen; + const ast = { buffer, sourceText, sourceByteLen, sourceIsAscii, nodes: new Map(), token: TOKEN }; + + // Register `ast` with the recycle registry so buffer is returned to cache + // when `ast` is garbage collected + bufferRecycleRegistry.register(ast, buffer, ast); + + // Get root data class instance + const rawDataPos = buffer.int32[DATA_POINTER_POS_32]; + const data = new RawTransferData(rawDataPos, ast); + + return { + get program() { + return data.program; + }, + get module() { + return data.module; + }, + get comments() { + return data.comments; + }, + get errors() { + return data.errors; + }, + dispose: dispose.bind(null, ast), + visit(visitor) { + walkProgram(rawDataPos + PROGRAM_OFFSET, ast, getVisitorsArr(visitor)); + }, + }; +} + +/** + * Dispose of this AST. + * + * After calling this method, trying to read any nodes from this AST may cause an error. + * + * Buffer is returned to the cache to be reused. + * + * The buffer would be returned to the cache anyway, once all nodes of the AST are garbage collected, + * but calling `dispose` is preferable, as it will happen immediately. + * Otherwise, garbage collector may take time to collect the `ast` object, and new buffers may be created + * in the meantime, when we could have reused this one. + * + * @param {Object} ast - AST object containing buffer etc + * @returns {undefined} + */ +function dispose(ast) { + // Return buffer to cache, to be reused + returnBufferToCache(ast.buffer); + + // Remove connection between `ast` and the buffer + ast.buffer = null; + + // Clear other contents of `ast`, so they can be garbage collected + ast.sourceText = null; + ast.nodes = null; + + // Remove `ast` from recycling register. + // When `ast` is garbage collected, there's no longer any action to be taken. + bufferRecycleRegistry.unregister(ast); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/node-array.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/node-array.js new file mode 100644 index 0000000000000000000000000000000000000000..7b133640c2e6130daec9f0adb21b0753b82b7d2a --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/node-array.js @@ -0,0 +1,365 @@ +import { constructorError, TOKEN } from "./lazy-common.js"; + +// Internal symbol to get `NodeArray` from a proxy wrapping a `NodeArray`. +// +// Methods of `NodeArray` are called with `this` being the proxy, rather than the `NodeArray` itself. +// They can "unwrap" the proxy by getting `this[ARRAY]`, and the `get` proxy trap will return +// the actual `NodeArray`. +// +// This symbol is not exported, and it is not actually defined on `NodeArray`s, so user cannot obtain it +// via `Object.getOwnPropertySymbols` or `Reflect.ownKeys`. Therefore user code cannot unwrap the proxy. +const ARRAY = Symbol(); + +// Functions to get internal properties of a `NodeArray`. Initialized in class static block below. +let getInternalFromProxy, getLength, getElement; + +/** + * An array of AST nodes where elements are deserialized lazily upon access. + * + * Extends `Array` to make `Array.isArray` return `true` for a `NodeArray`. + * + * TODO: Other methods could maybe be more optimal, avoiding going via proxy multiple times + * e.g. `some`, `indexOf`. + */ +export class NodeArray extends Array { + #internal; + + /** + * Create a `NodeArray`. + * + * Constructor does not actually return a `NodeArray`, but one wrapped in a `Proxy`. + * The proxy intercepts accesses to elements and lazily deserializes them, + * and blocks mutation of elements or `length` property. + * + * @class + * @param {number} pos - Buffer position of first element + * @param {number} length - Number of elements + * @param {number} stride - Element size in bytes + * @param {Function} construct - Function to deserialize element + * @param {Object} ast - AST object + * @returns {Proxy} - `NodeArray` wrapped in a `Proxy` + */ + constructor(pos, length, stride, construct, ast) { + if (ast?.token !== TOKEN) constructorError(); + + super(); + this.#internal = { pos, length, ast, stride, construct }; + return new Proxy(this, PROXY_HANDLERS); + } + + // Allow `arr.filter`, `arr.map` etc. + static [Symbol.species] = Array; + + // Override `values` method with a more efficient one that avoids going via proxy for every iteration. + // TODO: Benchmark to check that this is actually faster. + values() { + return new NodeArrayValuesIterator(this); + } + + // Override `keys` method with a more efficient one that avoids going via proxy for every iteration. + // TODO: Benchmark to check that this is actually faster. + keys() { + return new NodeArrayKeysIterator(this); + } + + // Override `entries` method with a more efficient one that avoids going via proxy for every iteration. + // TODO: Benchmark to check that this is actually faster. + entries() { + return new NodeArrayEntriesIterator(this); + } + + // This method is overwritten with reference to `values` method below. + // Defining dummy method here to prevent the later assignment altering the shape of class prototype. + [Symbol.iterator]() {} + + /** + * Override `slice` method to return a `NodeArray`. + * + * @this {NodeArray} + * @param {*} start - Start of slice + * @param {*} end - End of slice + * @returns {NodeArray} - `NodeArray` containing slice of this one + */ + slice(start, end) { + const internal = this[ARRAY].#internal, + { length } = internal; + + start = toInt(start); + if (start < 0) { + start = length + start; + if (start < 0) start = 0; + } + + if (end === void 0) { + end = length; + } else { + end = toInt(end); + if (end < 0) { + end += length; + if (end < 0) end = 0; + } else if (end > length) { + end = length; + } + } + + let sliceLength = end - start; + if (sliceLength <= 0 || start >= length) { + start = 0; + sliceLength = 0; + } + + const { stride } = internal; + return new NodeArray( + internal.pos + start * stride, + sliceLength, + stride, + internal.construct, + internal.ast, + ); + } + + // Make `console.log` deserialize all elements. + [Symbol.for("nodejs.util.inspect.custom")]() { + const values = [...this.values()]; + Object.setPrototypeOf(values, DebugNodeArray.prototype); + return values; + } + + static { + /** + * Get internal properties of `NodeArray`, given a proxy wrapping a `NodeArray`. + * @param {Proxy} proxy - Proxy wrapping `NodeArray` object + * @returns {Object} - Internal properties object + */ + getInternalFromProxy = (proxy) => proxy[ARRAY].#internal; + + /** + * Get length of `NodeArray`. + * @param {NodeArray} arr - `NodeArray` object + * @returns {number} - Array length + */ + getLength = (arr) => arr.#internal.length; + + /** + * Get element of `NodeArray` at index `index`. + * + * @param {NodeArray} arr - `NodeArray` object + * @param {number} index - Index of element to get + * @returns {*} - Element at index `index`, or `undefined` if out of bounds + */ + getElement = (arr, index) => { + const internal = arr.#internal; + if (index >= internal.length) return void 0; + return (0, internal.construct)(internal.pos + index * internal.stride, internal.ast); + }; + } +} + +// oxlint-disable-next-line typescript/unbound-method +NodeArray.prototype[Symbol.iterator] = NodeArray.prototype.values; + +/** + * Iterator over values of a `NodeArray`. + * Returned by `values` method, and also used as iterator for `for (const node of nodeArray) {}`. + */ +class NodeArrayValuesIterator { + #internal; + + constructor(proxy) { + const internal = getInternalFromProxy(proxy), + { pos, stride } = internal; + + this.#internal = { + pos, + endPos: pos + internal.length * stride, + ast: internal.ast, + construct: internal.construct, + stride, + }; + } + + next() { + const internal = this.#internal, + { pos } = internal; + if (pos === internal.endPos) return { done: true, value: null }; + internal.pos = pos + internal.stride; + return { done: false, value: (0, internal.construct)(pos, internal.ast) }; + } + + [Symbol.iterator]() { + return this; + } +} + +/** + * Iterator over keys of a `NodeArray`. Returned by `keys` method. + */ +class NodeArrayKeysIterator { + #internal; + + constructor(proxy) { + const internal = getInternalFromProxy(proxy); + this.#internal = { index: 0, length: internal.length }; + } + + next() { + const internal = this.#internal, + { index } = internal; + if (index === internal.length) return { done: true, value: null }; + internal.index = index + 1; + return { done: false, value: index }; + } + + [Symbol.iterator]() { + return this; + } +} + +/** + * Iterator over values of a `NodeArray`. Returned by `entries` method. + */ +class NodeArrayEntriesIterator { + #internal; + + constructor(proxy) { + const internal = getInternalFromProxy(proxy); + + this.#internal = { + index: 0, + length: internal.length, + pos: internal.pos, + ast: internal.ast, + construct: internal.construct, + stride: internal.stride, + }; + } + + next() { + const internal = this.#internal, + { index } = internal; + if (index === internal.length) return { done: true, value: null }; + internal.index = index + 1; + return { + done: false, + value: [index, (0, internal.construct)(internal.pos + index * internal.stride, internal.ast)], + }; + } + + [Symbol.iterator]() { + return this; + } +} + +// Class used for `[Symbol.for('nodejs.util.inspect.custom')]` method (for `console.log`). +const DebugNodeArray = class NodeArray extends Array {}; + +// Proxy handlers. +// +// Every `NodeArray` returned to user is wrapped in a `Proxy`, using these handlers. +// They lazily deserialize array elements upon access, and block mutation of array elements / `length`. +const PROXY_HANDLERS = { + // Return `true` for indexes which are in bounds. + // e.g. `'0' in arr`. + has(arr, key) { + const index = toIndex(key); + if (index !== null) return index < getLength(arr); + return Reflect.has(arr, key); + }, + + // Get elements and length. + get(arr, key) { + // Methods of `NodeArray` are called with `this` being the proxy, rather than the `NodeArray` itself. + // They can "unwrap" the proxy by getting `this[ARRAY]`. + if (key === ARRAY) return arr; + if (key === "length") return getLength(arr); + const index = toIndex(key); + if (index !== null) return getElement(arr, index); + + return Reflect.get(arr, key); + }, + + // Get descriptors for elements and length. + getOwnPropertyDescriptor(arr, key) { + if (key === "length") { + // Cannot return `writable: false` unfortunately + return { value: getLength(arr), writable: true, enumerable: false, configurable: false }; + } + + const index = toIndex(key); + if (index !== null) { + const value = getElement(arr, index); + if (value === void 0) return void 0; + // Cannot return `configurable: false` unfortunately + return { value, writable: false, enumerable: true, configurable: true }; + } + + return Reflect.getOwnPropertyDescriptor(arr, key); + }, + + // Prevent setting `length` or entries. + // Catches: + // * `Object.defineProperty(arr, 0, {value: null})`. + // * `arr[1] = null`. + // * `arr.length = 0`. + // * `Object.defineProperty(arr, 'length', {value: 0})`. + // * Other operations which mutate entries e.g. `arr.push(123)`. + defineProperty(arr, key, descriptor) { + if (key === "length" || toIndex(key) !== null) return false; + return Reflect.defineProperty(arr, key, descriptor); + }, + + // Prevent deleting entries. + deleteProperty(arr, key) { + // Note: `Reflect.deleteProperty(arr, 'length')` already returns `false` + if (toIndex(key) !== null) return false; + return Reflect.deleteProperty(arr, key); + }, + + // Get keys, including element indexes. + ownKeys(arr) { + const keys = [], + length = getLength(arr); + for (let i = 0; i < length; i++) { + keys.push(i + ""); + } + keys.push(...Reflect.ownKeys(arr)); + return keys; + }, +}; + +/** + * Convert key to array index, if it is a valid array index. + * + * Only strings comprising a plain integer are valid indexes. + * e.g. `"-1"`, `"01"`, `"0xFF"`, `"1e1"`, `"1 "` are not valid indexes. + * Integers >= 4294967295 are not valid indexes. + * + * @param {string|Symbol} - Key used for property lookup. + * @returns {number|null} - `key` converted to integer, if it's a valid array index, otherwise `null`. + */ +function toIndex(key) { + if (typeof key === "string") { + if (key === "0") return 0; + if (INDEX_REGEX.test(key)) { + const index = +key; + if (index < 4294967295) return index; + } + } + return null; +} + +const INDEX_REGEX = /^[1-9]\d*$/; + +/** + * Convert value to integer. + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion + * + * @param {*} value - Value to convert to integer. + * @returns {number} - Integer + */ +function toInt(value) { + value = Math.trunc(+value); + // `value === 0` check is to convert -0 to 0 + if (value === 0 || Number.isNaN(value)) return 0; + return value; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/supported.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/supported.js new file mode 100644 index 0000000000000000000000000000000000000000..33d5e2b05af2b881a2e1ddf543508ace709c251e --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/supported.js @@ -0,0 +1,52 @@ +import { rawTransferSupported as rawTransferSupportedBinding } from "../bindings.js"; + +let rawTransferIsSupported = null; + +/** + * Returns `true` if `experimentalRawTransfer` is option is supported. + * + * Raw transfer is only supported on 64-bit little-endian systems, + * and NodeJS >= v22.0.0 or Deno >= v2.0.0. + * + * Versions of NodeJS prior to v22.0.0 do not support creating an `ArrayBuffer` larger than 4 GiB. + * Bun (as at v1.2.4) also does not support creating an `ArrayBuffer` larger than 4 GiB. + * Support on Deno v1 is unknown and it's EOL, so treating Deno before v2.0.0 as unsupported. + * + * No easy way to determining pointer width (64 bit or 32 bit) in JS, + * so call a function on Rust side to find out. + * + * @returns {boolean} - `true` if raw transfer is supported on this platform + */ +export function rawTransferSupported() { + if (rawTransferIsSupported === null) { + rawTransferIsSupported = rawTransferRuntimeSupported() && rawTransferSupportedBinding(); + } + return rawTransferIsSupported; +} + +// Checks copied from: +// https://github.com/unjs/std-env/blob/ab15595debec9e9115a9c1d31bc7597a8e71dbfd/src/runtimes.ts +// MIT license: https://github.com/unjs/std-env/blob/ab15595debec9e9115a9c1d31bc7597a8e71dbfd/LICENCE +function rawTransferRuntimeSupported() { + let global; + try { + global = globalThis; + } catch { + return false; + } + + const isBun = !!global.Bun || !!global.process?.versions?.bun; + if (isBun) return false; + + const isDeno = !!global.Deno; + if (isDeno) { + const match = Deno.version?.deno?.match(/^(\d+)\./); + return !!match && match[1] * 1 >= 2; + } + + const isNode = global.process?.release?.name === "node"; + if (!isNode) return false; + + const match = process.version?.match(/^v(\d+)\./); + return !!match && match[1] * 1 >= 22; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/visitor.js b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..cd18ec8757850e0564357f942dd0cdd3ac4f5a8e --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/raw-transfer/visitor.js @@ -0,0 +1,127 @@ +import { + LEAF_NODE_TYPES_COUNT, + NODE_TYPE_IDS_MAP, + NODE_TYPES_COUNT, +} from "../generated/lazy/type_ids.js"; + +// Getter for private `#visitorsArr` property of `Visitor` class. Initialized in class body below. +let getVisitorsArrTemp; + +/** + * Visitor class, used to visit an AST. + */ +export class Visitor { + #visitorsArr; + + /** + * Create `Visitor`. + * + * Provide an object where keys are names of AST nodes you want to visit, + * and values are visitor functions which receive AST node objects of that type. + * + * Keys can also be postfixed with `:exit` to visit when exiting the node, rather than entering. + * + * ```js + * const visitor = new Visitor({ + * BinaryExpression(binExpr) { + * // Do stuff when entering a `BinaryExpression` + * }, + * 'BinaryExpression:exit'(binExpr) { + * // Do stuff when exiting a `BinaryExpression` + * }, + * }); + * ``` + * + * @class + * @param {Object} visitor - Object defining visit functions for AST nodes + * @returns {Visitor} + */ + constructor(visitor) { + this.#visitorsArr = createVisitorsArr(visitor); + } + + static { + getVisitorsArrTemp = (visitor) => visitor.#visitorsArr; + } +} + +export const getVisitorsArr = getVisitorsArrTemp; + +/** + * Create array of visitors, keyed by node type ID. + * + * Each element of array is one of: + * + * * No visitor for this type = `null`. + * * Visitor for leaf node = visit function. + * * Visitor for non-leaf node = object of form `{ enter, exit }`, + * where each property is either a visitor function or `null`. + * + * @param {Object} visitor - Visitors object from user + * @returns {Array} - Array of visitors + */ +function createVisitorsArr(visitor) { + if (visitor === null || typeof visitor !== "object") { + throw new Error("`visitor` must be an object"); + } + + // Create empty visitors array + const visitorsArr = []; + for (let i = NODE_TYPES_COUNT; i !== 0; i--) { + visitorsArr.push(null); + } + + // Populate visitors array from provided object + for (let name of Object.keys(visitor)) { + const visitFn = visitor[name]; + if (typeof visitFn !== "function") { + throw new Error(`'${name}' property of \`visitor\` object is not a function`); + } + + const isExit = name.endsWith(":exit"); + if (isExit) name = name.slice(0, -5); + + const typeId = NODE_TYPE_IDS_MAP.get(name); + if (typeId === void 0) throw new Error(`Unknown node type '${name}' in \`visitor\` object`); + + if (typeId < LEAF_NODE_TYPES_COUNT) { + // Leaf node. Store just 1 function. + const existingVisitFn = visitorsArr[typeId]; + if (existingVisitFn === null) { + visitorsArr[typeId] = visitFn; + } else if (isExit) { + visitorsArr[typeId] = combineVisitFunctions(existingVisitFn, visitFn); + } else { + visitorsArr[typeId] = combineVisitFunctions(visitFn, existingVisitFn); + } + continue; + } + + let enterExit = visitorsArr[typeId]; + if (enterExit === null) { + enterExit = visitorsArr[typeId] = { enter: null, exit: null }; + } + + if (isExit) { + enterExit.exit = visitFn; + } else { + enterExit.enter = visitFn; + } + } + + return visitorsArr; +} + +/** + * Combine 2 visitor functions into 1. + * + * @param {function} visit1 - 1st visitor function + * @param {function} visit2 - 2nd visitor function + * @returns {function} - Combined visitor function + */ +function combineVisitFunctions(visit1, visit2) { + return function (node) { + visit1(node); + visit2(node); + }; +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/visit/index.js b/tools/ui/node_modules/oxc-parser/src-js/visit/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a52f291e1cb0f18e0846dc4fc8dd2f9d56d809bf --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/visit/index.js @@ -0,0 +1,41 @@ +import { createRequire } from "node:module"; + +// Lazy-loaded when first construct a `Visitor` +let walkProgram = null, + addVisitorToCompiled, + createCompiledVisitor, + finalizeCompiledVisitor; + +/** + * Visitor class for traversing AST. + */ +export class Visitor { + #compiledVisitor = null; + + constructor(visitor) { + if (walkProgram === null) { + const require = createRequire(import.meta.url); + ({ walkProgram } = require("../generated/visit/walk.js")); + ({ + addVisitorToCompiled, + createCompiledVisitor, + finalizeCompiledVisitor, + } = require("./visitor.js")); + } + + const compiledVisitor = createCompiledVisitor(); + addVisitorToCompiled(visitor); + const needsVisit = finalizeCompiledVisitor(); + if (needsVisit) this.#compiledVisitor = compiledVisitor; + } + + /** + * Visit AST. + * @param program - The AST to visit. + * @returns {undefined} + */ + visit(program) { + const compiledVisitor = this.#compiledVisitor; + if (compiledVisitor !== null) walkProgram(program, compiledVisitor); + } +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/visit/visitor.js b/tools/ui/node_modules/oxc-parser/src-js/visit/visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..efad2fe18adabc951a47e3c4fc11ffd164ea24f4 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/visit/visitor.js @@ -0,0 +1,405 @@ +// Functions to compile 1 or more visitor objects into a single compiled visitor. +// +// # Visitor objects +// +// Visitor objects which are generated by rules' `create` functions have keys being either: +// * Name of an AST type. or +// * Name of an AST type postfixed with `:exit`. +// +// Each property value must be a function that handles that AST node. +// +// e.g.: +// +// ``` +// { +// BinaryExpression(node) { +// // Do stuff on enter +// }, +// 'BinaryExpression:exit'(node) { +// // Do stuff on exit +// }, +// } +// ``` +// +// # Compiled visitor +// +// Compiled visitor is an array with `NODE_TYPES_COUNT` length, keyed by the ID of the node type. +// `NODE_TYPE_IDS_MAP` maps from type name to ID. +// +// Each element of compiled array is one of: +// * No visitor for this type = `null`. +// * Visitor for leaf node = visit function. +// * Visitor for non-leaf node = object of form `{ enter, exit }`, +// where each property is either a visitor function or `null`. +// +// e.g.: +// +// ``` +// [ +// // Leaf nodes +// function(node) { /* do stuff */ }, +// // ... +// +// // Non-leaf nodes +// { +// enter: function(node) { /* do stuff */ }, +// exit: null, +// }, +// // ... +// ] +// ``` +// +// # Object reuse +// +// No more than 1 compiled visitor exists at any time, so we reuse a single array `compiledVisitor`, +// rather than creating a new array for each file being linted. +// +// To compile visitors, call: +// * `initCompiledVisitor` once. +// * `addVisitorToCompiled` with each visitor object. +// * `finalizeCompiledVisitor` once. +// +// After this sequence of calls, `compiledVisitor` is ready to be used to walk the AST. +// +// We also recycle: +// +// * `{ enter, exit }` objects which are stored in compiled visitor. +// * Temporary arrays used to store multiple visit functions, which are merged into a single function +// in `finalizeCompiledVisitor`. +// +// The aim is to reduce pressure on the garbage collector. All these recycled objects are long-lived +// and will graduate to "old space", which leaves as much capacity as possible in "new space" +// for objects created by user code in visitors. If ephemeral user-created objects all fit in new space, +// it will avoid full GC runs, which should greatly improve performance. + +import { + LEAF_NODE_TYPES_COUNT, + NODE_TYPE_IDS_MAP, + NODE_TYPES_COUNT, +} from "../generated/visit/type_ids.js"; + +// Compiled visitor used for visiting each file. +// Same array is reused for each file. +// +// Initialized with `.push()` to ensure V8 treats the array as "packed" (linear array), +// not "holey" (hash map). This is critical, as looking up elements in this array is a very hot path +// during AST visitation, and holey arrays are much slower. +// https://v8.dev/blog/elements-kinds +let compiledVisitor; + +export function createCompiledVisitor() { + // Create a new compiled visitor array + compiledVisitor = []; + for (let i = NODE_TYPES_COUNT; i !== 0; i--) { + compiledVisitor.push(null); + } + return compiledVisitor; +} + +// Arrays containing type IDs of types which have multiple visit functions defined for them. +// +// Filled with `0` initially up to maximum size they could ever need to be so: +// 1. These arrays never need to grow. +// 2. V8 treats these arrays as "PACKED_SMI_ELEMENTS". +const mergedLeafVisitorTypeIds = [], + mergedEnterVisitorTypeIds = [], + mergedExitVisitorTypeIds = []; + +for (let i = LEAF_NODE_TYPES_COUNT; i !== 0; i--) { + mergedLeafVisitorTypeIds.push(0); +} + +for (let i = NODE_TYPES_COUNT - LEAF_NODE_TYPES_COUNT; i !== 0; i--) { + mergedEnterVisitorTypeIds.push(0); + mergedExitVisitorTypeIds.push(0); +} + +mergedLeafVisitorTypeIds.length = 0; +mergedEnterVisitorTypeIds.length = 0; +mergedExitVisitorTypeIds.length = 0; + +// `true` if `addVisitor` has been called with a visitor which visits at least one AST type +let hasActiveVisitors = false; + +// Enter+exit object cache. +// +// `compiledVisitor` may contain many `{ enter, exit }` objects. +// Use this cache to reuse those objects across all visitor compilations. +// +// `enterExitObjectCacheNextIndex` is the index of first object in cache which is currently unused. +// It may point to the end of the cache array. +const enterExitObjectCache = []; +let enterExitObjectCacheNextIndex = 0; + +function getEnterExitObject() { + if (enterExitObjectCacheNextIndex < enterExitObjectCache.length) { + return enterExitObjectCache[enterExitObjectCacheNextIndex++]; + } + + const enterExit = { enter: null, exit: null }; + enterExitObjectCache.push(enterExit); + enterExitObjectCacheNextIndex++; + return enterExit; +} + +// Visit function arrays cache. +// +// During compilation, many arrays may be used temporarily to store multiple visit functions for same AST type. +// The functions in each array are merged into a single function in `finalizeCompiledVisitor`, +// after which these arrays aren't used again. +// +// Use this cache to reuse these arrays across each visitor compilation. +// +// `visitFnArrayCacheNextIndex` is the index of first array in cache which is currently unused. +// It may point to the end of the cache array. +const visitFnArrayCache = []; +let visitFnArrayCacheNextIndex = 0; + +function createVisitFnArray(visit1, visit2) { + if (visitFnArrayCacheNextIndex < visitFnArrayCache.length) { + const arr = visitFnArrayCache[visitFnArrayCacheNextIndex++]; + arr.push(visit1, visit2); + return arr; + } + + const arr = [visit1, visit2]; + visitFnArrayCache.push(arr); + visitFnArrayCacheNextIndex++; + return arr; +} + +/** + * Initialize compiled visitor, ready for calls to `addVisitor`. + */ +export function initCompiledVisitor() { + // Reset `compiledVisitor` array after previous compilation + for (let i = 0; i < NODE_TYPES_COUNT; i++) { + compiledVisitor[i] = null; + } + + // Reset enter+exit objects which were used in previous compilation + for (let i = 0; i < enterExitObjectCacheNextIndex; i++) { + const enterExit = enterExitObjectCache[i]; + enterExit.enter = null; + enterExit.exit = null; + } + enterExitObjectCacheNextIndex = 0; +} + +/** + * Add a visitor to compiled visitor. + * + * @param visitor - Visitor object + */ +export function addVisitorToCompiled(visitor) { + if (visitor === null || typeof visitor !== "object") { + throw new TypeError("Visitor must be an object"); + } + + // Exit if is empty visitor + const keys = Object.keys(visitor), + keysLen = keys.length; + if (keysLen === 0) return; + + hasActiveVisitors = true; + + // Populate visitors array from provided object + for (let i = 0; i < keysLen; i++) { + let name = keys[i]; + + const visitFn = visitor[name]; + if (typeof visitFn !== "function") { + throw new TypeError(`'${name}' property of visitor object is not a function`); + } + + const isExit = name.endsWith(":exit"); + if (isExit) name = name.slice(0, -5); + + const typeId = NODE_TYPE_IDS_MAP.get(name); + if (typeId === void 0) throw new Error(`Unknown node type '${name}' in visitor object`); + + const existing = compiledVisitor[typeId]; + if (typeId < LEAF_NODE_TYPES_COUNT) { + // Leaf node - store just 1 function, not enter+exit pair + if (existing === null) { + compiledVisitor[typeId] = visitFn; + } else if (Array.isArray(existing)) { + if (isExit) { + existing.push(visitFn); + } else { + // Insert before last in array in case last was enter visit function from the current rule, + // to ensure enter is called before exit. + // It could also be either an enter or exit visitor function for another rule, but the order + // rules are called in doesn't matter. We only need to make sure that a rule's exit visitor + // isn't called before enter visitor *for that same rule*. + existing.splice(existing.length - 1, 0, visitFn); + } + } else { + // Same as above, enter visitor is put to front of list to make sure enter is called before exit + compiledVisitor[typeId] = isExit + ? createVisitFnArray(existing, visitFn) + : createVisitFnArray(visitFn, existing); + mergedLeafVisitorTypeIds.push(typeId); + } + } else { + // Not leaf node - store enter+exit pair + if (existing === null) { + const enterExit = (compiledVisitor[typeId] = getEnterExitObject()); + if (isExit) { + enterExit.exit = visitFn; + } else { + enterExit.enter = visitFn; + } + } else if (isExit) { + const { exit } = existing; + if (exit === null) { + existing.exit = visitFn; + } else if (Array.isArray(exit)) { + exit.push(visitFn); + } else { + existing.exit = createVisitFnArray(exit, visitFn); + mergedExitVisitorTypeIds.push(typeId); + } + } else { + const { enter } = existing; + if (enter === null) { + existing.enter = visitFn; + } else if (Array.isArray(enter)) { + enter.push(visitFn); + } else { + existing.enter = createVisitFnArray(enter, visitFn); + mergedEnterVisitorTypeIds.push(typeId); + } + } + } + } +} + +/** + * Finalize compiled visitor. + * + * After calling this function, `compiledVisitor` is ready to be used to walk the AST. + * + * @returns {boolean} - `true` if compiled visitor visits at least 1 AST type + */ +export function finalizeCompiledVisitor() { + if (hasActiveVisitors === false) return false; + + // Merge visit functions for node types which have multiple visitors from different rules, + // or enter+exit functions for leaf nodes + for (let i = mergedLeafVisitorTypeIds.length - 1; i >= 0; i--) { + const typeId = mergedLeafVisitorTypeIds[i]; + compiledVisitor[typeId] = mergeVisitFns(compiledVisitor[typeId]); + } + + for (let i = mergedEnterVisitorTypeIds.length - 1; i >= 0; i--) { + const typeId = mergedEnterVisitorTypeIds[i]; + const enterExit = compiledVisitor[typeId]; + enterExit.enter = mergeVisitFns(enterExit.enter); + } + + for (let i = mergedExitVisitorTypeIds.length - 1; i >= 0; i--) { + const typeId = mergedExitVisitorTypeIds[i]; + const enterExit = compiledVisitor[typeId]; + enterExit.exit = mergeVisitFns(enterExit.exit); + } + + // Reset state, ready for next time + mergedLeafVisitorTypeIds.length = 0; + mergedEnterVisitorTypeIds.length = 0; + mergedExitVisitorTypeIds.length = 0; + + // Note: Visit function arrays have been emptied in `mergeVisitFns`, so all arrays in `visitFnArrayCache` + // are now empty and ready for reuse. We just need to reset the index. + visitFnArrayCacheNextIndex = 0; + + hasActiveVisitors = false; + + return true; +} + +/** + * Merge array of visit functions into a single function, which calls each of input functions in turn. + * + * The array passed is cleared (length set to 0), so the array can be reused. + * + * The merged function is statically defined and does not contain a loop, to hopefully allow + * JS engine to heavily optimize it. + * + * `mergers` contains pre-defined functions to merge up to 5 visit functions. + * Merger functions for merging more than 5 visit functions are created dynamically on demand. + * + * @param visitFns - Array of visit functions + * @returns Function which calls all of `visitFns` in turn. + */ +function mergeVisitFns(visitFns) { + const numVisitFns = visitFns.length; + + // Get or create merger for merging `numVisitFns` functions + let merger; + if (mergers.length <= numVisitFns) { + while (mergers.length < numVisitFns) { + mergers.push(null); + } + merger = createMerger(numVisitFns); + mergers.push(merger); + } else { + merger = mergers[numVisitFns]; + if (merger === null) merger = mergers[numVisitFns] = createMerger(numVisitFns); + } + + // Merge functions + const mergedFn = merger(...visitFns); + + // Empty `visitFns` array, so it can be reused + visitFns.length = 0; + + return mergedFn; +} + +/** + * Create a merger function that merges `fnCount` functions. + * + * @param fnCount - Number of functions to be merged + * @returns Function to merge `fnCount` functions + */ +function createMerger(fnCount) { + const args = []; + let body = "return node=>{"; + for (let i = 1; i <= fnCount; i++) { + args.push(`visit${i}`); + body += `visit${i}(node);`; + } + body += "}"; + args.push(body); + // oxlint-disable-next-line typescript/no-implied-eval + return new Function(...args); +} + +// Pre-defined mergers for merging up to 5 functions +const mergers = [ + null, // No merger for 0 functions + null, // No merger for 1 function + (visit1, visit2) => (node) => { + visit1(node); + visit2(node); + }, + (visit1, visit2, visit3) => (node) => { + visit1(node); + visit2(node); + visit3(node); + }, + (visit1, visit2, visit3, visit4) => (node) => { + visit1(node); + visit2(node); + visit3(node); + visit4(node); + }, + (visit1, visit2, visit3, visit4, visit5) => (node) => { + visit1(node); + visit2(node); + visit3(node); + visit4(node); + visit5(node); + }, +]; diff --git a/tools/ui/node_modules/oxc-parser/src-js/wasm.js b/tools/ui/node_modules/oxc-parser/src-js/wasm.js new file mode 100644 index 0000000000000000000000000000000000000000..6b56063b8aa2ba9416fa489f710d193ee4353969 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/wasm.js @@ -0,0 +1,11 @@ +export * from "@oxc-parser/binding-wasm32-wasi"; +import * as bindings from "@oxc-parser/binding-wasm32-wasi"; +import { wrap } from "./wrap.js"; + +export async function parse(...args) { + return wrap(await bindings.parse(...args)); +} + +export function parseSync(filename, sourceText, options) { + return wrap(bindings.parseSync(filename, sourceText, options)); +} diff --git a/tools/ui/node_modules/oxc-parser/src-js/webcontainer-fallback.cjs b/tools/ui/node_modules/oxc-parser/src-js/webcontainer-fallback.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c65c53210dbad2a613303bd5170610cbbf71d1e9 --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/webcontainer-fallback.cjs @@ -0,0 +1,21 @@ +const fs = require("node:fs"); +const childProcess = require("node:child_process"); + +const pkg = JSON.parse(fs.readFileSync(require.resolve("oxc-parser/package.json"), "utf-8")); +const { version } = pkg; +const baseDir = `/tmp/oxc-parser-${version}`; +const bindingEntry = `${baseDir}/node_modules/@oxc-parser/binding-wasm32-wasi/parser.wasi.cjs`; + +if (!fs.existsSync(bindingEntry)) { + fs.rmSync(baseDir, { recursive: true, force: true }); + fs.mkdirSync(baseDir, { recursive: true }); + const bindingPkg = `@oxc-parser/binding-wasm32-wasi@${version}`; + // oxlint-disable-next-line no-console + console.log(`[oxc-parser] Downloading ${bindingPkg} on WebContainer...`); + childProcess.execFileSync("pnpm", ["i", bindingPkg], { + cwd: baseDir, + stdio: "inherit", + }); +} + +module.exports = require(bindingEntry); diff --git a/tools/ui/node_modules/oxc-parser/src-js/wrap.js b/tools/ui/node_modules/oxc-parser/src-js/wrap.js new file mode 100644 index 0000000000000000000000000000000000000000..a8a660c092f161255503fd685346a16e70cc466d --- /dev/null +++ b/tools/ui/node_modules/oxc-parser/src-js/wrap.js @@ -0,0 +1,57 @@ +export function wrap(result) { + let program, module, comments, errors; + return { + get program() { + if (!program) program = jsonParseAst(result.program); + return program; + }, + get module() { + if (!module) module = result.module; + return module; + }, + get comments() { + if (!comments) comments = result.comments; + return comments; + }, + get errors() { + if (!errors) errors = result.errors; + return errors; + }, + }; +} + +// Used by `napi/playground/scripts/patch.js`. +// +// Set `value` field of `Literal`s which are `BigInt`s or `RegExp`s. +// +// Returned JSON contains an array `fixes` with paths to these nodes +// e.g. for `123n; foo(/xyz/)`, `fixes` will be +// `[["body", 0, "expression"], ["body", 1, "expression", "arguments", 2]]`. +// +// Walk down the AST to these nodes and alter them. +// Compiling the list of fixes on Rust side avoids having to do a full AST traversal on JS side +// to locate the likely very few `Literal`s which need fixing. +export function jsonParseAst(programJson) { + const { node: program, fixes } = JSON.parse(programJson); + for (const fixPath of fixes) { + applyFix(program, fixPath); + } + return program; +} + +function applyFix(program, fixPath) { + let node = program; + for (const key of fixPath) { + node = node[key]; + } + + if (node.bigint) { + node.value = BigInt(node.bigint); + } else { + try { + node.value = RegExp(node.regex.pattern, node.regex.flags); + } catch { + // Invalid regexp, or valid regexp using syntax not supported by this version of NodeJS + } + } +} diff --git a/tools/ui/node_modules/oxc-resolver/README.md b/tools/ui/node_modules/oxc-resolver/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a15dee218e56839b6ff8f43bb7568ac3547e1fe4 --- /dev/null +++ b/tools/ui/node_modules/oxc-resolver/README.md @@ -0,0 +1,366 @@ +

+
+
+
+ + + + Oxc logo + + +
+
+
+

+ +
+ +[![Crates.io][crates-badge]][crates-url] +[![npmjs.com][npm-badge]][npm-url] + +[![Docs.rs][docs-badge]][docs-url] +[![Build Status][ci-badge]][ci-url] +[![Code Coverage][code-coverage-badge]][code-coverage-url] +[![CodSpeed Badge][codspeed-badge]][codspeed-url] +[![Sponsors][sponsors-badge]][sponsors-url] +[![Discord chat][discord-badge]][discord-url] +[![MIT licensed][license-badge]][license-url] + +
+ +# Oxc Resolver + +Rust port of [enhanced-resolve], [tsconfig-paths-webpack-plugin] and [tsconfck] + +- Released on [crates.io](https://crates.io/crates/oxc_resolver) and [npm](https://npmx.dev/package/oxc-resolver). +- Implements the [ESM](https://nodejs.org/api/esm.html#resolution-algorithm) and [CommonJS](https://nodejs.org/api/modules.html#all-together) module resolution algorithm specification. +- Built-in [tsconfig-paths-webpack-plugin] + - support extending tsconfig defined in `tsconfig.extends` + - support paths alias defined in `tsconfig.compilerOptions.paths` + - support project references defined `tsconfig.references` + - support [template variable ${configDir} for substitution of config files directory path](https://github.com/microsoft/TypeScript/pull/58042) +- Built-in tsconfig discovery ([tsconfck]) +- Supports in-memory file system via the `FileSystem` trait. +- Contains `tracing` instrumentation. + +## Usage + +### npm package + +See index.d.ts for `resolveSync` and `ResolverFactory` API. + +Quick example: + +```javascript +import assert from "assert"; +import path from "path"; +import resolve, { ResolverFactory } from "./index.js"; + +// `resolve` +assert(resolve.sync(process.cwd(), "./index.js").path, path.join(cwd, "index.js")); + +// `ResolverFactory` +const resolver = new ResolverFactory(); +assert(resolver.sync(process.cwd(), "./index.js").path, path.join(cwd, "index.js")); +``` + +#### File-based Resolution + +For file-based resolution with automatic tsconfig discovery, use `resolveFileSync` or `resolveFileAsync`: + +```javascript +const resolver = new ResolverFactory(); + +// Resolves from a file path (not directory) +const result = resolver.resolveFileSync("/path/to/file.ts", "./module"); + +// Async version +const result = await resolver.resolveFileAsync("/path/to/file.ts", "./module"); +``` + +**Key Differences:** + +- `sync(directory, specifier)` - Takes a **directory path**, uses manually configured tsconfig if provided +- `resolveFileSync(file, specifier)` - Takes a **file path**, automatically discovers tsconfig.json by traversing parent directories + +**Why use `resolveFileSync`?** + +When resolving from a specific file (e.g., in bundlers, linters, or language servers), `resolveFileSync` automatically finds the correct `tsconfig.json` by: + +- Traversing parent directories from the file location +- Respecting TypeScript project references +- Honoring `include`, `exclude`, and `files` fields to determine which tsconfig applies +- Ensuring tsconfig `paths` aliases work correctly based on the file's context + +#### Supports WASM + +See https://stackblitz.com/edit/oxc-resolver for usage example. + +### Rust + +See [docs.rs/oxc_resolver](https://docs.rs/oxc_resolver/latest/oxc_resolver). + +### [Yarn Plug'n'Play](https://yarnpkg.com/features/pnp) + +- For node.js, yarn pnp should work without any configuration, given the following conditions: + - the program is called with the `yarn` command, where the value [`process.versions.pnp`](https://yarnpkg.com/advanced/pnpapi#processversionspnp) is set. + - `.pnp.cjs` manifest file exists in the closest directory, searched from the current working directory, + - no multi-project setup, per second bullet point in [FIND_PNP_MANIFEST](https://yarnpkg.com/advanced/pnp-spec#find_pnp_manifest) + +## Terminology + +### `directory` + +An **absolute** path to a directory where the specifier is resolved against. + +For CommonJS modules, it is the `__dirname` variable that contains the absolute path to the folder containing current module. + +For ECMAScript modules, it is the value of `import.meta.url`. + +Behavior is undefined when given a path to a file. + +### `specifier` + +The string passed to `require` or `import`, i.e. `require("specifier")` or `import "specifier"` + +## Errors and Trouble Shooting + +- `Error: Package subpath '.' is not defined by "exports" in` - occurs when resolving without `conditionNames`. + +## Configuration + +The following usages apply to both Rust and Node.js; the code snippets are written in JavaScript. + +To handle the `exports` field in `package.json`, ESM and CJS need to be differentiated. + +### ESM + +Per [ESM Resolution algorithm](https://nodejs.org/api/esm.html#resolution-and-loading-algorithm) + +> defaultConditions is the conditional environment name array, ["node", "import"]. + +This means when the caller is an ESM import (`import "module"`), resolve options should be + +```javascript +{ + "conditionNames": ["node", "import"] +} +``` + +### CJS + +Per [CJS Resolution algorithm](https://nodejs.org/api/modules.html#all-together) + +> LOAD_PACKAGE_EXPORTS(X, DIR) +> +> 5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH, +> `package.json` "exports", ["node", "require"]) defined in the ESM resolver. + +This means when the caller is a CJS require (`require("module")`), resolve options should be + +```javascript +{ + "conditionNames": ["node", "require"] +} +``` + +### Cache + +To support both CJS and ESM with the same cache: + +```javascript +const esmResolver = new ResolverFactory({ + conditionNames: ["node", "import"], +}); + +const cjsResolver = esmResolver.cloneWithOptions({ + conditionNames: ["node", "require"], +}); +``` + +### Browser Field + +From this [non-standard spec](https://github.com/defunctzombie/package-browser-field-spec): + +> The `browser` field is provided to JavaScript bundlers or component tools when packaging modules for client side use. + +The option is + +```javascript +{ + "aliasFields": ["browser"] +} +``` + +### Main Field + +```javascript +{ + "mainFields": ["module", "main"] +} +``` + +Quoting esbuild's documentation: + +- `main` - This is [the standard field](https://docs.npmjs.com/files/package.json#main) for all packages that are meant to be used with node. The name main is hard-coded in to node's module resolution logic itself. Because it's intended for use with node, it's reasonable to expect that the file path in this field is a CommonJS-style module. +- `module` - This field came from a [proposal](https://github.com/dherman/defense-of-dot-js/blob/f31319be735b21739756b87d551f6711bd7aa283/proposal.md) for how to integrate ECMAScript modules into node. Because of this, it's reasonable to expect that the file path in this field is an ECMAScript-style module. This proposal wasn't adopted by node (node uses "type": "module" instead) but it was adopted by major bundlers because ECMAScript-style modules lead to better tree shaking, or dead code removal. +- `browser` - This field came from a [proposal](https://gist.github.com/defunctzombie/4339901/49493836fb873ddaa4b8a7aa0ef2352119f69211) that allows bundlers to replace node-specific files or modules with their browser-friendly versions. It lets you specify an alternate browser-specific entry point. Note that it is possible for a package to use both the browser and module field together (see the note below). + +## Options + +The following options are aligned with [enhanced-resolve], and is implemented for Rust crate usage. + +See [index.d.ts](https://github.com/oxc-project/oxc-resolver/blob/main/napi/index.d.ts) for Node.js usage. + +| Field | Default | Description | +| ------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| alias | {} | A hash map of module alias configurations | +| aliasFields | [] | A list of alias fields in description files | +| extensionAlias | {} | An object which maps extension to extension aliases | +| conditionNames | [] | A list of exports field condition names | +| enforceExtension | false | Enforce that an extension from extensions must be used | +| exportsFields | ["exports"] | A list of exports fields in description files | +| extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files | +| fallback | {} | Same as `alias`, but only used if default resolving fails | +| fileSystem | | The file system which should be used | +| fullySpecified | false | Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests) | +| mainFields | ["main"] | A list of main fields in description files | +| mainFiles | ["index"] | A list of main files in directories | +| modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name. Absolute `NODE_PATH` entries are appended automatically when set. | +| resolveToContext | false | Resolve to a context instead of a file | +| preferRelative | false | Prefer to resolve module requests as relative request and fallback to resolving as module | +| preferAbsolute | false | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots | +| restrictions | [] | A list of resolve restrictions | +| roots | [] | A list of root paths | +| symlinks | true | Whether to resolve symlinks to their symlinked location | +| allowPackageExportsInDirectoryResolve | false | Allow `exports` field in `require('../directory')`. Not part of `enhanced-resolve`. | + +### TypeScript Configuration + +| Field | Default | Description | +| ------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| tsconfig | None | TypeScript related config for resolver | +| tsconfig.configFile | | A relative path to the tsconfig file based on `cwd`, or an absolute path to the tsconfig file. | +| tsconfig.references | `[]` | - 'auto': inherits from TypeScript config
- `string []`: relative path (based on directory of the referencing tsconfig file) or absolute path of referenced project's tsconfig | + +### Unimplemented Options + +| Field | Default | Description | +| ---------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| descriptionFiles | ["package.json"] | A list of description files to read from | +| cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with `path` and `request` properties. | +| cacheWithContext | true | If unsafe cache is enabled, includes `request.context` in the cache key | +| plugins | [] | A list of additional resolve plugins which should be applied | +| resolver | undefined | A prepared Resolver to which the plugins are attached | +| unsafeCache | false | Use this cache object to unsafely cache the successful requests | + +## Debugging + +The following environment variable emits tracing information for the `oxc_resolver::resolve` function. + +e.g. + +``` +2024-06-11T07:12:20.003537Z DEBUG oxc_resolver: options: ResolveOptions { ... }, path: "...", specifier: "...", ret: "..." + at /path/to/oxc_resolver-1.8.1/src/lib.rs:212 + in oxc_resolver::resolve with path: "...", specifier: "..." +``` + +The input values are `options`, `path` and `specifier`, the returned value is `ret`. + +### NAPI + +``` +OXC_LOG=DEBUG your_program +``` + +### Rolldown + +```bash +RD_LOG='oxc_resolver' rolldown build +``` + +## Test + +Tests are ported from + +- [enhanced-resolve](https://github.com/webpack/enhanced-resolve/tree/main/test) +- [tsconfig-path](https://github.com/dividab/tsconfig-paths/blob/master/src/__tests__/data/match-path-data.ts) and [parcel-resolver](https://github.com/parcel-bundler/parcel/tree/v2/packages/utils/node-resolver-core/test/fixture/tsconfig) for tsconfig-paths + +Test cases are located in `./src/tests`, fixtures are located in `./tests` + +- [x] alias.test.js +- [x] browserField.test.js +- [x] dependencies.test.js +- [x] exportsField.test.js +- [x] extension-alias.test.js +- [x] extensions.test.js +- [x] fallback.test.js +- [x] fullSpecified.test.js +- [x] identifier.test.js (see unit test in `crates/oxc_resolver/src/request.rs`) +- [x] importsField.test.js +- [x] incorrect-description-file.test.js (need to add ctx.fileDependencies) +- [x] missing.test.js +- [x] path.test.js (see unit test in `crates/oxc_resolver/src/path.rs`) +- [ ] plugins.test.js +- [ ] pnp.test.js +- [x] resolve.test.js +- [x] restrictions.test.js (partially done, regex is not supported yet) +- [x] roots.test.js +- [x] scoped-packages.test.js +- [x] simple.test.js +- [x] symlink.test.js + +Irrelevant tests + +- CachedInputFileSystem.test.js +- SyncAsyncFileSystemDecorator.test.js +- forEachBail.test.js +- getPaths.test.js +- pr-53.test.js +- unsafe-cache.test.js +- yield.test.js + +## [Sponsored By](https://github.com/sponsors/Boshen) + +

+ + My sponsors + +

+ +## 📖 License + +`oxc_resolver` is free and open-source software licensed under the [MIT License](./LICENSE). + +Oxc partially copies code from the following projects. + +| Project | License | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| [webpack/enhanced-resolve](https://github.com/webpack/enhanced-resolve) | [MIT](https://github.com/webpack/enhanced-resolve/blob/main/LICENSE) | +| [dividab/tsconfig-paths](https://github.com/dividab/tsconfig-paths) | [MIT](https://github.com/dividab/tsconfig-paths/blob/master/LICENSE) | +| [parcel-bundler/parcel](https://github.com/parcel-bundler/parcel) | [MIT](https://github.com/parcel-bundler/parcel/blob/v2/LICENSE) | +| [tmccombs/json-comments-rs](https://github.com/tmccombs/json-comments-rs) | [Apache 2.0](https://github.com/tmccombs/json-comments-rs/blob/main/LICENSE) | +| [dominikg/tsconfck](https://github.com/dominikg/tsconfck) | [MIT](https://github.com/dominikg/tsconfck/blob/main/packages/tsconfck/LICENSE) | + +[enhanced-resolve]: https://github.com/webpack/enhanced-resolve +[tsconfig-paths-webpack-plugin]: https://github.com/dividab/tsconfig-paths-webpack-plugin +[discord-badge]: https://img.shields.io/discord/1079625926024900739?logo=discord&label=Discord +[discord-url]: https://discord.gg/9uXCAwqQZW +[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg +[license-url]: https://github.com/oxc-project/oxc-resolver/blob/main/LICENSE +[ci-badge]: https://github.com/oxc-project/oxc-resolver/actions/workflows/ci.yml/badge.svg?event=push&branch=main +[ci-url]: https://github.com/oxc-project/oxc-resolver/actions/workflows/ci.yml?query=event%3Apush+branch%3Amain +[code-coverage-badge]: https://codecov.io/github/oxc-project/oxc-resolver/branch/main/graph/badge.svg +[code-coverage-url]: https://codecov.io/gh/oxc-project/oxc-resolver +[sponsors-badge]: https://img.shields.io/github/sponsors/Boshen +[sponsors-url]: https://github.com/sponsors/Boshen +[codspeed-badge]: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json +[codspeed-url]: https://codspeed.io/oxc-project/oxc-resolver +[crates-badge]: https://img.shields.io/crates/dr/oxc_resolver +[crates-url]: https://crates.io/crates/oxc_resolver +[docs-badge]: https://img.shields.io/docsrs/oxc_resolver +[docs-url]: https://docs.rs/oxc_resolver/latest/oxc_resolver +[npm-badge]: https://img.shields.io/npm/dw/oxc-resolver?label=npm +[npm-url]: https://npmx.dev/package/oxc-resolver +[tsconfck]: https://github.com/dominikg/tsconfck diff --git a/tools/ui/node_modules/oxc-resolver/browser.js b/tools/ui/node_modules/oxc-resolver/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..e0a24e7e14c315b3e6b591a86290e59ef9438fa4 --- /dev/null +++ b/tools/ui/node_modules/oxc-resolver/browser.js @@ -0,0 +1 @@ +export * from '@oxc-resolver/binding-wasm32-wasi' diff --git a/tools/ui/node_modules/oxc-resolver/index.d.ts b/tools/ui/node_modules/oxc-resolver/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbdb66cf05d9c0568619eb6a0c540f4d0d09af31 --- /dev/null +++ b/tools/ui/node_modules/oxc-resolver/index.d.ts @@ -0,0 +1,311 @@ +/* auto-generated by NAPI-RS */ +/* eslint-disable */ +export declare class ResolverFactory { + constructor(options?: NapiResolveOptions | undefined | null) + static default(): ResolverFactory + /** Clone the resolver using the same underlying cache. */ + cloneWithOptions(options: NapiResolveOptions): ResolverFactory + /** + * Clear the underlying cache. + * + * Warning: The caller must ensure that there're no ongoing resolution operations when calling this method. Otherwise, it may cause those operations to return an incorrect result. + */ + clearCache(): void + /** Synchronously resolve `specifier` at an absolute path to a `directory`. */ + sync(directory: string, request: string): ResolveResult + /** Asynchronously resolve `specifier` at an absolute path to a `directory`. */ + async(directory: string, request: string): Promise + /** + * Synchronously resolve `specifier` at an absolute path to a `file`. + * + * This method automatically discovers tsconfig.json by traversing parent directories. + */ + resolveFileSync(file: string, request: string): ResolveResult + /** + * Asynchronously resolve `specifier` at an absolute path to a `file`. + * + * This method automatically discovers tsconfig.json by traversing parent directories. + */ + resolveFileAsync(file: string, request: string): Promise + /** + * Synchronously resolve `specifier` for TypeScript declaration files. + * + * `file` is the absolute path to the containing file. + * Uses TypeScript's `moduleResolution: "bundler"` algorithm. + */ + resolveDtsSync(file: string, request: string): ResolveResult + /** + * Asynchronously resolve `specifier` for TypeScript declaration files. + * + * `file` is the absolute path to the containing file. + * Uses TypeScript's `moduleResolution: "bundler"` algorithm. + */ + resolveDtsAsync(file: string, request: string): Promise +} + +/** Node.js builtin module when `Options::builtin_modules` is enabled. */ +export interface Builtin { + /** + * Resolved module. + * + * Always prefixed with "node:" in compliance with the ESM specification. + */ + resolved: string + /** + * Whether the request was prefixed with `node:` or not. + * `fs` -> `false`. + * `node:fs` returns `true`. + */ + isRuntimeModule: boolean +} + +export declare const enum EnforceExtension { + Auto = 0, + Enabled = 1, + Disabled = 2 +} + +export declare const enum ModuleType { + Module = 'module', + CommonJs = 'commonjs', + Json = 'json', + Wasm = 'wasm', + Addon = 'addon' +} + +/** + * Module Resolution Options + * + * Options are directly ported from [enhanced-resolve](https://github.com/webpack/enhanced-resolve#resolver-options). + * + * See [webpack resolve](https://webpack.js.org/configuration/resolve/) for information and examples + */ +export interface NapiResolveOptions { + /** + * Discover tsconfig automatically or use the specified tsconfig.json path. + * + * Default `None` + */ + tsconfig?: 'auto' | TsconfigOptions + /** + * Alias for [ResolveOptions::alias] and [ResolveOptions::fallback]. + * + * For the second value of the tuple, `None -> AliasValue::Ignore`, Some(String) -> + * AliasValue::Path(String)` + * Create aliases to import or require certain modules more easily. + * A trailing $ can also be added to the given object's keys to signify an exact match. + * Default `{}` + */ + alias?: Record> + /** + * A list of alias fields in description files. + * Specify a field, such as `browser`, to be parsed according to [this specification](https://github.com/defunctzombie/package-browser-field-spec). + * Can be a path to json object such as `["path", "to", "exports"]`. + * + * Default `[]` + */ + aliasFields?: (string | string[])[] + /** + * Condition names for exports field which defines entry points of a package. + * The key order in the exports field is significant. During condition matching, earlier entries have higher priority and take precedence over later entries. + * + * Default `[]` + */ + conditionNames?: Array + /** + * If true, it will not allow extension-less files. + * So by default `require('./foo')` works if `./foo` has a `.js` extension, + * but with this enabled only `require('./foo.js')` will work. + * + * Default to `true` when [ResolveOptions::extensions] contains an empty string. + * Use `Some(false)` to disable the behavior. + * See + * + * Default None, which is the same as `Some(false)` when the above empty rule is not applied. + */ + enforceExtension?: EnforceExtension + /** + * A list of exports fields in description files. + * Can be a path to json object such as `["path", "to", "exports"]`. + * + * Default `[["exports"]]`. + */ + exportsFields?: (string | string[])[] + /** + * Fields from `package.json` which are used to provide the internal requests of a package + * (requests starting with # are considered internal). + * + * Can be a path to a JSON object such as `["path", "to", "imports"]`. + * + * Default `[["imports"]]`. + */ + importsFields?: (string | string[])[] + /** + * An object which maps extension to extension aliases. + * + * Default `{}` + */ + extensionAlias?: Record> + /** + * Attempt to resolve these extensions in order. + * If multiple files share the same name but have different extensions, + * will resolve the one with the extension listed first in the array and skip the rest. + * + * Default `[".js", ".json", ".node"]` + */ + extensions?: Array + /** + * Redirect module requests when normal resolving fails. + * + * Default `{}` + */ + fallback?: Record> + /** + * Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests). + * + * See also webpack configuration [resolve.fullySpecified](https://webpack.js.org/configuration/module/#resolvefullyspecified) + * + * Default `false` + */ + fullySpecified?: boolean + /** + * A list of main fields in description files + * + * Default `["main"]`. + */ + mainFields?: string | string[] + /** + * The filename to be used while resolving directories. + * + * Default `["index"]` + */ + mainFiles?: Array + /** + * A list of directories to resolve modules from, can be absolute path or folder name. + * + * Default `["node_modules"]` + */ + modules?: string | string[] + /** + * Resolve to a context instead of a file. + * + * Default `false` + */ + resolveToContext?: boolean + /** + * Prefer to resolve module requests as relative requests instead of using modules from node_modules directories. + * + * Default `false` + */ + preferRelative?: boolean + /** + * Prefer to resolve server-relative urls as absolute paths before falling back to resolve in ResolveOptions::roots. + * + * Default `false` + */ + preferAbsolute?: boolean + /** + * A list of resolve restrictions to restrict the paths that a request can be resolved on. + * + * Default `[]` + */ + restrictions?: Array + /** + * A list of directories where requests of server-relative URLs (starting with '/') are resolved. + * On non-Windows systems these requests are resolved as an absolute path first. + * + * Default `[]` + */ + roots?: Array + /** + * Whether to resolve symlinks to their symlinked location. + * When enabled, symlinked resources are resolved to their real path, not their symlinked location. + * Note that this may cause module resolution to fail when using tools that symlink packages (like npm link). + * + * Default `true` + */ + symlinks?: boolean + /** + * Whether to read the `NODE_PATH` environment variable and append its entries to `modules`. + * + * `NODE_PATH` is a deprecated Node.js feature that is not part of ESM resolution. + * Set this to `false` to disable the behavior. + * + * Default `true` + */ + nodePath?: boolean + /** + * Whether to parse [module.builtinModules](https://nodejs.org/api/module.html#modulebuiltinmodules) or not. + * For example, "zlib" will throw [crate::ResolveError::Builtin] when set to true. + * + * Default `false` + */ + builtinModules?: boolean + /** + * Resolve [ResolveResult::moduleType]. + * + * Default `false` + */ + moduleType?: boolean + /** + * Allow `exports` field in `require('../directory')`. + * + * This is not part of the spec but some vite projects rely on this behavior. + * See + * * + * * + * + * Default: `false` + */ + allowPackageExportsInDirectoryResolve?: boolean +} + +export interface ResolveResult { + path?: string + error?: string + builtin?: Builtin + /** + * Module type for this path. + * + * Enable with `ResolveOptions#moduleType`. + * + * The module type is computed `ESM_FILE_FORMAT` from the [ESM resolution algorithm specification](https://nodejs.org/docs/latest/api/esm.html#resolution-algorithm-specification). + * + * The algorithm uses the file extension or finds the closest `package.json` with the `type` field. + */ + moduleType?: ModuleType + /** `package.json` path for the given module. */ + packageJsonPath?: string +} + +/** + * Alias Value for [ResolveOptions::alias] and [ResolveOptions::fallback]. + * Use struct because napi don't support structured union now + */ +export interface Restriction { + path?: string + regex?: string +} + +export declare function sync(path: string, request: string): ResolveResult + +/** + * Tsconfig Options + * + * Derived from [tsconfig-paths-webpack-plugin](https://github.com/dividab/tsconfig-paths-webpack-plugin#options) + */ +export interface TsconfigOptions { + /** + * Allows you to specify where to find the TypeScript configuration file. + * You may provide + * * a relative path to the configuration file. It will be resolved relative to cwd. + * * an absolute path to the configuration file. + */ + configFile: string + /** + * Support for Typescript Project References. + * + * * `'auto'`: use the `references` field from tsconfig of `config_file`. + */ + references?: 'auto' +} diff --git a/tools/ui/node_modules/oxc-resolver/index.js b/tools/ui/node_modules/oxc-resolver/index.js new file mode 100644 index 0000000000000000000000000000000000000000..358e55b97f78b8058e7454f2773b6d410281186a --- /dev/null +++ b/tools/ui/node_modules/oxc-resolver/index.js @@ -0,0 +1,594 @@ +// prettier-ignore +/* eslint-disable */ +// @ts-nocheck +/* auto-generated by NAPI-RS */ + +const { readFileSync } = require('node:fs') +let nativeBinding = null +const loadErrors = [] + +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} + +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') + +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (typeof process.report?.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return true + } + } + return false +} + +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./resolver.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-android-arm64') + const bindingPackageVersion = require('@oxc-resolver/binding-android-arm64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./resolver.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-android-arm-eabi') + const bindingPackageVersion = require('@oxc-resolver/binding-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if (process.config?.variables?.shlib_suffix === 'dll.a' || process.config?.variables?.node_target_type === 'shared_library') { + try { + return require('./resolver.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-win32-x64-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./resolver.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-win32-x64-msvc') + const bindingPackageVersion = require('@oxc-resolver/binding-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./resolver.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-win32-ia32-msvc') + const bindingPackageVersion = require('@oxc-resolver/binding-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./resolver.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-win32-arm64-msvc') + const bindingPackageVersion = require('@oxc-resolver/binding-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./resolver.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-darwin-universal') + const bindingPackageVersion = require('@oxc-resolver/binding-darwin-universal/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./resolver.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-darwin-x64') + const bindingPackageVersion = require('@oxc-resolver/binding-darwin-x64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./resolver.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-darwin-arm64') + const bindingPackageVersion = require('@oxc-resolver/binding-darwin-arm64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./resolver.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-freebsd-x64') + const bindingPackageVersion = require('@oxc-resolver/binding-freebsd-x64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./resolver.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-freebsd-arm64') + const bindingPackageVersion = require('@oxc-resolver/binding-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./resolver.linux-x64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-x64-musl') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./resolver.linux-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-x64-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm64') { + if (isMusl()) { + try { + return require('./resolver.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-arm64-musl') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./resolver.linux-arm64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-arm64-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./resolver.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-arm-musleabihf') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./resolver.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-arm-gnueabihf') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./resolver.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-loong64-musl') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./resolver.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-loong64-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./resolver.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-riscv64-musl') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./resolver.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-riscv64-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./resolver.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-ppc64-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./resolver.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-linux-s390x-gnu') + const bindingPackageVersion = require('@oxc-resolver/binding-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./resolver.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-openharmony-arm64') + const bindingPackageVersion = require('@oxc-resolver/binding-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./resolver.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-openharmony-x64') + const bindingPackageVersion = require('@oxc-resolver/binding-openharmony-x64/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./resolver.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@oxc-resolver/binding-openharmony-arm') + const bindingPackageVersion = require('@oxc-resolver/binding-openharmony-arm/package.json').version + if (bindingPackageVersion !== '11.20.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 11.20.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +nativeBinding = requireNative() + +if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { + let wasiBinding = null + let wasiBindingError = null + try { + wasiBinding = require('./resolver.wasi.cjs') + nativeBinding = wasiBinding + } catch (err) { + if (process.env.NAPI_RS_FORCE_WASI) { + wasiBindingError = err + } + } + if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { + try { + wasiBinding = require('@oxc-resolver/binding-wasm32-wasi') + nativeBinding = wasiBinding + } catch (err) { + if (process.env.NAPI_RS_FORCE_WASI) { + if (!wasiBindingError) { + wasiBindingError = err + } else { + wasiBindingError.cause = err + } + loadErrors.push(err) + } + } + } + if (process.env.NAPI_RS_FORCE_WASI === 'error' && !wasiBinding) { + const error = new Error('WASI binding not found and NAPI_RS_FORCE_WASI is set to error') + error.cause = wasiBindingError + throw error + } +} + +if (!nativeBinding && globalThis.process?.versions?.["webcontainer"]) { + try { + nativeBinding = require('./webcontainer-fallback.js'); + } catch (err) { + loadErrors.push(err) + } +} + +if (!nativeBinding) { + if (loadErrors.length > 0) { + throw new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + { + cause: loadErrors.reduce((err, cur) => { + cur.cause = err + return cur + }), + }, + ) + } + throw new Error(`Failed to load native binding`) +} + +module.exports = nativeBinding +module.exports.ResolverFactory = nativeBinding.ResolverFactory +module.exports.EnforceExtension = nativeBinding.EnforceExtension +module.exports.ModuleType = nativeBinding.ModuleType +module.exports.sync = nativeBinding.sync + +if (process.versions.pnp) { + process.env.OXC_RESOLVER_YARN_PNP = '1' +} diff --git a/tools/ui/node_modules/oxc-resolver/package.json b/tools/ui/node_modules/oxc-resolver/package.json new file mode 100644 index 0000000000000000000000000000000000000000..73c0cf47d7b8bdbf614d464dd8bfc748fec30c42 --- /dev/null +++ b/tools/ui/node_modules/oxc-resolver/package.json @@ -0,0 +1,96 @@ +{ + "name": "oxc-resolver", + "version": "11.20.0", + "description": "Oxc Resolver Node API", + "homepage": "https://oxc.rs", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/oxc-project/oxc-resolver.git" + }, + "funding": { + "url": "https://github.com/sponsors/Boshen" + }, + "files": [ + "browser.js", + "index.d.ts", + "index.js", + "webcontainer-fallback.js" + ], + "main": "index.js", + "browser": "browser.js", + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "prepare": "vp config", + "fmt": "vp fmt", + "test": "vp test run -r ./napi", + "build:debug": "napi build --platform --manifest-path napi/Cargo.toml", + "build": "vp run build:debug --features allocator --release", + "postbuild:debug": "node napi/patch.mjs" + }, + "devDependencies": { + "@emnapi/core": "^1.9.2", + "@emnapi/runtime": "^1.9.2", + "@napi-rs/cli": "^3.6.1", + "@napi-rs/wasm-runtime": "^1.1.3", + "@types/node": "^25.0.8", + "emnapi": "^1.9.2", + "typescript": "^6.0.0", + "vite-plus": "catalog:" + }, + "napi": { + "binaryName": "resolver", + "packageName": "@oxc-resolver/binding", + "targets": [ + "aarch64-apple-darwin", + "aarch64-linux-android", + "aarch64-pc-windows-msvc", + "aarch64-unknown-linux-gnu", + "aarch64-unknown-linux-musl", + "aarch64-unknown-linux-ohos", + "armv7-linux-androideabi", + "armv7-unknown-linux-gnueabihf", + "armv7-unknown-linux-musleabihf", + "powerpc64le-unknown-linux-gnu", + "riscv64gc-unknown-linux-gnu", + "riscv64gc-unknown-linux-musl", + "s390x-unknown-linux-gnu", + "wasm32-wasip1-threads", + "x86_64-apple-darwin", + "x86_64-pc-windows-msvc", + "x86_64-unknown-freebsd", + "x86_64-unknown-linux-gnu", + "x86_64-unknown-linux-musl" + ], + "wasm": { + "browser": { + "fs": true + } + } + }, + "packageManager": "pnpm@11.0.4", + "optionalDependencies": { + "@oxc-resolver/binding-darwin-arm64": "11.20.0", + "@oxc-resolver/binding-android-arm64": "11.20.0", + "@oxc-resolver/binding-win32-arm64-msvc": "11.20.0", + "@oxc-resolver/binding-linux-arm64-gnu": "11.20.0", + "@oxc-resolver/binding-linux-arm64-musl": "11.20.0", + "@oxc-resolver/binding-openharmony-arm64": "11.20.0", + "@oxc-resolver/binding-android-arm-eabi": "11.20.0", + "@oxc-resolver/binding-linux-arm-gnueabihf": "11.20.0", + "@oxc-resolver/binding-linux-arm-musleabihf": "11.20.0", + "@oxc-resolver/binding-linux-ppc64-gnu": "11.20.0", + "@oxc-resolver/binding-linux-riscv64-gnu": "11.20.0", + "@oxc-resolver/binding-linux-riscv64-musl": "11.20.0", + "@oxc-resolver/binding-linux-s390x-gnu": "11.20.0", + "@oxc-resolver/binding-wasm32-wasi": "11.20.0", + "@oxc-resolver/binding-darwin-x64": "11.20.0", + "@oxc-resolver/binding-win32-x64-msvc": "11.20.0", + "@oxc-resolver/binding-freebsd-x64": "11.20.0", + "@oxc-resolver/binding-linux-x64-gnu": "11.20.0", + "@oxc-resolver/binding-linux-x64-musl": "11.20.0" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/oxc-resolver/webcontainer-fallback.js b/tools/ui/node_modules/oxc-resolver/webcontainer-fallback.js new file mode 100644 index 0000000000000000000000000000000000000000..ec469c45436a01a34c8900a825fa17345d5f1535 --- /dev/null +++ b/tools/ui/node_modules/oxc-resolver/webcontainer-fallback.js @@ -0,0 +1,23 @@ +const fs = require('node:fs'); +const childProcess = require('node:child_process'); + +const pkg = JSON.parse( + fs.readFileSync(require.resolve('oxc-resolver/package.json'), 'utf-8'), +); +const version = pkg.version; +const baseDir = `/tmp/oxc-resolver-${version}`; +const bindingEntry = `${baseDir}/node_modules/@oxc-resolver/binding-wasm32-wasi/resolver.wasi.cjs`; + +if (!fs.existsSync(bindingEntry)) { + fs.rmSync(baseDir, { recursive: true, force: true }); + fs.mkdirSync(baseDir, { recursive: true }); + const bindingPkg = `@oxc-resolver/binding-wasm32-wasi@${version}`; + // eslint-disable-next-line: no-console + console.log(`[oxc-resolver] Downloading ${bindingPkg} on WebContainer...`); + childProcess.execFileSync('pnpm', ['i', bindingPkg], { + cwd: baseDir, + stdio: 'inherit', + }); +} + +module.exports = require(bindingEntry); diff --git a/tools/ui/node_modules/p-limit/index.d.ts b/tools/ui/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f348d7f13a8b00c5559112bb177b4f527468c63b --- /dev/null +++ b/tools/ui/node_modules/p-limit/index.d.ts @@ -0,0 +1,42 @@ +declare namespace pLimit { + interface Limit { + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue: () => void; + + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + } +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +declare function pLimit(concurrency: number): pLimit.Limit; + +export = pLimit; diff --git a/tools/ui/node_modules/p-limit/index.js b/tools/ui/node_modules/p-limit/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c2ae52d90db4776496b2cae20e636aea0d2dfceb --- /dev/null +++ b/tools/ui/node_modules/p-limit/index.js @@ -0,0 +1,71 @@ +'use strict'; +const Queue = require('yocto-queue'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + throw new TypeError('Expected `concurrency` to be a number from 1 and up'); + } + + const queue = new Queue(); + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.size > 0) { + queue.dequeue()(); + } + }; + + const run = async (fn, resolve, ...args) => { + activeCount++; + + const result = (async () => fn(...args))(); + + resolve(result); + + try { + await result; + } catch {} + + next(); + }; + + const enqueue = (fn, resolve, ...args) => { + queue.enqueue(run.bind(null, fn, resolve, ...args)); + + (async () => { + // This function needs to wait until the next microtask before comparing + // `activeCount` to `concurrency`, because `activeCount` is updated asynchronously + // when the run function is dequeued and called. The comparison in the if-statement + // needs to happen asynchronously as well to get an up-to-date value for `activeCount`. + await Promise.resolve(); + + if (activeCount < concurrency && queue.size > 0) { + queue.dequeue()(); + } + })(); + }; + + const generator = (fn, ...args) => new Promise(resolve => { + enqueue(fn, resolve, ...args); + }); + + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.size + }, + clearQueue: { + value: () => { + queue.clear(); + } + } + }); + + return generator; +}; + +module.exports = pLimit; diff --git a/tools/ui/node_modules/p-limit/license b/tools/ui/node_modules/p-limit/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/tools/ui/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/tools/ui/node_modules/p-limit/package.json b/tools/ui/node_modules/p-limit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..76514736fc9c490a3a377fc26a68ef956ab10f21 --- /dev/null +++ b/tools/ui/node_modules/p-limit/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-limit", + "version": "3.1.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.4.0", + "in-range": "^2.0.0", + "random-int": "^2.0.1", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.35.0" + } +} diff --git a/tools/ui/node_modules/p-limit/readme.md b/tools/ui/node_modules/p-limit/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b283c1e635aab38570d6ef544dea70e2af741c7a --- /dev/null +++ b/tools/ui/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/tools/ui/node_modules/p-locate/index.d.ts b/tools/ui/node_modules/p-locate/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..38c7e578f7665c2dc97c845454937e7eab8d8198 --- /dev/null +++ b/tools/ui/node_modules/p-locate/index.d.ts @@ -0,0 +1,53 @@ +declare namespace pLocate { + interface Options { + /** + Number of concurrently pending promises returned by `tester`. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +/** +Get the first fulfilled promise that satisfies the provided testing function. + +@param input - An iterable of promises/values to test. +@param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. +@returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +@example +``` +import pathExists = require('path-exists'); +import pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` +*/ +declare function pLocate( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: pLocate.Options +): Promise; + +export = pLocate; diff --git a/tools/ui/node_modules/p-locate/index.js b/tools/ui/node_modules/p-locate/index.js new file mode 100644 index 0000000000000000000000000000000000000000..641c3dd1e819d27f9efe65a9437b8980ca07e8c9 --- /dev/null +++ b/tools/ui/node_modules/p-locate/index.js @@ -0,0 +1,50 @@ +'use strict'; +const pLimit = require('p-limit'); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +module.exports = pLocate; diff --git a/tools/ui/node_modules/p-locate/license b/tools/ui/node_modules/p-locate/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/tools/ui/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/tools/ui/node_modules/p-locate/package.json b/tools/ui/node_modules/p-locate/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2d5e447f55a7bdc7216e30ae3dcf0a6529c8ae14 --- /dev/null +++ b/tools/ui/node_modules/p-locate/package.json @@ -0,0 +1,54 @@ +{ + "name": "p-locate", + "version": "5.0.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^3.0.2" + }, + "devDependencies": { + "ava": "^2.4.0", + "delay": "^4.1.0", + "in-range": "^2.0.0", + "time-span": "^4.0.0", + "tsd": "^0.13.1", + "xo": "^0.32.1" + } +} diff --git a/tools/ui/node_modules/p-locate/readme.md b/tools/ui/node_modules/p-locate/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..be85ec1d4483c8eb8463541623922669be3dee5b --- /dev/null +++ b/tools/ui/node_modules/p-locate/readme.md @@ -0,0 +1,93 @@ +# p-locate [![Build Status](https://travis-ci.com/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.com/github/sindresorhus/p-locate) + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + +## Install + +``` +$ npm install p-locate +``` + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const pathExists = require('path-exists'); +const pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + +## API + +### pLocate(input, tester, options?) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `object` + +##### concurrency + +Type: `number`\ +Default: `Infinity`\ +Minimum: `1` + +Number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`\ +Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/tools/ui/node_modules/package-json-from-dist/LICENSE.md b/tools/ui/node_modules/package-json-from-dist/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..881248b6d7f0ca2c4f65c41c0af5e02bb0680601 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/LICENSE.md @@ -0,0 +1,63 @@ +All packages under `src/` are licensed according to the terms in +their respective `LICENSE` or `LICENSE.md` files. + +The remainder of this project is licensed under the Blue Oak +Model License, as follows: + +----- + +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/tools/ui/node_modules/package-json-from-dist/README.md b/tools/ui/node_modules/package-json-from-dist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a9e13448518750fad06bc6661470003043387c21 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/README.md @@ -0,0 +1,110 @@ +# package-json-from-dist + +Sometimes you want to load the `package.json` into your +TypeScript program, and it's tempting to just `import +'../package.json'`, since that seems to work. + +However, this requires `tsc` to make an entire copy of your +`package.json` file into the `dist` folder, which is a problem if +you're using something like +[tshy](https://github.com/isaacs/tshy), which uses the +`package.json` file in dist for another purpose. Even when that +does work, it's asking the module system to do a bunch of extra +fs system calls, just to load a version number or something. (See +[this issue](https://github.com/isaacs/tshy/issues/61).) + +This module helps by just finding the package.json file +appropriately, and reading and parsing it in the most normal +fashion. + +## Caveats + +This _only_ works if your code builds into a target folder called +`dist`, which is in the root of the package. It also requires +that you do not have a folder named `node_modules` anywhere +within your dev environment, or else it'll get the wrong answers +there. (But, at least, that'll be in dev, so you're pretty likely +to notice.) + +If you build to some other location, then you'll need a different +approach. (Feel free to fork this module and make it your own, or +just put the code right inline, there's not much of it.) + +## USAGE + +```js +// src/index.ts +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' + +const pj = findPackageJson(import.meta.url) +console.log(`package.json found at ${pj}`) + +const pkg = loadPackageJson(import.meta.url) +console.log(`Hello from ${pkg.name}@${pkg.version}`) +``` + +If your module is not directly in the `./src` folder, then you need +to specify the path that you would expect to find the +`package.json` when it's _not_ built to the `dist` folder. + +```js +// src/components/something.ts +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' + +const pj = findPackageJson(import.meta.url, '../../package.json') +console.log(`package.json found at ${pj}`) + +const pkg = loadPackageJson(import.meta.url, '../../package.json') +console.log(`Hello from ${pkg.name}@${pkg.version}`) +``` + +When running from CommmonJS, use `__filename` instead of +`import.meta.url`. + +```js +// src/index.cts +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' + +const pj = findPackageJson(__filename) +console.log(`package.json found at ${pj}`) + +const pkg = loadPackageJson(__filename) +console.log(`Hello from ${pkg.name}@${pkg.version}`) +``` + +Since [tshy](https://github.com/isaacs/tshy) builds _both_ +CommonJS and ESM by default, you may find that you need a +CommonJS override and some `//@ts-ignore` magic to make it work. + +`src/pkg.ts`: + +```js +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' +//@ts-ignore +export const pkg = loadPackageJson(import.meta.url) +//@ts-ignore +export const pj = findPackageJson(import.meta.url) +``` + +`src/pkg-cjs.cts`: + +```js +import { + findPackageJson, + loadPackageJson, +} from 'package-json-from-dist' +export const pkg = loadPackageJson(__filename) +export const pj = findPackageJson(__filename) +``` diff --git a/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.d.ts b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d486ffd2bb6ee5f2cb6a47940b00b3f19d207132 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.d.ts @@ -0,0 +1,89 @@ +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +export declare const findPackageJson: (from: string | URL, pathFromSrc?: string) => string; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +export declare const loadPackageJson: (from: string | URL, pathFromSrc?: string) => any; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..ca3e21c763477d704191598e7328770abec8f447 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,KAClB,MAsCF,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,QAEiD,CAAA"} \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.js b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b966ac9fef535bd244ae002b6e45fd93fe5d88f3 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadPackageJson = exports.findPackageJson = void 0; +const node_fs_1 = require("node:fs"); +const node_path_1 = require("node:path"); +const node_url_1 = require("node:url"); +const NM = `${node_path_1.sep}node_modules${node_path_1.sep}`; +const STORE = `.store${node_path_1.sep}`; +const PKG = `${node_path_1.sep}package${node_path_1.sep}`; +const DIST = `${node_path_1.sep}dist${node_path_1.sep}`; +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +const findPackageJson = (from, pathFromSrc = '../package.json') => { + const f = typeof from === 'object' || from.startsWith('file://') ? + (0, node_url_1.fileURLToPath)(from) + : from; + const __dirname = (0, node_path_1.dirname)(f); + const nms = __dirname.lastIndexOf(NM); + if (nms !== -1) { + // inside of node_modules. find the dist directly under package name. + const nm = __dirname.substring(0, nms + NM.length); + const pkgDir = __dirname.substring(nms + NM.length); + // affordance for yarn berry, which puts package contents in + // '.../node_modules/.store/${id}-${hash}/package/...' + if (pkgDir.startsWith(STORE)) { + const pkg = pkgDir.indexOf(PKG, STORE.length); + if (pkg) { + return (0, node_path_1.resolve)(nm, pkgDir.substring(0, pkg + PKG.length), 'package.json'); + } + } + const pkgName = pkgDir.startsWith('@') ? + pkgDir.split(node_path_1.sep, 2).join(node_path_1.sep) + : String(pkgDir.split(node_path_1.sep)[0]); + return (0, node_path_1.resolve)(nm, pkgName, 'package.json'); + } + else { + // see if we are in a dist folder. + const d = __dirname.lastIndexOf(DIST); + if (d !== -1) { + return (0, node_path_1.resolve)(__dirname.substring(0, d), 'package.json'); + } + else { + return (0, node_path_1.resolve)(__dirname, pathFromSrc); + } + } +}; +exports.findPackageJson = findPackageJson; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +const loadPackageJson = (from, pathFromSrc = '../package.json') => JSON.parse((0, node_fs_1.readFileSync)((0, exports.findPackageJson)(from, pathFromSrc), 'utf8')); +exports.loadPackageJson = loadPackageJson; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.js.map b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..2fb5d23c11461daca2676055b897875ba20533c0 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,qCAAsC;AACtC,yCAAiD;AACjD,uCAAwC;AAExC,MAAM,EAAE,GAAG,GAAG,eAAG,eAAe,eAAG,EAAE,CAAA;AACrC,MAAM,KAAK,GAAG,SAAS,eAAG,EAAE,CAAA;AAC5B,MAAM,GAAG,GAAG,GAAG,eAAG,UAAU,eAAG,EAAE,CAAA;AACjC,MAAM,IAAI,GAAG,GAAG,eAAG,OAAO,eAAG,EAAE,CAAA;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACI,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EAC/B,EAAE;IACV,MAAM,CAAC,GACL,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;QACtD,IAAA,wBAAa,EAAC,IAAI,CAAC;QACrB,CAAC,CAAC,IAAI,CAAA;IACR,MAAM,SAAS,GAAG,IAAA,mBAAO,EAAC,CAAC,CAAC,CAAA;IAE5B,MAAM,GAAG,GAAG,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;IACrC,IAAI,GAAG,KAAK,CAAC,CAAC,EAAE,CAAC;QACf,qEAAqE;QACrE,MAAM,EAAE,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,CAAA;QAClD,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,CAAA;QACnD,4DAA4D;QAC5D,sDAAsD;QACtD,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7B,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;YAC7C,IAAI,GAAG,EAAE,CAAC;gBACR,OAAO,IAAA,mBAAO,EACZ,EAAE,EACF,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,EACrC,cAAc,CACf,CAAA;YACH,CAAC;QACH,CAAC;QACD,MAAM,OAAO,GACX,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;YACtB,MAAM,CAAC,KAAK,CAAC,eAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,eAAG,CAAC;YAChC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,eAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAChC,OAAO,IAAA,mBAAO,EAAC,EAAE,EAAE,OAAO,EAAE,cAAc,CAAC,CAAA;IAC7C,CAAC;SAAM,CAAC;QACN,kCAAkC;QAClC,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;QACrC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;YACb,OAAO,IAAA,mBAAO,EAAC,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,CAAC,CAAA;QAC3D,CAAC;aAAM,CAAC;YACN,OAAO,IAAA,mBAAO,EAAC,SAAS,EAAE,WAAW,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;AACH,CAAC,CAAA;AAzCY,QAAA,eAAe,mBAyC3B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACI,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EACvC,EAAE,CACF,IAAI,CAAC,KAAK,CAAC,IAAA,sBAAY,EAAC,IAAA,uBAAe,EAAC,IAAI,EAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,CAAA;AAJzD,QAAA,eAAe,mBAI0C","sourcesContent":["import { readFileSync } from 'node:fs'\nimport { dirname, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst NM = `${sep}node_modules${sep}`\nconst STORE = `.store${sep}`\nconst PKG = `${sep}package${sep}`\nconst DIST = `${sep}dist${sep}`\n\n/**\n * Find the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url)\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url, '../../package.json')\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(__filename)\n * console.log(`package.json found at ${pj}`)\n * ```\n */\nexport const findPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n): string => {\n const f =\n typeof from === 'object' || from.startsWith('file://') ?\n fileURLToPath(from)\n : from\n const __dirname = dirname(f)\n\n const nms = __dirname.lastIndexOf(NM)\n if (nms !== -1) {\n // inside of node_modules. find the dist directly under package name.\n const nm = __dirname.substring(0, nms + NM.length)\n const pkgDir = __dirname.substring(nms + NM.length)\n // affordance for yarn berry, which puts package contents in\n // '.../node_modules/.store/${id}-${hash}/package/...'\n if (pkgDir.startsWith(STORE)) {\n const pkg = pkgDir.indexOf(PKG, STORE.length)\n if (pkg) {\n return resolve(\n nm,\n pkgDir.substring(0, pkg + PKG.length),\n 'package.json',\n )\n }\n }\n const pkgName =\n pkgDir.startsWith('@') ?\n pkgDir.split(sep, 2).join(sep)\n : String(pkgDir.split(sep)[0])\n return resolve(nm, pkgName, 'package.json')\n } else {\n // see if we are in a dist folder.\n const d = __dirname.lastIndexOf(DIST)\n if (d !== -1) {\n return resolve(__dirname.substring(0, d), 'package.json')\n } else {\n return resolve(__dirname, pathFromSrc)\n }\n }\n}\n\n/**\n * Load the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url, '../../package.json')\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(__filename)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n */\nexport const loadPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n) =>\n JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8'))\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/commonjs/package.json b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/tools/ui/node_modules/package-json-from-dist/dist/esm/index.d.ts b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d486ffd2bb6ee5f2cb6a47940b00b3f19d207132 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.d.ts @@ -0,0 +1,89 @@ +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +export declare const findPackageJson: (from: string | URL, pathFromSrc?: string) => string; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +export declare const loadPackageJson: (from: string | URL, pathFromSrc?: string) => any; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/esm/index.d.ts.map b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..ca3e21c763477d704191598e7328770abec8f447 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,KAClB,MAsCF,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,GAAG,GAAG,gBACL,MAAM,QAEiD,CAAA"} \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/esm/index.js b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..426ad3c2d1859792560c09926f3ca7119f3146d5 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.js @@ -0,0 +1,129 @@ +import { readFileSync } from 'node:fs'; +import { dirname, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +const NM = `${sep}node_modules${sep}`; +const STORE = `.store${sep}`; +const PKG = `${sep}package${sep}`; +const DIST = `${sep}dist${sep}`; +/** + * Find the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url) + * console.log(`package.json found at ${pj}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(import.meta.url, '../../package.json') + * console.log(`package.json found at ${pj}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { findPackageJson } from 'package-json-from-dist' + * + * const pj = findPackageJson(__filename) + * console.log(`package.json found at ${pj}`) + * ``` + */ +export const findPackageJson = (from, pathFromSrc = '../package.json') => { + const f = typeof from === 'object' || from.startsWith('file://') ? + fileURLToPath(from) + : from; + const __dirname = dirname(f); + const nms = __dirname.lastIndexOf(NM); + if (nms !== -1) { + // inside of node_modules. find the dist directly under package name. + const nm = __dirname.substring(0, nms + NM.length); + const pkgDir = __dirname.substring(nms + NM.length); + // affordance for yarn berry, which puts package contents in + // '.../node_modules/.store/${id}-${hash}/package/...' + if (pkgDir.startsWith(STORE)) { + const pkg = pkgDir.indexOf(PKG, STORE.length); + if (pkg) { + return resolve(nm, pkgDir.substring(0, pkg + PKG.length), 'package.json'); + } + } + const pkgName = pkgDir.startsWith('@') ? + pkgDir.split(sep, 2).join(sep) + : String(pkgDir.split(sep)[0]); + return resolve(nm, pkgName, 'package.json'); + } + else { + // see if we are in a dist folder. + const d = __dirname.lastIndexOf(DIST); + if (d !== -1) { + return resolve(__dirname.substring(0, d), 'package.json'); + } + else { + return resolve(__dirname, pathFromSrc); + } + } +}; +/** + * Load the package.json file, either from a TypeScript file somewhere not + * in a 'dist' folder, or a built and/or installed 'dist' folder. + * + * Note: this *only* works if you build your code into `'./dist'`, and that the + * source path does not also contain `'dist'`! If you don't build into + * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will + * not work properly! + * + * The default `pathFromSrc` option assumes that the calling code lives one + * folder below the root of the package. Otherwise, it must be specified. + * + * Example: + * + * ```ts + * // src/index.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * If the caller is deeper within the project source, then you must provide + * the appropriate fallback path: + * + * ```ts + * // src/components/something.ts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(import.meta.url, '../../package.json') + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + * + * When running from CommmonJS, use `__filename` instead of `import.meta.url` + * + * ```ts + * // src/index.cts + * import { loadPackageJson } from 'package-json-from-dist' + * + * const pj = loadPackageJson(__filename) + * console.log(`Hello from ${pj.name}@${pj.version}`) + * ``` + */ +export const loadPackageJson = (from, pathFromSrc = '../package.json') => JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8')); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/esm/index.js.map b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..53b6ce7a53965dcd9257205af835c364c18dfe7d --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAA;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,MAAM,EAAE,GAAG,GAAG,GAAG,eAAe,GAAG,EAAE,CAAA;AACrC,MAAM,KAAK,GAAG,SAAS,GAAG,EAAE,CAAA;AAC5B,MAAM,GAAG,GAAG,GAAG,GAAG,UAAU,GAAG,EAAE,CAAA;AACjC,MAAM,IAAI,GAAG,GAAG,GAAG,OAAO,GAAG,EAAE,CAAA;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EAC/B,EAAE;IACV,MAAM,CAAC,GACL,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC;QACtD,aAAa,CAAC,IAAI,CAAC;QACrB,CAAC,CAAC,IAAI,CAAA;IACR,MAAM,SAAS,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;IAE5B,MAAM,GAAG,GAAG,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,CAAA;IACrC,IAAI,GAAG,KAAK,CAAC,CAAC,EAAE,CAAC;QACf,qEAAqE;QACrE,MAAM,EAAE,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,CAAA;QAClD,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,CAAA;QACnD,4DAA4D;QAC5D,sDAAsD;QACtD,IAAI,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7B,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;YAC7C,IAAI,GAAG,EAAE,CAAC;gBACR,OAAO,OAAO,CACZ,EAAE,EACF,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,EACrC,cAAc,CACf,CAAA;YACH,CAAC;QACH,CAAC;QACD,MAAM,OAAO,GACX,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;YACtB,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;YAChC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAChC,OAAO,OAAO,CAAC,EAAE,EAAE,OAAO,EAAE,cAAc,CAAC,CAAA;IAC7C,CAAC;SAAM,CAAC;QACN,kCAAkC;QAClC,MAAM,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;QACrC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;YACb,OAAO,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,CAAC,CAAA;QAC3D,CAAC;aAAM,CAAC;YACN,OAAO,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC,CAAA;QACxC,CAAC;IACH,CAAC;AACH,CAAC,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,IAAkB,EAClB,cAAsB,iBAAiB,EACvC,EAAE,CACF,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,CAAA","sourcesContent":["import { readFileSync } from 'node:fs'\nimport { dirname, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst NM = `${sep}node_modules${sep}`\nconst STORE = `.store${sep}`\nconst PKG = `${sep}package${sep}`\nconst DIST = `${sep}dist${sep}`\n\n/**\n * Find the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url)\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(import.meta.url, '../../package.json')\n * console.log(`package.json found at ${pj}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { findPackageJson } from 'package-json-from-dist'\n *\n * const pj = findPackageJson(__filename)\n * console.log(`package.json found at ${pj}`)\n * ```\n */\nexport const findPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n): string => {\n const f =\n typeof from === 'object' || from.startsWith('file://') ?\n fileURLToPath(from)\n : from\n const __dirname = dirname(f)\n\n const nms = __dirname.lastIndexOf(NM)\n if (nms !== -1) {\n // inside of node_modules. find the dist directly under package name.\n const nm = __dirname.substring(0, nms + NM.length)\n const pkgDir = __dirname.substring(nms + NM.length)\n // affordance for yarn berry, which puts package contents in\n // '.../node_modules/.store/${id}-${hash}/package/...'\n if (pkgDir.startsWith(STORE)) {\n const pkg = pkgDir.indexOf(PKG, STORE.length)\n if (pkg) {\n return resolve(\n nm,\n pkgDir.substring(0, pkg + PKG.length),\n 'package.json',\n )\n }\n }\n const pkgName =\n pkgDir.startsWith('@') ?\n pkgDir.split(sep, 2).join(sep)\n : String(pkgDir.split(sep)[0])\n return resolve(nm, pkgName, 'package.json')\n } else {\n // see if we are in a dist folder.\n const d = __dirname.lastIndexOf(DIST)\n if (d !== -1) {\n return resolve(__dirname.substring(0, d), 'package.json')\n } else {\n return resolve(__dirname, pathFromSrc)\n }\n }\n}\n\n/**\n * Load the package.json file, either from a TypeScript file somewhere not\n * in a 'dist' folder, or a built and/or installed 'dist' folder.\n *\n * Note: this *only* works if you build your code into `'./dist'`, and that the\n * source path does not also contain `'dist'`! If you don't build into\n * `'./dist'`, or if you have files at `./src/dist/dist.ts`, then this will\n * not work properly!\n *\n * The default `pathFromSrc` option assumes that the calling code lives one\n * folder below the root of the package. Otherwise, it must be specified.\n *\n * Example:\n *\n * ```ts\n * // src/index.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * If the caller is deeper within the project source, then you must provide\n * the appropriate fallback path:\n *\n * ```ts\n * // src/components/something.ts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(import.meta.url, '../../package.json')\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n *\n * When running from CommmonJS, use `__filename` instead of `import.meta.url`\n *\n * ```ts\n * // src/index.cts\n * import { loadPackageJson } from 'package-json-from-dist'\n *\n * const pj = loadPackageJson(__filename)\n * console.log(`Hello from ${pj.name}@${pj.version}`)\n * ```\n */\nexport const loadPackageJson = (\n from: string | URL,\n pathFromSrc: string = '../package.json',\n) =>\n JSON.parse(readFileSync(findPackageJson(from, pathFromSrc), 'utf8'))\n"]} \ No newline at end of file diff --git a/tools/ui/node_modules/package-json-from-dist/dist/esm/package.json b/tools/ui/node_modules/package-json-from-dist/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/tools/ui/node_modules/package-json-from-dist/package.json b/tools/ui/node_modules/package-json-from-dist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a2d03c3269d72d08bc82d62ff15c0c671bf3a63b --- /dev/null +++ b/tools/ui/node_modules/package-json-from-dist/package.json @@ -0,0 +1,68 @@ +{ + "name": "package-json-from-dist", + "version": "1.0.1", + "description": "Load the local package.json from either src or dist folder", + "main": "./dist/commonjs/index.js", + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc" + }, + "author": "Isaac Z. Schlueter (https://izs.me)", + "license": "BlueOak-1.0.0", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/package-json-from-dist.git" + }, + "devDependencies": { + "@types/node": "^20.12.12", + "prettier": "^3.2.5", + "tap": "^18.5.3", + "typedoc": "^0.24.8", + "typescript": "^5.1.6", + "tshy": "^1.14.0" + }, + "prettier": { + "semi": false, + "printWidth": 70, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf", + "experimentalTernaries": true + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "types": "./dist/commonjs/index.d.ts", + "type": "module" +} diff --git a/tools/ui/node_modules/package-manager-detector/LICENSE b/tools/ui/node_modules/package-manager-detector/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..97b7cc87199ed2947e15ad3268d211dc3f245bd1 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-PRESENT Anthony Fu + +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. diff --git a/tools/ui/node_modules/package-manager-detector/README.md b/tools/ui/node_modules/package-manager-detector/README.md new file mode 100644 index 0000000000000000000000000000000000000000..45369dcdd4af9e11fd38f5b2a3a2d8700a3e5403 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/README.md @@ -0,0 +1,109 @@ +# package-manager-detector + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![JSDocs][jsdocs-src]][jsdocs-href] +[![License][license-src]][license-href] + +Package manager detector is based on lock files, the `package.json` `packageManager` field, and installation metadata to detect the package manager used in a project. + +It supports `npm`, `yarn`, `pnpm`, `deno`, and `bun`. + +## Install + +```sh +# pnpm +pnpm add package-manager-detector + +# npm +npm i package-manager-detector + +# yarn +yarn add package-manager-detector +``` + +## Usage + +To check the file system for which package manager is used: + +```js +import { detect } from 'package-manager-detector/detect' +``` + +or to get the currently running package manager: + +```js +import { getUserAgent } from 'package-manager-detector/detect' +``` + +## Customize Detection Strategy + +By default, the `detect` API searches through the current directory for lock files, and if none exists, it looks for the `packageManager` field in `package.json`. If that also doesn't exist, it will check the `devEngines.packageManager` field in `package.json`. If all strategies couldn't detect the package manager, it'll crawl upwards to the parent directory and repeat the detection process until it reaches the root directory. + +The strategies can be configured through `detect`'s `strategies` option with the following accepted strategies: + +- `'lockfile'`: Look up for lock files. +- `'packageManager-field'`: Look up for the `packageManager` field in package.json. +- `'devEngines-field'`: Look up for the `devEngines.packageManager` field in package.json. +- `'install-metadata'`: Look up for installation metadata added by package managers. + +The order of the strategies can also be changed to prioritize one strategy over another. For example, if you prefer to detect the package manager used for installation: + +```js +import { detect } from 'package-manager-detector/detect' + +const pm = await detect({ + strategies: ['install-metadata', 'lockfile', 'packageManager-field', 'devEngines-field'] +}) +``` + +## Agents and Commands + +This package includes package manager agents and their corresponding commands for: + +- `'agent'` - run the package manager with no arguments +- `'install'` - install dependencies +- `'frozen'` - install dependencies using frozen lockfile +- `'add'` - add dependencies +- `'uninstall'` - remove dependencies +- `'global'` - install global packages +- `'global_uninstall'` - remove global packages +- `'upgrade'` - upgrade dependencies +- `'upgrade-interactive'` - upgrade dependencies interactively: not available for `npm` +- `'dedupe'` - deduplicate dependencies with overlapping ranges: not available for `deno` and `bun` +- `'execute'` - download & execute binary scripts +- `'execute-local'` - execute binary scripts (from package locally installed) +- `'run'` - run `package.json` scripts + +### Using Agents and Commands + +A `resolveCommand` function is provided to resolve the command for a specific agent. + +```ts +import { resolveCommand } from 'package-manager-detector/commands' +import { detect } from 'package-manager-detector/detect' + +const pm = await detect() +if (!pm) + throw new Error('Could not detect package manager') + +const { command, args } = resolveCommand(pm.agent, 'add', ['@antfu/ni']) // { command: 'pnpm', args: ['add', '@antfu/ni'] } +console.log(`Detected the ${pm.agent} package manager. You can run a install with ${command} ${args.join(' ')}`) +``` + +You can check the source code or the [JSDocs](https://www.jsdocs.io/package/package-manager-detector) for more information. + +## License + +[MIT](./LICENSE) License © 2020-PRESENT [Anthony Fu](https://github.com/antfu) + + + +[npm-version-src]: https://img.shields.io/npm/v/package-manager-detector?style=flat&colorA=18181B&colorB=F0DB4F +[npm-version-href]: https://npmjs.com/package/package-manager-detector +[npm-downloads-src]: https://img.shields.io/npm/dm/package-manager-detector?style=flat&colorA=18181B&colorB=F0DB4F +[npm-downloads-href]: https://npmjs.com/package/package-manager-detector +[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=18181B&colorB=F0DB4F +[jsdocs-href]: https://www.jsdocs.io/package/package-manager-detector +[license-src]: https://img.shields.io/github/license/antfu-collective/package-manager-detector.svg?style=flat&colorA=18181B&colorB=F0DB4F +[license-href]: https://github.com/antfu-collective/package-manager-detector/blob/main/LICENSE diff --git a/tools/ui/node_modules/package-manager-detector/dist/commands.d.mts b/tools/ui/node_modules/package-manager-detector/dist/commands.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..7c1fb54b970ece898b0a02a5987dbd15c73f607d --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/commands.d.mts @@ -0,0 +1,36 @@ +import { c as AgentCommands, b as AgentCommandValue, R as ResolvedCommand, A as Agent, C as Command } from './shared/package-manager-detector.DksAilYA.mjs'; + +declare const COMMANDS: { + npm: AgentCommands; + yarn: AgentCommands; + 'yarn@berry': AgentCommands; + pnpm: AgentCommands; + 'pnpm@6': AgentCommands; + bun: AgentCommands; + deno: AgentCommands; +}; +/** + * Resolve the command for the agent merging the command arguments with the provided arguments. + * + * For example, to show how to install `@antfu/ni` globally using `pnpm`: + * ```js + * import { resolveCommand } from 'package-manager-detector/commands' + * const { command, args } = resolveCommand('pnpm', 'global', ['@antfu/ni']) + * console.log(`${command} ${args.join(' ')}`) // 'pnpm add -g @antfu/ni' + * ``` + * + * @param agent The agent to use. + * @param command the command to resolve. + * @param args The arguments to pass to the command. + * @returns {ResolvedCommand} The resolved command or `null` if the agent command is not found. + */ +declare function resolveCommand(agent: Agent, command: Command, args: string[]): ResolvedCommand | null; +/** + * Construct the command from the agent command merging the command arguments with the provided arguments. + * @param value {AgentCommandValue} The agent command to use. + * @param args The arguments to pass to the command. + * @returns {ResolvedCommand} The resolved command or `null` if the command is `null`. + */ +declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null; + +export { COMMANDS, constructCommand, resolveCommand }; diff --git a/tools/ui/node_modules/package-manager-detector/dist/commands.mjs b/tools/ui/node_modules/package-manager-detector/dist/commands.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c479bf0e4206135f41fd038986f6c5d2618cade8 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/commands.mjs @@ -0,0 +1,133 @@ +function dashDashArg(agent, agentCommand) { + return (args) => { + if (args.length > 1) { + return [agent, agentCommand, args[0], "--", ...args.slice(1)]; + } else { + return [agent, agentCommand, args[0]]; + } + }; +} +function denoExecute() { + return (args) => { + return ["deno", "run", `npm:${args[0]}`, ...args.slice(1)]; + }; +} +const npm = { + "agent": ["npm", 0], + "run": dashDashArg("npm", "run"), + "install": ["npm", "i", 0], + "frozen": ["npm", "ci", 0], + "global": ["npm", "i", "-g", 0], + "add": ["npm", "i", 0], + "upgrade": ["npm", "update", 0], + "upgrade-interactive": null, + "dedupe": ["npm", "dedupe", 0], + "execute": ["npx", 0], + "execute-local": ["npx", 0], + "uninstall": ["npm", "uninstall", 0], + "global_uninstall": ["npm", "uninstall", "-g", 0] +}; +const yarn = { + "agent": ["yarn", 0], + "run": ["yarn", "run", 0], + "install": ["yarn", "install", 0], + "frozen": ["yarn", "install", "--frozen-lockfile", 0], + "global": ["yarn", "global", "add", 0], + "add": ["yarn", "add", 0], + "upgrade": ["yarn", "upgrade", 0], + "upgrade-interactive": ["yarn", "upgrade-interactive", 0], + "dedupe": null, + "execute": ["npx", 0], + "execute-local": dashDashArg("yarn", "exec"), + "uninstall": ["yarn", "remove", 0], + "global_uninstall": ["yarn", "global", "remove", 0] +}; +const yarnBerry = { + ...yarn, + "frozen": ["yarn", "install", "--immutable", 0], + "upgrade": ["yarn", "up", 0], + "upgrade-interactive": ["yarn", "up", "-i", 0], + "dedupe": ["yarn", "dedupe", 0], + "execute": ["yarn", "dlx", 0], + "execute-local": ["yarn", "exec", 0], + // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821 + "global": ["npm", "i", "-g", 0], + "global_uninstall": ["npm", "uninstall", "-g", 0] +}; +const pnpm = { + "agent": ["pnpm", 0], + "run": ["pnpm", "run", 0], + "install": ["pnpm", "i", 0], + "frozen": ["pnpm", "i", "--frozen-lockfile", 0], + "global": ["pnpm", "add", "-g", 0], + "add": ["pnpm", "add", 0], + "upgrade": ["pnpm", "update", 0], + "upgrade-interactive": ["pnpm", "update", "-i", 0], + "dedupe": ["pnpm", "dedupe", 0], + "execute": ["pnpm", "dlx", 0], + "execute-local": ["pnpm", "exec", 0], + "uninstall": ["pnpm", "remove", 0], + "global_uninstall": ["pnpm", "remove", "--global", 0] +}; +const bun = { + "agent": ["bun", 0], + "run": ["bun", "run", 0], + "install": ["bun", "install", 0], + "frozen": ["bun", "install", "--frozen-lockfile", 0], + "global": ["bun", "add", "-g", 0], + "add": ["bun", "add", 0], + "upgrade": ["bun", "update", 0], + "upgrade-interactive": ["bun", "update", "-i", 0], + "dedupe": null, + "execute": ["bun", "x", 0], + "execute-local": ["bun", "x", 0], + "uninstall": ["bun", "remove", 0], + "global_uninstall": ["bun", "remove", "-g", 0] +}; +const deno = { + "agent": ["deno", 0], + "run": ["deno", "task", 0], + "install": ["deno", "install", 0], + "frozen": ["deno", "install", "--frozen", 0], + "global": ["deno", "install", "-g", 0], + "add": ["deno", "add", 0], + "upgrade": ["deno", "outdated", "--update", 0], + "upgrade-interactive": ["deno", "outdated", "--update", 0], + "dedupe": null, + "execute": denoExecute(), + "execute-local": ["deno", "task", "--eval", 0], + "uninstall": ["deno", "remove", 0], + "global_uninstall": ["deno", "uninstall", "-g", 0] +}; +const COMMANDS = { + "npm": npm, + "yarn": yarn, + "yarn@berry": yarnBerry, + "pnpm": pnpm, + // pnpm v6.x or below + "pnpm@6": { + ...pnpm, + run: dashDashArg("pnpm", "run") + }, + "bun": bun, + "deno": deno +}; +function resolveCommand(agent, command, args) { + const value = COMMANDS[agent][command]; + return constructCommand(value, args); +} +function constructCommand(value, args) { + if (value == null) + return null; + const list = typeof value === "function" ? value(args) : value.flatMap((v) => { + if (typeof v === "number") + return args; + return [v]; + }); + return { + command: list[0], + args: list.slice(1) + }; +} + +export { COMMANDS, constructCommand, resolveCommand }; diff --git a/tools/ui/node_modules/package-manager-detector/dist/constants.d.mts b/tools/ui/node_modules/package-manager-detector/dist/constants.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5b751acdb054248d548599ae0f507bbd96b98189 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/constants.d.mts @@ -0,0 +1,8 @@ +import { A as Agent, a as AgentName } from './shared/package-manager-detector.DksAilYA.mjs'; + +declare const AGENTS: Agent[]; +declare const LOCKS: Record; +declare const INSTALL_METADATA: Record; +declare const INSTALL_PAGE: Record; + +export { AGENTS, INSTALL_METADATA, INSTALL_PAGE, LOCKS }; diff --git a/tools/ui/node_modules/package-manager-detector/dist/constants.mjs b/tools/ui/node_modules/package-manager-detector/dist/constants.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a8cba4bc13cc29193a7b7f4c8579aed1f2d2500e --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/constants.mjs @@ -0,0 +1,45 @@ +const AGENTS = [ + "npm", + "yarn", + "yarn@berry", + "pnpm", + "pnpm@6", + "bun", + "deno" +]; +const LOCKS = { + "bun.lock": "bun", + "bun.lockb": "bun", + "deno.lock": "deno", + "pnpm-lock.yaml": "pnpm", + "pnpm-workspace.yaml": "pnpm", + "yarn.lock": "yarn", + "package-lock.json": "npm", + "npm-shrinkwrap.json": "npm" +}; +const INSTALL_METADATA = { + "node_modules/.deno/": "deno", + "node_modules/.pnpm/": "pnpm", + "node_modules/.yarn-state.yml": "yarn", + // yarn v2+ (node-modules) + "node_modules/.yarn_integrity": "yarn", + // yarn v1 + "node_modules/.package-lock.json": "npm", + ".pnp.cjs": "yarn", + // yarn v3+ (pnp) + ".pnp.js": "yarn", + // yarn v2 (pnp) + "bun.lock": "bun", + "bun.lockb": "bun" +}; +const INSTALL_PAGE = { + "bun": "https://bun.sh", + "deno": "https://deno.com", + "pnpm": "https://pnpm.io/installation", + "pnpm@6": "https://pnpm.io/6.x/installation", + "yarn": "https://classic.yarnpkg.com/en/docs/install", + "yarn@berry": "https://yarnpkg.com/getting-started/install", + "npm": "https://docs.npmjs.com/cli/configuring-npm/install" +}; + +export { AGENTS, INSTALL_METADATA, INSTALL_PAGE, LOCKS }; diff --git a/tools/ui/node_modules/package-manager-detector/dist/detect.d.mts b/tools/ui/node_modules/package-manager-detector/dist/detect.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b48aaf48211e13b257487d8bd763ff1595f3762c --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/detect.d.mts @@ -0,0 +1,16 @@ +import { d as DetectOptions, e as DetectResult, a as AgentName } from './shared/package-manager-detector.DksAilYA.mjs'; + +/** + * Detects the package manager used in the running process. + * + * This method will check for `process.env.npm_config_user_agent`. + */ +declare function getUserAgent(): AgentName | null; +/** + * Detects the package manager used in the project. + * @param options {DetectOptions} The options to use when detecting the package manager. + * @returns {Promise} The detected package manager or `null` if not found. + */ +declare function detect(options?: DetectOptions): Promise; + +export { detect, getUserAgent }; diff --git a/tools/ui/node_modules/package-manager-detector/dist/detect.mjs b/tools/ui/node_modules/package-manager-detector/dist/detect.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c912e54e25182f33555c129d9a84bbff7c6a6040 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/detect.mjs @@ -0,0 +1,134 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import process from 'node:process'; +import { INSTALL_METADATA, LOCKS, AGENTS } from './constants.mjs'; + +async function pathExists(path2, type) { + try { + const stat = await fs.stat(path2); + return type === "file" ? stat.isFile() : stat.isDirectory(); + } catch { + return false; + } +} +function getUserAgent() { + const userAgent = process.env.npm_config_user_agent; + if (!userAgent) { + return null; + } + const name = userAgent.split("/")[0]; + return AGENTS.includes(name) ? name : null; +} +function* lookup(cwd = process.cwd()) { + let directory = path.resolve(cwd); + const { root } = path.parse(directory); + while (directory && directory !== root) { + yield directory; + directory = path.dirname(directory); + } +} +async function parsePackageJson(filepath, options) { + if (!filepath || !await pathExists(filepath, "file")) + return null; + return await handlePackageManager(filepath, options); +} +async function detect(options = {}) { + const { + cwd, + strategies = ["lockfile", "packageManager-field", "devEngines-field"] + } = options; + let stopDir; + if (typeof options.stopDir === "string") { + const resolved = path.resolve(options.stopDir); + stopDir = (dir) => dir === resolved; + } else { + stopDir = options.stopDir; + } + for (const directory of lookup(cwd)) { + for (const strategy of strategies) { + switch (strategy) { + case "lockfile": { + for (const lock of Object.keys(LOCKS)) { + if (await pathExists(path.join(directory, lock), "file")) { + const name = LOCKS[lock]; + const result = await parsePackageJson(path.join(directory, "package.json"), options); + if (result) + return result; + else + return { name, agent: name }; + } + } + break; + } + case "packageManager-field": + case "devEngines-field": { + const result = await parsePackageJson(path.join(directory, "package.json"), options); + if (result) + return result; + break; + } + case "install-metadata": { + for (const metadata of Object.keys(INSTALL_METADATA)) { + const fileOrDir = metadata.endsWith("/") ? "dir" : "file"; + if (await pathExists(path.join(directory, metadata), fileOrDir)) { + const name = INSTALL_METADATA[metadata]; + const agent = name === "yarn" ? isMetadataYarnClassic(metadata) ? "yarn" : "yarn@berry" : name; + return { name, agent }; + } + } + break; + } + } + } + if (stopDir?.(directory)) + break; + } + return null; +} +function getNameAndVer(pkg) { + const handelVer = (version) => version?.match(/\d+(\.\d+){0,2}/)?.[0] ?? version; + if (typeof pkg.packageManager === "string") { + const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@"); + return { name, ver: handelVer(ver) }; + } + if (typeof pkg.devEngines?.packageManager?.name === "string") { + return { + name: pkg.devEngines.packageManager.name, + ver: handelVer(pkg.devEngines.packageManager.version) + }; + } + return void 0; +} +async function handlePackageManager(filepath, options) { + try { + const content = await fs.readFile(filepath, "utf8"); + const pkg = options.packageJsonParser ? await options.packageJsonParser(content, filepath) : JSON.parse(content); + let agent; + const nameAndVer = getNameAndVer(pkg); + if (nameAndVer) { + const name = nameAndVer.name; + const ver = nameAndVer.ver; + let version = ver; + if (name === "yarn" && ver && Number.parseInt(ver) > 1) { + agent = "yarn@berry"; + version = "berry"; + return { name, agent, version }; + } else if (name === "pnpm" && ver && Number.parseInt(ver) < 7) { + agent = "pnpm@6"; + return { name, agent, version }; + } else if (AGENTS.includes(name)) { + agent = name; + return { name, agent, version }; + } else { + return options.onUnknown?.(pkg.packageManager) ?? null; + } + } + } catch { + } + return null; +} +function isMetadataYarnClassic(metadataPath) { + return metadataPath.endsWith(".yarn_integrity"); +} + +export { detect, getUserAgent }; diff --git a/tools/ui/node_modules/package-manager-detector/dist/index.d.mts b/tools/ui/node_modules/package-manager-detector/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..fce26d2c3530f9603db23255ab7f20d793fba9bc --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/index.d.mts @@ -0,0 +1,4 @@ +export { COMMANDS, constructCommand, resolveCommand } from './commands.mjs'; +export { AGENTS, INSTALL_METADATA, INSTALL_PAGE, LOCKS } from './constants.mjs'; +export { detect, getUserAgent } from './detect.mjs'; +export { A as Agent, b as AgentCommandValue, c as AgentCommands, a as AgentName, C as Command, d as DetectOptions, e as DetectResult, D as DetectStrategy, R as ResolvedCommand } from './shared/package-manager-detector.DksAilYA.mjs'; diff --git a/tools/ui/node_modules/package-manager-detector/dist/index.mjs b/tools/ui/node_modules/package-manager-detector/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f495cd5591fd2b43941825192793a761ba95d8db --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/index.mjs @@ -0,0 +1,6 @@ +export { COMMANDS, constructCommand, resolveCommand } from './commands.mjs'; +export { AGENTS, INSTALL_METADATA, INSTALL_PAGE, LOCKS } from './constants.mjs'; +export { detect, getUserAgent } from './detect.mjs'; +import 'node:fs/promises'; +import 'node:path'; +import 'node:process'; diff --git a/tools/ui/node_modules/package-manager-detector/dist/shared/package-manager-detector.DksAilYA.d.mts b/tools/ui/node_modules/package-manager-detector/dist/shared/package-manager-detector.DksAilYA.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..02c52beb368202d2781941254756f6754eed0aa6 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/dist/shared/package-manager-detector.DksAilYA.d.mts @@ -0,0 +1,92 @@ +type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno'; +type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno'; +type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null; +interface AgentCommands { + 'agent': AgentCommandValue; + 'run': AgentCommandValue; + 'install': AgentCommandValue; + 'frozen': AgentCommandValue; + 'global': AgentCommandValue; + 'add': AgentCommandValue; + 'upgrade': AgentCommandValue; + 'upgrade-interactive': AgentCommandValue; + 'dedupe': AgentCommandValue; + 'execute': AgentCommandValue; + 'execute-local': AgentCommandValue; + 'uninstall': AgentCommandValue; + 'global_uninstall': AgentCommandValue; +} +type Command = keyof AgentCommands; +interface ResolvedCommand { + /** + * CLI command. + */ + command: string; + /** + * Arguments for the CLI command, merged with user arguments. + */ + args: string[]; +} +type DetectStrategy = 'lockfile' | 'packageManager-field' | 'devEngines-field' | 'install-metadata'; +interface DetectOptions { + /** + * Current working directory to start looking up for package manager. + * @default `process.cwd()` + */ + cwd?: string; + /** + * The strategies to use for detecting the package manager. The strategies + * are executed in the order it's specified for every directory that it iterates + * upwards from the `cwd`. + * + * - `'lockfile'`: Look up for lock files. + * - `'packageManager-field'`: Look up for the `packageManager` field in package.json. + * - `'devEngines-field'`: Look up for the `devEngines.packageManager` field in package.json. + * - `'install-metadata'`: Look up for installation metadata added by package managers. + * + * @default ['lockfile', 'packageManager-field', 'devEngines-field'] + */ + strategies?: DetectStrategy[]; + /** + * Callback when unknown package manager from package.json. + * @param packageManager - The `packageManager` value from package.json file. + */ + onUnknown?: (packageManager: string) => DetectResult | null | undefined; + /** + * The path to stop traversing up the directory. + */ + stopDir?: string | ((currentDir: string) => boolean); + /** + * Optional custom parser for `package.json` content. + * + * If provided, it will be used instead of `JSON.parse` when reading `package.json` files. + * This can be used to support JSONC, YAML, or other formats. + * + * @param content - The content of the file. + * @param filepath - The absolute path to the file. + * @returns The parsed object or a Promise resolving to it. + * @default JSON.parse + */ + packageJsonParser?: (content: string, filepath: string) => any | Promise; +} +interface DetectResult { + /** + * Agent name without the specifier. + * + * Can be `npm`, `yarn`, `pnpm`, `bun`, or `deno`. + */ + name: AgentName; + /** + * Agent specifier to resolve the command. + * + * May contain '@' to differentiate the version (e.g. 'yarn@berry'). + * Use `name` for the agent name without the specifier. + */ + agent: Agent; + /** + * Specific version of the agent, read from `packageManager` field in package.json. + */ + version?: string; +} + +export type { Agent as A, Command as C, DetectStrategy as D, ResolvedCommand as R, AgentName as a, AgentCommandValue as b, AgentCommands as c, DetectOptions as d, DetectResult as e }; diff --git a/tools/ui/node_modules/package-manager-detector/package.json b/tools/ui/node_modules/package-manager-detector/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8cfd856deee266a6b90e1af7c930f531bf919e73 --- /dev/null +++ b/tools/ui/node_modules/package-manager-detector/package.json @@ -0,0 +1,62 @@ +{ + "name": "package-manager-detector", + "type": "module", + "version": "1.6.0", + "description": "Package manager detector", + "author": "Anthony Fu ", + "license": "MIT", + "homepage": "https://github.com/antfu-collective/package-manager-detector#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/antfu-collective/package-manager-detector.git" + }, + "bugs": { + "url": "https://github.com/antfu-collective/package-manager-detector/issues" + }, + "sideEffects": false, + "exports": { + ".": "./dist/index.mjs", + "./commands": "./dist/commands.mjs", + "./detect": "./dist/detect.mjs", + "./constants": "./dist/constants.mjs" + }, + "main": "./dist/index.mjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "typesVersions": { + "*": { + "commands": [ + "./dist/commands.d.mts" + ], + "detect": [ + "./dist/detect.d.mts" + ], + "constants": [ + "./dist/constants.d.mts" + ] + } + }, + "files": [ + "dist" + ], + "devDependencies": { + "@antfu/eslint-config": "^6.2.0", + "@types/fs-extra": "^11.0.4", + "@types/node": "^24.10.1", + "bumpp": "^10.3.2", + "eslint": "^9.39.1", + "fs-extra": "^11.3.2", + "typescript": "^5.9.3", + "unbuild": "^3.6.1", + "vitest": "^4.0.14", + "vitest-package-exports": "^0.1.1" + }, + "scripts": { + "build": "unbuild", + "stub": "unbuild --stub", + "release": "bumpp", + "lint": "eslint", + "lint:fix": "eslint --fix", + "test": "vitest" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/parent-module/index.js b/tools/ui/node_modules/parent-module/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a26f953a1728aa47b9f94d9c0e0f208116c22478 --- /dev/null +++ b/tools/ui/node_modules/parent-module/index.js @@ -0,0 +1,37 @@ +'use strict'; +const callsites = require('callsites'); + +module.exports = filepath => { + const stacks = callsites(); + + if (!filepath) { + return stacks[2].getFileName(); + } + + let seenVal = false; + + // Skip the first stack as it's this function + stacks.shift(); + + for (const stack of stacks) { + const parentFilepath = stack.getFileName(); + + if (typeof parentFilepath !== 'string') { + continue; + } + + if (parentFilepath === filepath) { + seenVal = true; + continue; + } + + // Skip native modules + if (parentFilepath === 'module.js') { + continue; + } + + if (seenVal && parentFilepath !== filepath) { + return parentFilepath; + } + } +}; diff --git a/tools/ui/node_modules/parent-module/license b/tools/ui/node_modules/parent-module/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/tools/ui/node_modules/parent-module/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/tools/ui/node_modules/parent-module/package.json b/tools/ui/node_modules/parent-module/package.json new file mode 100644 index 0000000000000000000000000000000000000000..790333d0b1a659ca73482b1756c8509e6c7049ff --- /dev/null +++ b/tools/ui/node_modules/parent-module/package.json @@ -0,0 +1,46 @@ +{ + "name": "parent-module", + "version": "1.0.1", + "description": "Get the path of the parent module", + "license": "MIT", + "repository": "sindresorhus/parent-module", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "parent", + "module", + "package", + "pkg", + "caller", + "calling", + "module", + "path", + "callsites", + "callsite", + "stacktrace", + "stack", + "trace", + "function", + "file" + ], + "dependencies": { + "callsites": "^3.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "execa": "^1.0.0", + "xo": "^0.24.0" + } +} diff --git a/tools/ui/node_modules/parent-module/readme.md b/tools/ui/node_modules/parent-module/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..dffb4ce8f1acaa42f9ecfa7150b035eada30ca81 --- /dev/null +++ b/tools/ui/node_modules/parent-module/readme.md @@ -0,0 +1,67 @@ +# parent-module [![Build Status](https://travis-ci.org/sindresorhus/parent-module.svg?branch=master)](https://travis-ci.org/sindresorhus/parent-module) + +> Get the path of the parent module + +Node.js exposes `module.parent`, but it only gives you the first cached parent, which is not necessarily the actual parent. + + +## Install + +``` +$ npm install parent-module +``` + + +## Usage + +```js +// bar.js +const parentModule = require('parent-module'); + +module.exports = () => { + console.log(parentModule()); + //=> '/Users/sindresorhus/dev/unicorn/foo.js' +}; +``` + +```js +// foo.js +const bar = require('./bar'); + +bar(); +``` + + +## API + +### parentModule([filepath]) + +By default, it will return the path of the immediate parent. + +#### filepath + +Type: `string`
+Default: [`__filename`](https://nodejs.org/api/globals.html#globals_filename) + +Filepath of the module of which to get the parent path. + +Useful if you want it to work [multiple module levels down](https://github.com/sindresorhus/parent-module/tree/master/fixtures/filepath). + + +## Tip + +Combine it with [`read-pkg-up`](https://github.com/sindresorhus/read-pkg-up) to read the package.json of the parent module. + +```js +const path = require('path'); +const readPkgUp = require('read-pkg-up'); +const parentModule = require('parent-module'); + +console.log(readPkgUp.sync({cwd: path.dirname(parentModule())}).pkg); +//=> {name: 'chalk', version: '1.0.0', …} +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/tools/ui/node_modules/parse5/LICENSE b/tools/ui/node_modules/parse5/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f3265d4b88f7aac271ec21679195adff8446855e --- /dev/null +++ b/tools/ui/node_modules/parse5/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2019 Ivan Nikulin (ifaaan@gmail.com, https://github.com/inikulin) + +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. diff --git a/tools/ui/node_modules/parse5/README.md b/tools/ui/node_modules/parse5/README.md new file mode 100644 index 0000000000000000000000000000000000000000..139f8c6ae03cd80b0696e78a3d79c5132aeb1d19 --- /dev/null +++ b/tools/ui/node_modules/parse5/README.md @@ -0,0 +1,38 @@ +

+ + parse5 + +

+ +
+

parse5

+HTML parser and serializer. +
+
+ +
+npm install --save parse5 +
+
+ +

+ 📖 Documentation 📖 +

+ +--- + +

+ List of parse5 toolset packages +

+ +

+ GitHub +

+ +

+ Online playground +

+ +

+ Changelog +

diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/doctype.d.ts b/tools/ui/node_modules/parse5/dist/cjs/common/doctype.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..993afaac5b5b5a808eb4a32c9707c3ec052442b4 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/doctype.d.ts @@ -0,0 +1,4 @@ +import { DOCUMENT_MODE } from './html.js'; +import type { DoctypeToken } from './token.js'; +export declare function isConforming(token: DoctypeToken): boolean; +export declare function getDocumentMode(token: DoctypeToken): DOCUMENT_MODE; diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/doctype.js b/tools/ui/node_modules/parse5/dist/cjs/common/doctype.js new file mode 100644 index 0000000000000000000000000000000000000000..82aed98535a69c1255f4820cfdbe6157261d362e --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/doctype.js @@ -0,0 +1,118 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isConforming = isConforming; +exports.getDocumentMode = getDocumentMode; +const html_js_1 = require("./html.js"); +//Const +const VALID_DOCTYPE_NAME = 'html'; +const VALID_SYSTEM_ID = 'about:legacy-compat'; +const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; +const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [ + '+//silmaril//dtd html pro v0r11 19970101//', + '-//as//dtd html 3.0 aswedit + extensions//', + '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', + '-//ietf//dtd html 2.0 level 1//', + '-//ietf//dtd html 2.0 level 2//', + '-//ietf//dtd html 2.0 strict level 1//', + '-//ietf//dtd html 2.0 strict level 2//', + '-//ietf//dtd html 2.0 strict//', + '-//ietf//dtd html 2.0//', + '-//ietf//dtd html 2.1e//', + '-//ietf//dtd html 3.0//', + '-//ietf//dtd html 3.2 final//', + '-//ietf//dtd html 3.2//', + '-//ietf//dtd html 3//', + '-//ietf//dtd html level 0//', + '-//ietf//dtd html level 1//', + '-//ietf//dtd html level 2//', + '-//ietf//dtd html level 3//', + '-//ietf//dtd html strict level 0//', + '-//ietf//dtd html strict level 1//', + '-//ietf//dtd html strict level 2//', + '-//ietf//dtd html strict level 3//', + '-//ietf//dtd html strict//', + '-//ietf//dtd html//', + '-//metrius//dtd metrius presentational//', + '-//microsoft//dtd internet explorer 2.0 html strict//', + '-//microsoft//dtd internet explorer 2.0 html//', + '-//microsoft//dtd internet explorer 2.0 tables//', + '-//microsoft//dtd internet explorer 3.0 html strict//', + '-//microsoft//dtd internet explorer 3.0 html//', + '-//microsoft//dtd internet explorer 3.0 tables//', + '-//netscape comm. corp.//dtd html//', + '-//netscape comm. corp.//dtd strict html//', + "-//o'reilly and associates//dtd html 2.0//", + "-//o'reilly and associates//dtd html extended 1.0//", + "-//o'reilly and associates//dtd html extended relaxed 1.0//", + '-//sq//dtd html 2.0 hotmetal + extensions//', + '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', + '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', + '-//spyglass//dtd html 2.0 extended//', + '-//sun microsystems corp.//dtd hotjava html//', + '-//sun microsystems corp.//dtd hotjava strict html//', + '-//w3c//dtd html 3 1995-03-24//', + '-//w3c//dtd html 3.2 draft//', + '-//w3c//dtd html 3.2 final//', + '-//w3c//dtd html 3.2//', + '-//w3c//dtd html 3.2s draft//', + '-//w3c//dtd html 4.0 frameset//', + '-//w3c//dtd html 4.0 transitional//', + '-//w3c//dtd html experimental 19960712//', + '-//w3c//dtd html experimental 970421//', + '-//w3c//dtd w3 html//', + '-//w3o//dtd w3 html 3.0//', + '-//webtechs//dtd mozilla html 2.0//', + '-//webtechs//dtd mozilla html//', +]; +const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [ + ...QUIRKS_MODE_PUBLIC_ID_PREFIXES, + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//', +]; +const QUIRKS_MODE_PUBLIC_IDS = new Set([ + '-//w3o//dtd w3 html strict 3.0//en//', + '-/w3c/dtd html 4.0 transitional/en', + 'html', +]); +const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//']; +const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [ + ...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES, + '-//w3c//dtd html 4.01 frameset//', + '-//w3c//dtd html 4.01 transitional//', +]; +//Utils +function hasPrefix(publicId, prefixes) { + return prefixes.some((prefix) => publicId.startsWith(prefix)); +} +//API +function isConforming(token) { + return (token.name === VALID_DOCTYPE_NAME && + token.publicId === null && + (token.systemId === null || token.systemId === VALID_SYSTEM_ID)); +} +function getDocumentMode(token) { + if (token.name !== VALID_DOCTYPE_NAME) { + return html_js_1.DOCUMENT_MODE.QUIRKS; + } + const { systemId } = token; + if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) { + return html_js_1.DOCUMENT_MODE.QUIRKS; + } + let { publicId } = token; + if (publicId !== null) { + publicId = publicId.toLowerCase(); + if (QUIRKS_MODE_PUBLIC_IDS.has(publicId)) { + return html_js_1.DOCUMENT_MODE.QUIRKS; + } + let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES; + if (hasPrefix(publicId, prefixes)) { + return html_js_1.DOCUMENT_MODE.QUIRKS; + } + prefixes = + systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES; + if (hasPrefix(publicId, prefixes)) { + return html_js_1.DOCUMENT_MODE.LIMITED_QUIRKS; + } + } + return html_js_1.DOCUMENT_MODE.NO_QUIRKS; +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/error-codes.d.ts b/tools/ui/node_modules/parse5/dist/cjs/common/error-codes.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac15bb3b605c59af68a87be1ade6803d7a258ae8 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/error-codes.d.ts @@ -0,0 +1,67 @@ +import type { Location } from './token.js'; +export interface ParserError extends Location { + code: ERR; +} +export type ParserErrorHandler = (error: ParserError) => void; +export declare enum ERR { + controlCharacterInInputStream = "control-character-in-input-stream", + noncharacterInInputStream = "noncharacter-in-input-stream", + surrogateInInputStream = "surrogate-in-input-stream", + nonVoidHtmlElementStartTagWithTrailingSolidus = "non-void-html-element-start-tag-with-trailing-solidus", + endTagWithAttributes = "end-tag-with-attributes", + endTagWithTrailingSolidus = "end-tag-with-trailing-solidus", + unexpectedSolidusInTag = "unexpected-solidus-in-tag", + unexpectedNullCharacter = "unexpected-null-character", + unexpectedQuestionMarkInsteadOfTagName = "unexpected-question-mark-instead-of-tag-name", + invalidFirstCharacterOfTagName = "invalid-first-character-of-tag-name", + unexpectedEqualsSignBeforeAttributeName = "unexpected-equals-sign-before-attribute-name", + missingEndTagName = "missing-end-tag-name", + unexpectedCharacterInAttributeName = "unexpected-character-in-attribute-name", + unknownNamedCharacterReference = "unknown-named-character-reference", + missingSemicolonAfterCharacterReference = "missing-semicolon-after-character-reference", + unexpectedCharacterAfterDoctypeSystemIdentifier = "unexpected-character-after-doctype-system-identifier", + unexpectedCharacterInUnquotedAttributeValue = "unexpected-character-in-unquoted-attribute-value", + eofBeforeTagName = "eof-before-tag-name", + eofInTag = "eof-in-tag", + missingAttributeValue = "missing-attribute-value", + missingWhitespaceBetweenAttributes = "missing-whitespace-between-attributes", + missingWhitespaceAfterDoctypePublicKeyword = "missing-whitespace-after-doctype-public-keyword", + missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers = "missing-whitespace-between-doctype-public-and-system-identifiers", + missingWhitespaceAfterDoctypeSystemKeyword = "missing-whitespace-after-doctype-system-keyword", + missingQuoteBeforeDoctypePublicIdentifier = "missing-quote-before-doctype-public-identifier", + missingQuoteBeforeDoctypeSystemIdentifier = "missing-quote-before-doctype-system-identifier", + missingDoctypePublicIdentifier = "missing-doctype-public-identifier", + missingDoctypeSystemIdentifier = "missing-doctype-system-identifier", + abruptDoctypePublicIdentifier = "abrupt-doctype-public-identifier", + abruptDoctypeSystemIdentifier = "abrupt-doctype-system-identifier", + cdataInHtmlContent = "cdata-in-html-content", + incorrectlyOpenedComment = "incorrectly-opened-comment", + eofInScriptHtmlCommentLikeText = "eof-in-script-html-comment-like-text", + eofInDoctype = "eof-in-doctype", + nestedComment = "nested-comment", + abruptClosingOfEmptyComment = "abrupt-closing-of-empty-comment", + eofInComment = "eof-in-comment", + incorrectlyClosedComment = "incorrectly-closed-comment", + eofInCdata = "eof-in-cdata", + absenceOfDigitsInNumericCharacterReference = "absence-of-digits-in-numeric-character-reference", + nullCharacterReference = "null-character-reference", + surrogateCharacterReference = "surrogate-character-reference", + characterReferenceOutsideUnicodeRange = "character-reference-outside-unicode-range", + controlCharacterReference = "control-character-reference", + noncharacterCharacterReference = "noncharacter-character-reference", + missingWhitespaceBeforeDoctypeName = "missing-whitespace-before-doctype-name", + missingDoctypeName = "missing-doctype-name", + invalidCharacterSequenceAfterDoctypeName = "invalid-character-sequence-after-doctype-name", + duplicateAttribute = "duplicate-attribute", + nonConformingDoctype = "non-conforming-doctype", + missingDoctype = "missing-doctype", + misplacedDoctype = "misplaced-doctype", + endTagWithoutMatchingOpenElement = "end-tag-without-matching-open-element", + closingOfElementWithOpenChildElements = "closing-of-element-with-open-child-elements", + disallowedContentInNoscriptInHead = "disallowed-content-in-noscript-in-head", + openElementsLeftAfterEof = "open-elements-left-after-eof", + abandonedHeadElementChild = "abandoned-head-element-child", + misplacedStartTagForHeadElement = "misplaced-start-tag-for-head-element", + nestedNoscriptInHead = "nested-noscript-in-head", + eofInElementThatCanContainOnlyText = "eof-in-element-that-can-contain-only-text" +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/error-codes.js b/tools/ui/node_modules/parse5/dist/cjs/common/error-codes.js new file mode 100644 index 0000000000000000000000000000000000000000..573e68e5be6d563e621b51e8a299ef7d77000550 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/error-codes.js @@ -0,0 +1,66 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ERR = void 0; +var ERR; +(function (ERR) { + ERR["controlCharacterInInputStream"] = "control-character-in-input-stream"; + ERR["noncharacterInInputStream"] = "noncharacter-in-input-stream"; + ERR["surrogateInInputStream"] = "surrogate-in-input-stream"; + ERR["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus"; + ERR["endTagWithAttributes"] = "end-tag-with-attributes"; + ERR["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus"; + ERR["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag"; + ERR["unexpectedNullCharacter"] = "unexpected-null-character"; + ERR["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name"; + ERR["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name"; + ERR["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name"; + ERR["missingEndTagName"] = "missing-end-tag-name"; + ERR["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name"; + ERR["unknownNamedCharacterReference"] = "unknown-named-character-reference"; + ERR["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference"; + ERR["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier"; + ERR["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value"; + ERR["eofBeforeTagName"] = "eof-before-tag-name"; + ERR["eofInTag"] = "eof-in-tag"; + ERR["missingAttributeValue"] = "missing-attribute-value"; + ERR["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes"; + ERR["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword"; + ERR["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers"; + ERR["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword"; + ERR["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier"; + ERR["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier"; + ERR["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier"; + ERR["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier"; + ERR["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier"; + ERR["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier"; + ERR["cdataInHtmlContent"] = "cdata-in-html-content"; + ERR["incorrectlyOpenedComment"] = "incorrectly-opened-comment"; + ERR["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text"; + ERR["eofInDoctype"] = "eof-in-doctype"; + ERR["nestedComment"] = "nested-comment"; + ERR["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment"; + ERR["eofInComment"] = "eof-in-comment"; + ERR["incorrectlyClosedComment"] = "incorrectly-closed-comment"; + ERR["eofInCdata"] = "eof-in-cdata"; + ERR["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference"; + ERR["nullCharacterReference"] = "null-character-reference"; + ERR["surrogateCharacterReference"] = "surrogate-character-reference"; + ERR["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range"; + ERR["controlCharacterReference"] = "control-character-reference"; + ERR["noncharacterCharacterReference"] = "noncharacter-character-reference"; + ERR["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name"; + ERR["missingDoctypeName"] = "missing-doctype-name"; + ERR["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name"; + ERR["duplicateAttribute"] = "duplicate-attribute"; + ERR["nonConformingDoctype"] = "non-conforming-doctype"; + ERR["missingDoctype"] = "missing-doctype"; + ERR["misplacedDoctype"] = "misplaced-doctype"; + ERR["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element"; + ERR["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements"; + ERR["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head"; + ERR["openElementsLeftAfterEof"] = "open-elements-left-after-eof"; + ERR["abandonedHeadElementChild"] = "abandoned-head-element-child"; + ERR["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element"; + ERR["nestedNoscriptInHead"] = "nested-noscript-in-head"; + ERR["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text"; +})(ERR || (exports.ERR = ERR = {})); diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/foreign-content.d.ts b/tools/ui/node_modules/parse5/dist/cjs/common/foreign-content.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d08d02b2cbdca814cea75bf32575636ccebd801e --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/foreign-content.d.ts @@ -0,0 +1,9 @@ +import { TAG_ID as $, NS } from './html.js'; +import type { TagToken, Attribute } from './token.js'; +export declare const SVG_TAG_NAMES_ADJUSTMENT_MAP: Map; +export declare function causesExit(startTagToken: TagToken): boolean; +export declare function adjustTokenMathMLAttrs(token: TagToken): void; +export declare function adjustTokenSVGAttrs(token: TagToken): void; +export declare function adjustTokenXMLAttrs(token: TagToken): void; +export declare function adjustTokenSVGTagName(token: TagToken): void; +export declare function isIntegrationPoint(tn: $, ns: NS, attrs: Attribute[], foreignNS?: NS): boolean; diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/foreign-content.js b/tools/ui/node_modules/parse5/dist/cjs/common/foreign-content.js new file mode 100644 index 0000000000000000000000000000000000000000..2015b0c7b045bdc99a1483f885fb4364d2b505c1 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/foreign-content.js @@ -0,0 +1,237 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = void 0; +exports.causesExit = causesExit; +exports.adjustTokenMathMLAttrs = adjustTokenMathMLAttrs; +exports.adjustTokenSVGAttrs = adjustTokenSVGAttrs; +exports.adjustTokenXMLAttrs = adjustTokenXMLAttrs; +exports.adjustTokenSVGTagName = adjustTokenSVGTagName; +exports.isIntegrationPoint = isIntegrationPoint; +const html_js_1 = require("./html.js"); +//MIME types +const MIME_TYPES = { + TEXT_HTML: 'text/html', + APPLICATION_XML: 'application/xhtml+xml', +}; +//Attributes +const DEFINITION_URL_ATTR = 'definitionurl'; +const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL'; +const SVG_ATTRS_ADJUSTMENT_MAP = new Map([ + 'attributeName', + 'attributeType', + 'baseFrequency', + 'baseProfile', + 'calcMode', + 'clipPathUnits', + 'diffuseConstant', + 'edgeMode', + 'filterUnits', + 'glyphRef', + 'gradientTransform', + 'gradientUnits', + 'kernelMatrix', + 'kernelUnitLength', + 'keyPoints', + 'keySplines', + 'keyTimes', + 'lengthAdjust', + 'limitingConeAngle', + 'markerHeight', + 'markerUnits', + 'markerWidth', + 'maskContentUnits', + 'maskUnits', + 'numOctaves', + 'pathLength', + 'patternContentUnits', + 'patternTransform', + 'patternUnits', + 'pointsAtX', + 'pointsAtY', + 'pointsAtZ', + 'preserveAlpha', + 'preserveAspectRatio', + 'primitiveUnits', + 'refX', + 'refY', + 'repeatCount', + 'repeatDur', + 'requiredExtensions', + 'requiredFeatures', + 'specularConstant', + 'specularExponent', + 'spreadMethod', + 'startOffset', + 'stdDeviation', + 'stitchTiles', + 'surfaceScale', + 'systemLanguage', + 'tableValues', + 'targetX', + 'targetY', + 'textLength', + 'viewBox', + 'viewTarget', + 'xChannelSelector', + 'yChannelSelector', + 'zoomAndPan', +].map((attr) => [attr.toLowerCase(), attr])); +const XML_ATTRS_ADJUSTMENT_MAP = new Map([ + ['xlink:actuate', { prefix: 'xlink', name: 'actuate', namespace: html_js_1.NS.XLINK }], + ['xlink:arcrole', { prefix: 'xlink', name: 'arcrole', namespace: html_js_1.NS.XLINK }], + ['xlink:href', { prefix: 'xlink', name: 'href', namespace: html_js_1.NS.XLINK }], + ['xlink:role', { prefix: 'xlink', name: 'role', namespace: html_js_1.NS.XLINK }], + ['xlink:show', { prefix: 'xlink', name: 'show', namespace: html_js_1.NS.XLINK }], + ['xlink:title', { prefix: 'xlink', name: 'title', namespace: html_js_1.NS.XLINK }], + ['xlink:type', { prefix: 'xlink', name: 'type', namespace: html_js_1.NS.XLINK }], + ['xml:lang', { prefix: 'xml', name: 'lang', namespace: html_js_1.NS.XML }], + ['xml:space', { prefix: 'xml', name: 'space', namespace: html_js_1.NS.XML }], + ['xmlns', { prefix: '', name: 'xmlns', namespace: html_js_1.NS.XMLNS }], + ['xmlns:xlink', { prefix: 'xmlns', name: 'xlink', namespace: html_js_1.NS.XMLNS }], +]); +//SVG tag names adjustment map +exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([ + 'altGlyph', + 'altGlyphDef', + 'altGlyphItem', + 'animateColor', + 'animateMotion', + 'animateTransform', + 'clipPath', + 'feBlend', + 'feColorMatrix', + 'feComponentTransfer', + 'feComposite', + 'feConvolveMatrix', + 'feDiffuseLighting', + 'feDisplacementMap', + 'feDistantLight', + 'feFlood', + 'feFuncA', + 'feFuncB', + 'feFuncG', + 'feFuncR', + 'feGaussianBlur', + 'feImage', + 'feMerge', + 'feMergeNode', + 'feMorphology', + 'feOffset', + 'fePointLight', + 'feSpecularLighting', + 'feSpotLight', + 'feTile', + 'feTurbulence', + 'foreignObject', + 'glyphRef', + 'linearGradient', + 'radialGradient', + 'textPath', +].map((tn) => [tn.toLowerCase(), tn])); +//Tags that causes exit from foreign content +const EXITS_FOREIGN_CONTENT = new Set([ + html_js_1.TAG_ID.B, + html_js_1.TAG_ID.BIG, + html_js_1.TAG_ID.BLOCKQUOTE, + html_js_1.TAG_ID.BODY, + html_js_1.TAG_ID.BR, + html_js_1.TAG_ID.CENTER, + html_js_1.TAG_ID.CODE, + html_js_1.TAG_ID.DD, + html_js_1.TAG_ID.DIV, + html_js_1.TAG_ID.DL, + html_js_1.TAG_ID.DT, + html_js_1.TAG_ID.EM, + html_js_1.TAG_ID.EMBED, + html_js_1.TAG_ID.H1, + html_js_1.TAG_ID.H2, + html_js_1.TAG_ID.H3, + html_js_1.TAG_ID.H4, + html_js_1.TAG_ID.H5, + html_js_1.TAG_ID.H6, + html_js_1.TAG_ID.HEAD, + html_js_1.TAG_ID.HR, + html_js_1.TAG_ID.I, + html_js_1.TAG_ID.IMG, + html_js_1.TAG_ID.LI, + html_js_1.TAG_ID.LISTING, + html_js_1.TAG_ID.MENU, + html_js_1.TAG_ID.META, + html_js_1.TAG_ID.NOBR, + html_js_1.TAG_ID.OL, + html_js_1.TAG_ID.P, + html_js_1.TAG_ID.PRE, + html_js_1.TAG_ID.RUBY, + html_js_1.TAG_ID.S, + html_js_1.TAG_ID.SMALL, + html_js_1.TAG_ID.SPAN, + html_js_1.TAG_ID.STRONG, + html_js_1.TAG_ID.STRIKE, + html_js_1.TAG_ID.SUB, + html_js_1.TAG_ID.SUP, + html_js_1.TAG_ID.TABLE, + html_js_1.TAG_ID.TT, + html_js_1.TAG_ID.U, + html_js_1.TAG_ID.UL, + html_js_1.TAG_ID.VAR, +]); +//Check exit from foreign content +function causesExit(startTagToken) { + const tn = startTagToken.tagID; + const isFontWithAttrs = tn === html_js_1.TAG_ID.FONT && + startTagToken.attrs.some(({ name }) => name === html_js_1.ATTRS.COLOR || name === html_js_1.ATTRS.SIZE || name === html_js_1.ATTRS.FACE); + return isFontWithAttrs || EXITS_FOREIGN_CONTENT.has(tn); +} +//Token adjustments +function adjustTokenMathMLAttrs(token) { + for (let i = 0; i < token.attrs.length; i++) { + if (token.attrs[i].name === DEFINITION_URL_ATTR) { + token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR; + break; + } + } +} +function adjustTokenSVGAttrs(token) { + for (let i = 0; i < token.attrs.length; i++) { + const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name); + if (adjustedAttrName != null) { + token.attrs[i].name = adjustedAttrName; + } + } +} +function adjustTokenXMLAttrs(token) { + for (let i = 0; i < token.attrs.length; i++) { + const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name); + if (adjustedAttrEntry) { + token.attrs[i].prefix = adjustedAttrEntry.prefix; + token.attrs[i].name = adjustedAttrEntry.name; + token.attrs[i].namespace = adjustedAttrEntry.namespace; + } + } +} +function adjustTokenSVGTagName(token) { + const adjustedTagName = exports.SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName); + if (adjustedTagName != null) { + token.tagName = adjustedTagName; + token.tagID = (0, html_js_1.getTagID)(token.tagName); + } +} +//Integration points +function isMathMLTextIntegrationPoint(tn, ns) { + return ns === html_js_1.NS.MATHML && (tn === html_js_1.TAG_ID.MI || tn === html_js_1.TAG_ID.MO || tn === html_js_1.TAG_ID.MN || tn === html_js_1.TAG_ID.MS || tn === html_js_1.TAG_ID.MTEXT); +} +function isHtmlIntegrationPoint(tn, ns, attrs) { + if (ns === html_js_1.NS.MATHML && tn === html_js_1.TAG_ID.ANNOTATION_XML) { + for (let i = 0; i < attrs.length; i++) { + if (attrs[i].name === html_js_1.ATTRS.ENCODING) { + const value = attrs[i].value.toLowerCase(); + return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML; + } + } + } + return ns === html_js_1.NS.SVG && (tn === html_js_1.TAG_ID.FOREIGN_OBJECT || tn === html_js_1.TAG_ID.DESC || tn === html_js_1.TAG_ID.TITLE); +} +function isIntegrationPoint(tn, ns, attrs, foreignNS) { + return (((!foreignNS || foreignNS === html_js_1.NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) || + ((!foreignNS || foreignNS === html_js_1.NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns))); +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/html.d.ts b/tools/ui/node_modules/parse5/dist/cjs/common/html.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fbc821439e955b166762442e75d54e2c20018a0 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/html.d.ts @@ -0,0 +1,289 @@ +/** All valid namespaces in HTML. */ +export declare enum NS { + HTML = "http://www.w3.org/1999/xhtml", + MATHML = "http://www.w3.org/1998/Math/MathML", + SVG = "http://www.w3.org/2000/svg", + XLINK = "http://www.w3.org/1999/xlink", + XML = "http://www.w3.org/XML/1998/namespace", + XMLNS = "http://www.w3.org/2000/xmlns/" +} +export declare enum ATTRS { + TYPE = "type", + ACTION = "action", + ENCODING = "encoding", + PROMPT = "prompt", + NAME = "name", + COLOR = "color", + FACE = "face", + SIZE = "size" +} +/** + * The mode of the document. + * + * @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks} + */ +export declare enum DOCUMENT_MODE { + NO_QUIRKS = "no-quirks", + QUIRKS = "quirks", + LIMITED_QUIRKS = "limited-quirks" +} +export declare enum TAG_NAMES { + A = "a", + ADDRESS = "address", + ANNOTATION_XML = "annotation-xml", + APPLET = "applet", + AREA = "area", + ARTICLE = "article", + ASIDE = "aside", + B = "b", + BASE = "base", + BASEFONT = "basefont", + BGSOUND = "bgsound", + BIG = "big", + BLOCKQUOTE = "blockquote", + BODY = "body", + BR = "br", + BUTTON = "button", + CAPTION = "caption", + CENTER = "center", + CODE = "code", + COL = "col", + COLGROUP = "colgroup", + DD = "dd", + DESC = "desc", + DETAILS = "details", + DIALOG = "dialog", + DIR = "dir", + DIV = "div", + DL = "dl", + DT = "dt", + EM = "em", + EMBED = "embed", + FIELDSET = "fieldset", + FIGCAPTION = "figcaption", + FIGURE = "figure", + FONT = "font", + FOOTER = "footer", + FOREIGN_OBJECT = "foreignObject", + FORM = "form", + FRAME = "frame", + FRAMESET = "frameset", + H1 = "h1", + H2 = "h2", + H3 = "h3", + H4 = "h4", + H5 = "h5", + H6 = "h6", + HEAD = "head", + HEADER = "header", + HGROUP = "hgroup", + HR = "hr", + HTML = "html", + I = "i", + IMG = "img", + IMAGE = "image", + INPUT = "input", + IFRAME = "iframe", + KEYGEN = "keygen", + LABEL = "label", + LI = "li", + LINK = "link", + LISTING = "listing", + MAIN = "main", + MALIGNMARK = "malignmark", + MARQUEE = "marquee", + MATH = "math", + MENU = "menu", + META = "meta", + MGLYPH = "mglyph", + MI = "mi", + MO = "mo", + MN = "mn", + MS = "ms", + MTEXT = "mtext", + NAV = "nav", + NOBR = "nobr", + NOFRAMES = "noframes", + NOEMBED = "noembed", + NOSCRIPT = "noscript", + OBJECT = "object", + OL = "ol", + OPTGROUP = "optgroup", + OPTION = "option", + P = "p", + PARAM = "param", + PLAINTEXT = "plaintext", + PRE = "pre", + RB = "rb", + RP = "rp", + RT = "rt", + RTC = "rtc", + RUBY = "ruby", + S = "s", + SCRIPT = "script", + SEARCH = "search", + SECTION = "section", + SELECT = "select", + SOURCE = "source", + SMALL = "small", + SPAN = "span", + STRIKE = "strike", + STRONG = "strong", + STYLE = "style", + SUB = "sub", + SUMMARY = "summary", + SUP = "sup", + TABLE = "table", + TBODY = "tbody", + TEMPLATE = "template", + TEXTAREA = "textarea", + TFOOT = "tfoot", + TD = "td", + TH = "th", + THEAD = "thead", + TITLE = "title", + TR = "tr", + TRACK = "track", + TT = "tt", + U = "u", + UL = "ul", + SVG = "svg", + VAR = "var", + WBR = "wbr", + XMP = "xmp" +} +/** + * Tag IDs are numeric IDs for known tag names. + * + * We use tag IDs to improve the performance of tag name comparisons. + */ +export declare enum TAG_ID { + UNKNOWN = 0, + A = 1, + ADDRESS = 2, + ANNOTATION_XML = 3, + APPLET = 4, + AREA = 5, + ARTICLE = 6, + ASIDE = 7, + B = 8, + BASE = 9, + BASEFONT = 10, + BGSOUND = 11, + BIG = 12, + BLOCKQUOTE = 13, + BODY = 14, + BR = 15, + BUTTON = 16, + CAPTION = 17, + CENTER = 18, + CODE = 19, + COL = 20, + COLGROUP = 21, + DD = 22, + DESC = 23, + DETAILS = 24, + DIALOG = 25, + DIR = 26, + DIV = 27, + DL = 28, + DT = 29, + EM = 30, + EMBED = 31, + FIELDSET = 32, + FIGCAPTION = 33, + FIGURE = 34, + FONT = 35, + FOOTER = 36, + FOREIGN_OBJECT = 37, + FORM = 38, + FRAME = 39, + FRAMESET = 40, + H1 = 41, + H2 = 42, + H3 = 43, + H4 = 44, + H5 = 45, + H6 = 46, + HEAD = 47, + HEADER = 48, + HGROUP = 49, + HR = 50, + HTML = 51, + I = 52, + IMG = 53, + IMAGE = 54, + INPUT = 55, + IFRAME = 56, + KEYGEN = 57, + LABEL = 58, + LI = 59, + LINK = 60, + LISTING = 61, + MAIN = 62, + MALIGNMARK = 63, + MARQUEE = 64, + MATH = 65, + MENU = 66, + META = 67, + MGLYPH = 68, + MI = 69, + MO = 70, + MN = 71, + MS = 72, + MTEXT = 73, + NAV = 74, + NOBR = 75, + NOFRAMES = 76, + NOEMBED = 77, + NOSCRIPT = 78, + OBJECT = 79, + OL = 80, + OPTGROUP = 81, + OPTION = 82, + P = 83, + PARAM = 84, + PLAINTEXT = 85, + PRE = 86, + RB = 87, + RP = 88, + RT = 89, + RTC = 90, + RUBY = 91, + S = 92, + SCRIPT = 93, + SEARCH = 94, + SECTION = 95, + SELECT = 96, + SOURCE = 97, + SMALL = 98, + SPAN = 99, + STRIKE = 100, + STRONG = 101, + STYLE = 102, + SUB = 103, + SUMMARY = 104, + SUP = 105, + TABLE = 106, + TBODY = 107, + TEMPLATE = 108, + TEXTAREA = 109, + TFOOT = 110, + TD = 111, + TH = 112, + THEAD = 113, + TITLE = 114, + TR = 115, + TRACK = 116, + TT = 117, + U = 118, + UL = 119, + SVG = 120, + VAR = 121, + WBR = 122, + XMP = 123 +} +export declare function getTagID(tagName: string): TAG_ID; +export declare const SPECIAL_ELEMENTS: Record>; +export declare const NUMBERED_HEADERS: Set; +export declare function hasUnescapedText(tn: string, scriptingEnabled: boolean): boolean; diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/html.js b/tools/ui/node_modules/parse5/dist/cjs/common/html.js new file mode 100644 index 0000000000000000000000000000000000000000..d18fc4488c4173d450d45c3432d52960b4413922 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/html.js @@ -0,0 +1,528 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NUMBERED_HEADERS = exports.SPECIAL_ELEMENTS = exports.TAG_ID = exports.TAG_NAMES = exports.DOCUMENT_MODE = exports.ATTRS = exports.NS = void 0; +exports.getTagID = getTagID; +exports.hasUnescapedText = hasUnescapedText; +/** All valid namespaces in HTML. */ +var NS; +(function (NS) { + NS["HTML"] = "http://www.w3.org/1999/xhtml"; + NS["MATHML"] = "http://www.w3.org/1998/Math/MathML"; + NS["SVG"] = "http://www.w3.org/2000/svg"; + NS["XLINK"] = "http://www.w3.org/1999/xlink"; + NS["XML"] = "http://www.w3.org/XML/1998/namespace"; + NS["XMLNS"] = "http://www.w3.org/2000/xmlns/"; +})(NS || (exports.NS = NS = {})); +var ATTRS; +(function (ATTRS) { + ATTRS["TYPE"] = "type"; + ATTRS["ACTION"] = "action"; + ATTRS["ENCODING"] = "encoding"; + ATTRS["PROMPT"] = "prompt"; + ATTRS["NAME"] = "name"; + ATTRS["COLOR"] = "color"; + ATTRS["FACE"] = "face"; + ATTRS["SIZE"] = "size"; +})(ATTRS || (exports.ATTRS = ATTRS = {})); +/** + * The mode of the document. + * + * @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks} + */ +var DOCUMENT_MODE; +(function (DOCUMENT_MODE) { + DOCUMENT_MODE["NO_QUIRKS"] = "no-quirks"; + DOCUMENT_MODE["QUIRKS"] = "quirks"; + DOCUMENT_MODE["LIMITED_QUIRKS"] = "limited-quirks"; +})(DOCUMENT_MODE || (exports.DOCUMENT_MODE = DOCUMENT_MODE = {})); +var TAG_NAMES; +(function (TAG_NAMES) { + TAG_NAMES["A"] = "a"; + TAG_NAMES["ADDRESS"] = "address"; + TAG_NAMES["ANNOTATION_XML"] = "annotation-xml"; + TAG_NAMES["APPLET"] = "applet"; + TAG_NAMES["AREA"] = "area"; + TAG_NAMES["ARTICLE"] = "article"; + TAG_NAMES["ASIDE"] = "aside"; + TAG_NAMES["B"] = "b"; + TAG_NAMES["BASE"] = "base"; + TAG_NAMES["BASEFONT"] = "basefont"; + TAG_NAMES["BGSOUND"] = "bgsound"; + TAG_NAMES["BIG"] = "big"; + TAG_NAMES["BLOCKQUOTE"] = "blockquote"; + TAG_NAMES["BODY"] = "body"; + TAG_NAMES["BR"] = "br"; + TAG_NAMES["BUTTON"] = "button"; + TAG_NAMES["CAPTION"] = "caption"; + TAG_NAMES["CENTER"] = "center"; + TAG_NAMES["CODE"] = "code"; + TAG_NAMES["COL"] = "col"; + TAG_NAMES["COLGROUP"] = "colgroup"; + TAG_NAMES["DD"] = "dd"; + TAG_NAMES["DESC"] = "desc"; + TAG_NAMES["DETAILS"] = "details"; + TAG_NAMES["DIALOG"] = "dialog"; + TAG_NAMES["DIR"] = "dir"; + TAG_NAMES["DIV"] = "div"; + TAG_NAMES["DL"] = "dl"; + TAG_NAMES["DT"] = "dt"; + TAG_NAMES["EM"] = "em"; + TAG_NAMES["EMBED"] = "embed"; + TAG_NAMES["FIELDSET"] = "fieldset"; + TAG_NAMES["FIGCAPTION"] = "figcaption"; + TAG_NAMES["FIGURE"] = "figure"; + TAG_NAMES["FONT"] = "font"; + TAG_NAMES["FOOTER"] = "footer"; + TAG_NAMES["FOREIGN_OBJECT"] = "foreignObject"; + TAG_NAMES["FORM"] = "form"; + TAG_NAMES["FRAME"] = "frame"; + TAG_NAMES["FRAMESET"] = "frameset"; + TAG_NAMES["H1"] = "h1"; + TAG_NAMES["H2"] = "h2"; + TAG_NAMES["H3"] = "h3"; + TAG_NAMES["H4"] = "h4"; + TAG_NAMES["H5"] = "h5"; + TAG_NAMES["H6"] = "h6"; + TAG_NAMES["HEAD"] = "head"; + TAG_NAMES["HEADER"] = "header"; + TAG_NAMES["HGROUP"] = "hgroup"; + TAG_NAMES["HR"] = "hr"; + TAG_NAMES["HTML"] = "html"; + TAG_NAMES["I"] = "i"; + TAG_NAMES["IMG"] = "img"; + TAG_NAMES["IMAGE"] = "image"; + TAG_NAMES["INPUT"] = "input"; + TAG_NAMES["IFRAME"] = "iframe"; + TAG_NAMES["KEYGEN"] = "keygen"; + TAG_NAMES["LABEL"] = "label"; + TAG_NAMES["LI"] = "li"; + TAG_NAMES["LINK"] = "link"; + TAG_NAMES["LISTING"] = "listing"; + TAG_NAMES["MAIN"] = "main"; + TAG_NAMES["MALIGNMARK"] = "malignmark"; + TAG_NAMES["MARQUEE"] = "marquee"; + TAG_NAMES["MATH"] = "math"; + TAG_NAMES["MENU"] = "menu"; + TAG_NAMES["META"] = "meta"; + TAG_NAMES["MGLYPH"] = "mglyph"; + TAG_NAMES["MI"] = "mi"; + TAG_NAMES["MO"] = "mo"; + TAG_NAMES["MN"] = "mn"; + TAG_NAMES["MS"] = "ms"; + TAG_NAMES["MTEXT"] = "mtext"; + TAG_NAMES["NAV"] = "nav"; + TAG_NAMES["NOBR"] = "nobr"; + TAG_NAMES["NOFRAMES"] = "noframes"; + TAG_NAMES["NOEMBED"] = "noembed"; + TAG_NAMES["NOSCRIPT"] = "noscript"; + TAG_NAMES["OBJECT"] = "object"; + TAG_NAMES["OL"] = "ol"; + TAG_NAMES["OPTGROUP"] = "optgroup"; + TAG_NAMES["OPTION"] = "option"; + TAG_NAMES["P"] = "p"; + TAG_NAMES["PARAM"] = "param"; + TAG_NAMES["PLAINTEXT"] = "plaintext"; + TAG_NAMES["PRE"] = "pre"; + TAG_NAMES["RB"] = "rb"; + TAG_NAMES["RP"] = "rp"; + TAG_NAMES["RT"] = "rt"; + TAG_NAMES["RTC"] = "rtc"; + TAG_NAMES["RUBY"] = "ruby"; + TAG_NAMES["S"] = "s"; + TAG_NAMES["SCRIPT"] = "script"; + TAG_NAMES["SEARCH"] = "search"; + TAG_NAMES["SECTION"] = "section"; + TAG_NAMES["SELECT"] = "select"; + TAG_NAMES["SOURCE"] = "source"; + TAG_NAMES["SMALL"] = "small"; + TAG_NAMES["SPAN"] = "span"; + TAG_NAMES["STRIKE"] = "strike"; + TAG_NAMES["STRONG"] = "strong"; + TAG_NAMES["STYLE"] = "style"; + TAG_NAMES["SUB"] = "sub"; + TAG_NAMES["SUMMARY"] = "summary"; + TAG_NAMES["SUP"] = "sup"; + TAG_NAMES["TABLE"] = "table"; + TAG_NAMES["TBODY"] = "tbody"; + TAG_NAMES["TEMPLATE"] = "template"; + TAG_NAMES["TEXTAREA"] = "textarea"; + TAG_NAMES["TFOOT"] = "tfoot"; + TAG_NAMES["TD"] = "td"; + TAG_NAMES["TH"] = "th"; + TAG_NAMES["THEAD"] = "thead"; + TAG_NAMES["TITLE"] = "title"; + TAG_NAMES["TR"] = "tr"; + TAG_NAMES["TRACK"] = "track"; + TAG_NAMES["TT"] = "tt"; + TAG_NAMES["U"] = "u"; + TAG_NAMES["UL"] = "ul"; + TAG_NAMES["SVG"] = "svg"; + TAG_NAMES["VAR"] = "var"; + TAG_NAMES["WBR"] = "wbr"; + TAG_NAMES["XMP"] = "xmp"; +})(TAG_NAMES || (exports.TAG_NAMES = TAG_NAMES = {})); +/** + * Tag IDs are numeric IDs for known tag names. + * + * We use tag IDs to improve the performance of tag name comparisons. + */ +var TAG_ID; +(function (TAG_ID) { + TAG_ID[TAG_ID["UNKNOWN"] = 0] = "UNKNOWN"; + TAG_ID[TAG_ID["A"] = 1] = "A"; + TAG_ID[TAG_ID["ADDRESS"] = 2] = "ADDRESS"; + TAG_ID[TAG_ID["ANNOTATION_XML"] = 3] = "ANNOTATION_XML"; + TAG_ID[TAG_ID["APPLET"] = 4] = "APPLET"; + TAG_ID[TAG_ID["AREA"] = 5] = "AREA"; + TAG_ID[TAG_ID["ARTICLE"] = 6] = "ARTICLE"; + TAG_ID[TAG_ID["ASIDE"] = 7] = "ASIDE"; + TAG_ID[TAG_ID["B"] = 8] = "B"; + TAG_ID[TAG_ID["BASE"] = 9] = "BASE"; + TAG_ID[TAG_ID["BASEFONT"] = 10] = "BASEFONT"; + TAG_ID[TAG_ID["BGSOUND"] = 11] = "BGSOUND"; + TAG_ID[TAG_ID["BIG"] = 12] = "BIG"; + TAG_ID[TAG_ID["BLOCKQUOTE"] = 13] = "BLOCKQUOTE"; + TAG_ID[TAG_ID["BODY"] = 14] = "BODY"; + TAG_ID[TAG_ID["BR"] = 15] = "BR"; + TAG_ID[TAG_ID["BUTTON"] = 16] = "BUTTON"; + TAG_ID[TAG_ID["CAPTION"] = 17] = "CAPTION"; + TAG_ID[TAG_ID["CENTER"] = 18] = "CENTER"; + TAG_ID[TAG_ID["CODE"] = 19] = "CODE"; + TAG_ID[TAG_ID["COL"] = 20] = "COL"; + TAG_ID[TAG_ID["COLGROUP"] = 21] = "COLGROUP"; + TAG_ID[TAG_ID["DD"] = 22] = "DD"; + TAG_ID[TAG_ID["DESC"] = 23] = "DESC"; + TAG_ID[TAG_ID["DETAILS"] = 24] = "DETAILS"; + TAG_ID[TAG_ID["DIALOG"] = 25] = "DIALOG"; + TAG_ID[TAG_ID["DIR"] = 26] = "DIR"; + TAG_ID[TAG_ID["DIV"] = 27] = "DIV"; + TAG_ID[TAG_ID["DL"] = 28] = "DL"; + TAG_ID[TAG_ID["DT"] = 29] = "DT"; + TAG_ID[TAG_ID["EM"] = 30] = "EM"; + TAG_ID[TAG_ID["EMBED"] = 31] = "EMBED"; + TAG_ID[TAG_ID["FIELDSET"] = 32] = "FIELDSET"; + TAG_ID[TAG_ID["FIGCAPTION"] = 33] = "FIGCAPTION"; + TAG_ID[TAG_ID["FIGURE"] = 34] = "FIGURE"; + TAG_ID[TAG_ID["FONT"] = 35] = "FONT"; + TAG_ID[TAG_ID["FOOTER"] = 36] = "FOOTER"; + TAG_ID[TAG_ID["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT"; + TAG_ID[TAG_ID["FORM"] = 38] = "FORM"; + TAG_ID[TAG_ID["FRAME"] = 39] = "FRAME"; + TAG_ID[TAG_ID["FRAMESET"] = 40] = "FRAMESET"; + TAG_ID[TAG_ID["H1"] = 41] = "H1"; + TAG_ID[TAG_ID["H2"] = 42] = "H2"; + TAG_ID[TAG_ID["H3"] = 43] = "H3"; + TAG_ID[TAG_ID["H4"] = 44] = "H4"; + TAG_ID[TAG_ID["H5"] = 45] = "H5"; + TAG_ID[TAG_ID["H6"] = 46] = "H6"; + TAG_ID[TAG_ID["HEAD"] = 47] = "HEAD"; + TAG_ID[TAG_ID["HEADER"] = 48] = "HEADER"; + TAG_ID[TAG_ID["HGROUP"] = 49] = "HGROUP"; + TAG_ID[TAG_ID["HR"] = 50] = "HR"; + TAG_ID[TAG_ID["HTML"] = 51] = "HTML"; + TAG_ID[TAG_ID["I"] = 52] = "I"; + TAG_ID[TAG_ID["IMG"] = 53] = "IMG"; + TAG_ID[TAG_ID["IMAGE"] = 54] = "IMAGE"; + TAG_ID[TAG_ID["INPUT"] = 55] = "INPUT"; + TAG_ID[TAG_ID["IFRAME"] = 56] = "IFRAME"; + TAG_ID[TAG_ID["KEYGEN"] = 57] = "KEYGEN"; + TAG_ID[TAG_ID["LABEL"] = 58] = "LABEL"; + TAG_ID[TAG_ID["LI"] = 59] = "LI"; + TAG_ID[TAG_ID["LINK"] = 60] = "LINK"; + TAG_ID[TAG_ID["LISTING"] = 61] = "LISTING"; + TAG_ID[TAG_ID["MAIN"] = 62] = "MAIN"; + TAG_ID[TAG_ID["MALIGNMARK"] = 63] = "MALIGNMARK"; + TAG_ID[TAG_ID["MARQUEE"] = 64] = "MARQUEE"; + TAG_ID[TAG_ID["MATH"] = 65] = "MATH"; + TAG_ID[TAG_ID["MENU"] = 66] = "MENU"; + TAG_ID[TAG_ID["META"] = 67] = "META"; + TAG_ID[TAG_ID["MGLYPH"] = 68] = "MGLYPH"; + TAG_ID[TAG_ID["MI"] = 69] = "MI"; + TAG_ID[TAG_ID["MO"] = 70] = "MO"; + TAG_ID[TAG_ID["MN"] = 71] = "MN"; + TAG_ID[TAG_ID["MS"] = 72] = "MS"; + TAG_ID[TAG_ID["MTEXT"] = 73] = "MTEXT"; + TAG_ID[TAG_ID["NAV"] = 74] = "NAV"; + TAG_ID[TAG_ID["NOBR"] = 75] = "NOBR"; + TAG_ID[TAG_ID["NOFRAMES"] = 76] = "NOFRAMES"; + TAG_ID[TAG_ID["NOEMBED"] = 77] = "NOEMBED"; + TAG_ID[TAG_ID["NOSCRIPT"] = 78] = "NOSCRIPT"; + TAG_ID[TAG_ID["OBJECT"] = 79] = "OBJECT"; + TAG_ID[TAG_ID["OL"] = 80] = "OL"; + TAG_ID[TAG_ID["OPTGROUP"] = 81] = "OPTGROUP"; + TAG_ID[TAG_ID["OPTION"] = 82] = "OPTION"; + TAG_ID[TAG_ID["P"] = 83] = "P"; + TAG_ID[TAG_ID["PARAM"] = 84] = "PARAM"; + TAG_ID[TAG_ID["PLAINTEXT"] = 85] = "PLAINTEXT"; + TAG_ID[TAG_ID["PRE"] = 86] = "PRE"; + TAG_ID[TAG_ID["RB"] = 87] = "RB"; + TAG_ID[TAG_ID["RP"] = 88] = "RP"; + TAG_ID[TAG_ID["RT"] = 89] = "RT"; + TAG_ID[TAG_ID["RTC"] = 90] = "RTC"; + TAG_ID[TAG_ID["RUBY"] = 91] = "RUBY"; + TAG_ID[TAG_ID["S"] = 92] = "S"; + TAG_ID[TAG_ID["SCRIPT"] = 93] = "SCRIPT"; + TAG_ID[TAG_ID["SEARCH"] = 94] = "SEARCH"; + TAG_ID[TAG_ID["SECTION"] = 95] = "SECTION"; + TAG_ID[TAG_ID["SELECT"] = 96] = "SELECT"; + TAG_ID[TAG_ID["SOURCE"] = 97] = "SOURCE"; + TAG_ID[TAG_ID["SMALL"] = 98] = "SMALL"; + TAG_ID[TAG_ID["SPAN"] = 99] = "SPAN"; + TAG_ID[TAG_ID["STRIKE"] = 100] = "STRIKE"; + TAG_ID[TAG_ID["STRONG"] = 101] = "STRONG"; + TAG_ID[TAG_ID["STYLE"] = 102] = "STYLE"; + TAG_ID[TAG_ID["SUB"] = 103] = "SUB"; + TAG_ID[TAG_ID["SUMMARY"] = 104] = "SUMMARY"; + TAG_ID[TAG_ID["SUP"] = 105] = "SUP"; + TAG_ID[TAG_ID["TABLE"] = 106] = "TABLE"; + TAG_ID[TAG_ID["TBODY"] = 107] = "TBODY"; + TAG_ID[TAG_ID["TEMPLATE"] = 108] = "TEMPLATE"; + TAG_ID[TAG_ID["TEXTAREA"] = 109] = "TEXTAREA"; + TAG_ID[TAG_ID["TFOOT"] = 110] = "TFOOT"; + TAG_ID[TAG_ID["TD"] = 111] = "TD"; + TAG_ID[TAG_ID["TH"] = 112] = "TH"; + TAG_ID[TAG_ID["THEAD"] = 113] = "THEAD"; + TAG_ID[TAG_ID["TITLE"] = 114] = "TITLE"; + TAG_ID[TAG_ID["TR"] = 115] = "TR"; + TAG_ID[TAG_ID["TRACK"] = 116] = "TRACK"; + TAG_ID[TAG_ID["TT"] = 117] = "TT"; + TAG_ID[TAG_ID["U"] = 118] = "U"; + TAG_ID[TAG_ID["UL"] = 119] = "UL"; + TAG_ID[TAG_ID["SVG"] = 120] = "SVG"; + TAG_ID[TAG_ID["VAR"] = 121] = "VAR"; + TAG_ID[TAG_ID["WBR"] = 122] = "WBR"; + TAG_ID[TAG_ID["XMP"] = 123] = "XMP"; +})(TAG_ID || (exports.TAG_ID = TAG_ID = {})); +const TAG_NAME_TO_ID = new Map([ + [TAG_NAMES.A, TAG_ID.A], + [TAG_NAMES.ADDRESS, TAG_ID.ADDRESS], + [TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML], + [TAG_NAMES.APPLET, TAG_ID.APPLET], + [TAG_NAMES.AREA, TAG_ID.AREA], + [TAG_NAMES.ARTICLE, TAG_ID.ARTICLE], + [TAG_NAMES.ASIDE, TAG_ID.ASIDE], + [TAG_NAMES.B, TAG_ID.B], + [TAG_NAMES.BASE, TAG_ID.BASE], + [TAG_NAMES.BASEFONT, TAG_ID.BASEFONT], + [TAG_NAMES.BGSOUND, TAG_ID.BGSOUND], + [TAG_NAMES.BIG, TAG_ID.BIG], + [TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE], + [TAG_NAMES.BODY, TAG_ID.BODY], + [TAG_NAMES.BR, TAG_ID.BR], + [TAG_NAMES.BUTTON, TAG_ID.BUTTON], + [TAG_NAMES.CAPTION, TAG_ID.CAPTION], + [TAG_NAMES.CENTER, TAG_ID.CENTER], + [TAG_NAMES.CODE, TAG_ID.CODE], + [TAG_NAMES.COL, TAG_ID.COL], + [TAG_NAMES.COLGROUP, TAG_ID.COLGROUP], + [TAG_NAMES.DD, TAG_ID.DD], + [TAG_NAMES.DESC, TAG_ID.DESC], + [TAG_NAMES.DETAILS, TAG_ID.DETAILS], + [TAG_NAMES.DIALOG, TAG_ID.DIALOG], + [TAG_NAMES.DIR, TAG_ID.DIR], + [TAG_NAMES.DIV, TAG_ID.DIV], + [TAG_NAMES.DL, TAG_ID.DL], + [TAG_NAMES.DT, TAG_ID.DT], + [TAG_NAMES.EM, TAG_ID.EM], + [TAG_NAMES.EMBED, TAG_ID.EMBED], + [TAG_NAMES.FIELDSET, TAG_ID.FIELDSET], + [TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION], + [TAG_NAMES.FIGURE, TAG_ID.FIGURE], + [TAG_NAMES.FONT, TAG_ID.FONT], + [TAG_NAMES.FOOTER, TAG_ID.FOOTER], + [TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT], + [TAG_NAMES.FORM, TAG_ID.FORM], + [TAG_NAMES.FRAME, TAG_ID.FRAME], + [TAG_NAMES.FRAMESET, TAG_ID.FRAMESET], + [TAG_NAMES.H1, TAG_ID.H1], + [TAG_NAMES.H2, TAG_ID.H2], + [TAG_NAMES.H3, TAG_ID.H3], + [TAG_NAMES.H4, TAG_ID.H4], + [TAG_NAMES.H5, TAG_ID.H5], + [TAG_NAMES.H6, TAG_ID.H6], + [TAG_NAMES.HEAD, TAG_ID.HEAD], + [TAG_NAMES.HEADER, TAG_ID.HEADER], + [TAG_NAMES.HGROUP, TAG_ID.HGROUP], + [TAG_NAMES.HR, TAG_ID.HR], + [TAG_NAMES.HTML, TAG_ID.HTML], + [TAG_NAMES.I, TAG_ID.I], + [TAG_NAMES.IMG, TAG_ID.IMG], + [TAG_NAMES.IMAGE, TAG_ID.IMAGE], + [TAG_NAMES.INPUT, TAG_ID.INPUT], + [TAG_NAMES.IFRAME, TAG_ID.IFRAME], + [TAG_NAMES.KEYGEN, TAG_ID.KEYGEN], + [TAG_NAMES.LABEL, TAG_ID.LABEL], + [TAG_NAMES.LI, TAG_ID.LI], + [TAG_NAMES.LINK, TAG_ID.LINK], + [TAG_NAMES.LISTING, TAG_ID.LISTING], + [TAG_NAMES.MAIN, TAG_ID.MAIN], + [TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK], + [TAG_NAMES.MARQUEE, TAG_ID.MARQUEE], + [TAG_NAMES.MATH, TAG_ID.MATH], + [TAG_NAMES.MENU, TAG_ID.MENU], + [TAG_NAMES.META, TAG_ID.META], + [TAG_NAMES.MGLYPH, TAG_ID.MGLYPH], + [TAG_NAMES.MI, TAG_ID.MI], + [TAG_NAMES.MO, TAG_ID.MO], + [TAG_NAMES.MN, TAG_ID.MN], + [TAG_NAMES.MS, TAG_ID.MS], + [TAG_NAMES.MTEXT, TAG_ID.MTEXT], + [TAG_NAMES.NAV, TAG_ID.NAV], + [TAG_NAMES.NOBR, TAG_ID.NOBR], + [TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES], + [TAG_NAMES.NOEMBED, TAG_ID.NOEMBED], + [TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT], + [TAG_NAMES.OBJECT, TAG_ID.OBJECT], + [TAG_NAMES.OL, TAG_ID.OL], + [TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP], + [TAG_NAMES.OPTION, TAG_ID.OPTION], + [TAG_NAMES.P, TAG_ID.P], + [TAG_NAMES.PARAM, TAG_ID.PARAM], + [TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT], + [TAG_NAMES.PRE, TAG_ID.PRE], + [TAG_NAMES.RB, TAG_ID.RB], + [TAG_NAMES.RP, TAG_ID.RP], + [TAG_NAMES.RT, TAG_ID.RT], + [TAG_NAMES.RTC, TAG_ID.RTC], + [TAG_NAMES.RUBY, TAG_ID.RUBY], + [TAG_NAMES.S, TAG_ID.S], + [TAG_NAMES.SCRIPT, TAG_ID.SCRIPT], + [TAG_NAMES.SEARCH, TAG_ID.SEARCH], + [TAG_NAMES.SECTION, TAG_ID.SECTION], + [TAG_NAMES.SELECT, TAG_ID.SELECT], + [TAG_NAMES.SOURCE, TAG_ID.SOURCE], + [TAG_NAMES.SMALL, TAG_ID.SMALL], + [TAG_NAMES.SPAN, TAG_ID.SPAN], + [TAG_NAMES.STRIKE, TAG_ID.STRIKE], + [TAG_NAMES.STRONG, TAG_ID.STRONG], + [TAG_NAMES.STYLE, TAG_ID.STYLE], + [TAG_NAMES.SUB, TAG_ID.SUB], + [TAG_NAMES.SUMMARY, TAG_ID.SUMMARY], + [TAG_NAMES.SUP, TAG_ID.SUP], + [TAG_NAMES.TABLE, TAG_ID.TABLE], + [TAG_NAMES.TBODY, TAG_ID.TBODY], + [TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE], + [TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA], + [TAG_NAMES.TFOOT, TAG_ID.TFOOT], + [TAG_NAMES.TD, TAG_ID.TD], + [TAG_NAMES.TH, TAG_ID.TH], + [TAG_NAMES.THEAD, TAG_ID.THEAD], + [TAG_NAMES.TITLE, TAG_ID.TITLE], + [TAG_NAMES.TR, TAG_ID.TR], + [TAG_NAMES.TRACK, TAG_ID.TRACK], + [TAG_NAMES.TT, TAG_ID.TT], + [TAG_NAMES.U, TAG_ID.U], + [TAG_NAMES.UL, TAG_ID.UL], + [TAG_NAMES.SVG, TAG_ID.SVG], + [TAG_NAMES.VAR, TAG_ID.VAR], + [TAG_NAMES.WBR, TAG_ID.WBR], + [TAG_NAMES.XMP, TAG_ID.XMP], +]); +function getTagID(tagName) { + var _a; + return (_a = TAG_NAME_TO_ID.get(tagName)) !== null && _a !== void 0 ? _a : TAG_ID.UNKNOWN; +} +const $ = TAG_ID; +exports.SPECIAL_ELEMENTS = { + [NS.HTML]: new Set([ + $.ADDRESS, + $.APPLET, + $.AREA, + $.ARTICLE, + $.ASIDE, + $.BASE, + $.BASEFONT, + $.BGSOUND, + $.BLOCKQUOTE, + $.BODY, + $.BR, + $.BUTTON, + $.CAPTION, + $.CENTER, + $.COL, + $.COLGROUP, + $.DD, + $.DETAILS, + $.DIR, + $.DIV, + $.DL, + $.DT, + $.EMBED, + $.FIELDSET, + $.FIGCAPTION, + $.FIGURE, + $.FOOTER, + $.FORM, + $.FRAME, + $.FRAMESET, + $.H1, + $.H2, + $.H3, + $.H4, + $.H5, + $.H6, + $.HEAD, + $.HEADER, + $.HGROUP, + $.HR, + $.HTML, + $.IFRAME, + $.IMG, + $.INPUT, + $.LI, + $.LINK, + $.LISTING, + $.MAIN, + $.MARQUEE, + $.MENU, + $.META, + $.NAV, + $.NOEMBED, + $.NOFRAMES, + $.NOSCRIPT, + $.OBJECT, + $.OL, + $.P, + $.PARAM, + $.PLAINTEXT, + $.PRE, + $.SCRIPT, + $.SECTION, + $.SELECT, + $.SOURCE, + $.STYLE, + $.SUMMARY, + $.TABLE, + $.TBODY, + $.TD, + $.TEMPLATE, + $.TEXTAREA, + $.TFOOT, + $.TH, + $.THEAD, + $.TITLE, + $.TR, + $.TRACK, + $.UL, + $.WBR, + $.XMP, + ]), + [NS.MATHML]: new Set([$.MI, $.MO, $.MN, $.MS, $.MTEXT, $.ANNOTATION_XML]), + [NS.SVG]: new Set([$.TITLE, $.FOREIGN_OBJECT, $.DESC]), + [NS.XLINK]: new Set(), + [NS.XML]: new Set(), + [NS.XMLNS]: new Set(), +}; +exports.NUMBERED_HEADERS = new Set([$.H1, $.H2, $.H3, $.H4, $.H5, $.H6]); +const UNESCAPED_TEXT = new Set([ + TAG_NAMES.STYLE, + TAG_NAMES.SCRIPT, + TAG_NAMES.XMP, + TAG_NAMES.IFRAME, + TAG_NAMES.NOEMBED, + TAG_NAMES.NOFRAMES, + TAG_NAMES.PLAINTEXT, +]); +function hasUnescapedText(tn, scriptingEnabled) { + return UNESCAPED_TEXT.has(tn) || (scriptingEnabled && tn === TAG_NAMES.NOSCRIPT); +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/token.d.ts b/tools/ui/node_modules/parse5/dist/cjs/common/token.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9bcc7dc545832a1c5cb46505501e89447874abcd --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/token.d.ts @@ -0,0 +1,84 @@ +import type { TAG_ID } from './html.js'; +export declare enum TokenType { + CHARACTER = 0, + NULL_CHARACTER = 1, + WHITESPACE_CHARACTER = 2, + START_TAG = 3, + END_TAG = 4, + COMMENT = 5, + DOCTYPE = 6, + EOF = 7, + HIBERNATION = 8 +} +export interface Location { + /** One-based line index of the first character. */ + startLine: number; + /** One-based column index of the first character. */ + startCol: number; + /** Zero-based first character index. */ + startOffset: number; + /** One-based line index of the last character. */ + endLine: number; + /** One-based column index of the last character. Points directly *after* the last character. */ + endCol: number; + /** Zero-based last character index. Points directly *after* the last character. */ + endOffset: number; +} +export interface LocationWithAttributes extends Location { + /** Start tag attributes' location info. */ + attrs?: Record; +} +export interface ElementLocation extends LocationWithAttributes { + /** Element's start tag location info. */ + startTag?: Location; + /** + * Element's end tag location info. + * This property is undefined, if the element has no closing tag. + */ + endTag?: Location; +} +interface TokenBase { + readonly type: TokenType; + location: Location | null; +} +export interface DoctypeToken extends TokenBase { + readonly type: TokenType.DOCTYPE; + name: string | null; + forceQuirks: boolean; + publicId: string | null; + systemId: string | null; +} +export interface Attribute { + /** The name of the attribute. */ + name: string; + /** The namespace of the attribute. */ + namespace?: string; + /** The namespace-related prefix of the attribute. */ + prefix?: string; + /** The value of the attribute. */ + value: string; +} +export interface TagToken extends TokenBase { + readonly type: TokenType.START_TAG | TokenType.END_TAG; + tagName: string; + /** Used to cache the ID of the tag name. */ + tagID: TAG_ID; + selfClosing: boolean; + ackSelfClosing: boolean; + attrs: Attribute[]; + location: LocationWithAttributes | null; +} +export declare function getTokenAttr(token: TagToken, attrName: string): string | null; +export interface CommentToken extends TokenBase { + readonly type: TokenType.COMMENT; + data: string; +} +export interface EOFToken extends TokenBase { + readonly type: TokenType.EOF; +} +export interface CharacterToken extends TokenBase { + type: TokenType.CHARACTER | TokenType.NULL_CHARACTER | TokenType.WHITESPACE_CHARACTER; + chars: string; +} +export type Token = DoctypeToken | TagToken | CommentToken | EOFToken | CharacterToken; +export {}; diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/token.js b/tools/ui/node_modules/parse5/dist/cjs/common/token.js new file mode 100644 index 0000000000000000000000000000000000000000..a46f0f29b4d2e7248b920b961316aa94a0ecb495 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/token.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TokenType = void 0; +exports.getTokenAttr = getTokenAttr; +var TokenType; +(function (TokenType) { + TokenType[TokenType["CHARACTER"] = 0] = "CHARACTER"; + TokenType[TokenType["NULL_CHARACTER"] = 1] = "NULL_CHARACTER"; + TokenType[TokenType["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER"; + TokenType[TokenType["START_TAG"] = 3] = "START_TAG"; + TokenType[TokenType["END_TAG"] = 4] = "END_TAG"; + TokenType[TokenType["COMMENT"] = 5] = "COMMENT"; + TokenType[TokenType["DOCTYPE"] = 6] = "DOCTYPE"; + TokenType[TokenType["EOF"] = 7] = "EOF"; + TokenType[TokenType["HIBERNATION"] = 8] = "HIBERNATION"; +})(TokenType || (exports.TokenType = TokenType = {})); +function getTokenAttr(token, attrName) { + for (let i = token.attrs.length - 1; i >= 0; i--) { + if (token.attrs[i].name === attrName) { + return token.attrs[i].value; + } + } + return null; +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/unicode.d.ts b/tools/ui/node_modules/parse5/dist/cjs/common/unicode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..63eda8b48742241c8b6f5de536821350e8cb2d7a --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/unicode.d.ts @@ -0,0 +1,42 @@ +export declare const REPLACEMENT_CHARACTER = "\uFFFD"; +export declare enum CODE_POINTS { + EOF = -1, + NULL = 0, + TABULATION = 9, + CARRIAGE_RETURN = 13, + LINE_FEED = 10, + FORM_FEED = 12, + SPACE = 32, + EXCLAMATION_MARK = 33, + QUOTATION_MARK = 34, + AMPERSAND = 38, + APOSTROPHE = 39, + HYPHEN_MINUS = 45, + SOLIDUS = 47, + DIGIT_0 = 48, + DIGIT_9 = 57, + SEMICOLON = 59, + LESS_THAN_SIGN = 60, + EQUALS_SIGN = 61, + GREATER_THAN_SIGN = 62, + QUESTION_MARK = 63, + LATIN_CAPITAL_A = 65, + LATIN_CAPITAL_Z = 90, + RIGHT_SQUARE_BRACKET = 93, + GRAVE_ACCENT = 96, + LATIN_SMALL_A = 97, + LATIN_SMALL_Z = 122 +} +export declare const SEQUENCES: { + DASH_DASH: string; + CDATA_START: string; + DOCTYPE: string; + SCRIPT: string; + PUBLIC: string; + SYSTEM: string; +}; +export declare function isSurrogate(cp: number): boolean; +export declare function isSurrogatePair(cp: number): boolean; +export declare function getSurrogatePairCodePoint(cp1: number, cp2: number): number; +export declare function isControlCodePoint(cp: number): boolean; +export declare function isUndefinedCodePoint(cp: number): boolean; diff --git a/tools/ui/node_modules/parse5/dist/cjs/common/unicode.js b/tools/ui/node_modules/parse5/dist/cjs/common/unicode.js new file mode 100644 index 0000000000000000000000000000000000000000..a2b317f3d076ae55ec9984fbacd043c7c9ea443a --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/common/unicode.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SEQUENCES = exports.CODE_POINTS = exports.REPLACEMENT_CHARACTER = void 0; +exports.isSurrogate = isSurrogate; +exports.isSurrogatePair = isSurrogatePair; +exports.getSurrogatePairCodePoint = getSurrogatePairCodePoint; +exports.isControlCodePoint = isControlCodePoint; +exports.isUndefinedCodePoint = isUndefinedCodePoint; +const UNDEFINED_CODE_POINTS = new Set([ + 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, + 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, + 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, + 1048575, 1114110, 1114111, +]); +exports.REPLACEMENT_CHARACTER = '\uFFFD'; +var CODE_POINTS; +(function (CODE_POINTS) { + CODE_POINTS[CODE_POINTS["EOF"] = -1] = "EOF"; + CODE_POINTS[CODE_POINTS["NULL"] = 0] = "NULL"; + CODE_POINTS[CODE_POINTS["TABULATION"] = 9] = "TABULATION"; + CODE_POINTS[CODE_POINTS["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN"; + CODE_POINTS[CODE_POINTS["LINE_FEED"] = 10] = "LINE_FEED"; + CODE_POINTS[CODE_POINTS["FORM_FEED"] = 12] = "FORM_FEED"; + CODE_POINTS[CODE_POINTS["SPACE"] = 32] = "SPACE"; + CODE_POINTS[CODE_POINTS["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK"; + CODE_POINTS[CODE_POINTS["QUOTATION_MARK"] = 34] = "QUOTATION_MARK"; + CODE_POINTS[CODE_POINTS["AMPERSAND"] = 38] = "AMPERSAND"; + CODE_POINTS[CODE_POINTS["APOSTROPHE"] = 39] = "APOSTROPHE"; + CODE_POINTS[CODE_POINTS["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS"; + CODE_POINTS[CODE_POINTS["SOLIDUS"] = 47] = "SOLIDUS"; + CODE_POINTS[CODE_POINTS["DIGIT_0"] = 48] = "DIGIT_0"; + CODE_POINTS[CODE_POINTS["DIGIT_9"] = 57] = "DIGIT_9"; + CODE_POINTS[CODE_POINTS["SEMICOLON"] = 59] = "SEMICOLON"; + CODE_POINTS[CODE_POINTS["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN"; + CODE_POINTS[CODE_POINTS["EQUALS_SIGN"] = 61] = "EQUALS_SIGN"; + CODE_POINTS[CODE_POINTS["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN"; + CODE_POINTS[CODE_POINTS["QUESTION_MARK"] = 63] = "QUESTION_MARK"; + CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A"; + CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z"; + CODE_POINTS[CODE_POINTS["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET"; + CODE_POINTS[CODE_POINTS["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT"; + CODE_POINTS[CODE_POINTS["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A"; + CODE_POINTS[CODE_POINTS["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z"; +})(CODE_POINTS || (exports.CODE_POINTS = CODE_POINTS = {})); +exports.SEQUENCES = { + DASH_DASH: '--', + CDATA_START: '[CDATA[', + DOCTYPE: 'doctype', + SCRIPT: 'script', + PUBLIC: 'public', + SYSTEM: 'system', +}; +//Surrogates +function isSurrogate(cp) { + return cp >= 55296 && cp <= 57343; +} +function isSurrogatePair(cp) { + return cp >= 56320 && cp <= 57343; +} +function getSurrogatePairCodePoint(cp1, cp2) { + return (cp1 - 55296) * 1024 + 9216 + cp2; +} +//NOTE: excluding NULL and ASCII whitespace +function isControlCodePoint(cp) { + return ((cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) || + (cp >= 0x7f && cp <= 0x9f)); +} +function isUndefinedCodePoint(cp) { + return (cp >= 64976 && cp <= 65007) || UNDEFINED_CODE_POINTS.has(cp); +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/index.d.ts b/tools/ui/node_modules/parse5/dist/cjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25540bdb22df60a7cea117f0c1aa8828a1d63385 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/index.d.ts @@ -0,0 +1,71 @@ +import { type ParserOptions } from './parser/index.js'; +import type { DefaultTreeAdapterMap } from './tree-adapters/default.js'; +import type { TreeAdapterTypeMap } from './tree-adapters/interface.js'; +export { type DefaultTreeAdapterMap, defaultTreeAdapter } from './tree-adapters/default.js'; +import type * as DefaultTreeAdapter from './tree-adapters/default.js'; +export declare namespace DefaultTreeAdapterTypes { + type Document = DefaultTreeAdapter.Document; + type DocumentFragment = DefaultTreeAdapter.DocumentFragment; + type Element = DefaultTreeAdapter.Element; + type CommentNode = DefaultTreeAdapter.CommentNode; + type TextNode = DefaultTreeAdapter.TextNode; + type Template = DefaultTreeAdapter.Template; + type DocumentType = DefaultTreeAdapter.DocumentType; + type ParentNode = DefaultTreeAdapter.ParentNode; + type ChildNode = DefaultTreeAdapter.ChildNode; + type Node = DefaultTreeAdapter.Node; + type DefaultTreeAdapterMap = DefaultTreeAdapter.DefaultTreeAdapterMap; +} +export type { TreeAdapter, TreeAdapterTypeMap } from './tree-adapters/interface.js'; +export { type ParserOptions, /** @internal */ Parser } from './parser/index.js'; +export { serialize, serializeOuter, type SerializerOptions } from './serializer/index.js'; +export { ERR as ErrorCodes, type ParserError, type ParserErrorHandler } from './common/error-codes.js'; +/** @internal */ +export * as foreignContent from './common/foreign-content.js'; +export * as html from './common/html.js'; +export * as Token from './common/token.js'; +/** @internal */ +export { Tokenizer, type TokenizerOptions, TokenizerMode, type TokenHandler } from './tokenizer/index.js'; +/** + * Parses an HTML string. + * + * @param html Input HTML string. + * @param options Parsing options. + * @returns Document + * + * @example + * + * ```js + * const parse5 = require('parse5'); + * + * const document = parse5.parse('Hi there!'); + * + * console.log(document.childNodes[1].tagName); //> 'html' + *``` + */ +export declare function parse(html: string, options?: ParserOptions): T['document']; +/** + * Parses an HTML fragment. + * + * @example + * + * ```js + * const parse5 = require('parse5'); + * + * const documentFragment = parse5.parseFragment('
'); + * + * console.log(documentFragment.childNodes[0].tagName); //> 'table' + * + * // Parses the html fragment in the context of the parsed element. + * const trFragment = parse5.parseFragment(documentFragment.childNodes[0], ''); + * + * console.log(trFragment.childNodes[0].childNodes[0].tagName); //> 'td' + * ``` + * + * @param fragmentContext Parsing context element. If specified, given fragment will be parsed as if it was set to the context element's `innerHTML` property. + * @param html Input HTML fragment string. + * @param options Parsing options. + * @returns DocumentFragment + */ +export declare function parseFragment(fragmentContext: T['parentNode'] | null, html: string, options: ParserOptions): T['documentFragment']; +export declare function parseFragment(html: string, options?: ParserOptions): T['documentFragment']; diff --git a/tools/ui/node_modules/parse5/dist/cjs/index.js b/tools/ui/node_modules/parse5/dist/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..00323895a6bc8857f7e72e65a8c614e4f4376210 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/index.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TokenizerMode = exports.Tokenizer = exports.Token = exports.html = exports.foreignContent = exports.ErrorCodes = exports.serializeOuter = exports.serialize = exports.Parser = exports.defaultTreeAdapter = void 0; +exports.parse = parse; +exports.parseFragment = parseFragment; +const index_js_1 = require("./parser/index.js"); +var default_js_1 = require("./tree-adapters/default.js"); +Object.defineProperty(exports, "defaultTreeAdapter", { enumerable: true, get: function () { return default_js_1.defaultTreeAdapter; } }); +var index_js_2 = require("./parser/index.js"); +Object.defineProperty(exports, "Parser", { enumerable: true, get: function () { return index_js_2.Parser; } }); +var index_js_3 = require("./serializer/index.js"); +Object.defineProperty(exports, "serialize", { enumerable: true, get: function () { return index_js_3.serialize; } }); +Object.defineProperty(exports, "serializeOuter", { enumerable: true, get: function () { return index_js_3.serializeOuter; } }); +var error_codes_js_1 = require("./common/error-codes.js"); +Object.defineProperty(exports, "ErrorCodes", { enumerable: true, get: function () { return error_codes_js_1.ERR; } }); +/** @internal */ +exports.foreignContent = require("./common/foreign-content.js"); +exports.html = require("./common/html.js"); +exports.Token = require("./common/token.js"); +/** @internal */ +var index_js_4 = require("./tokenizer/index.js"); +Object.defineProperty(exports, "Tokenizer", { enumerable: true, get: function () { return index_js_4.Tokenizer; } }); +Object.defineProperty(exports, "TokenizerMode", { enumerable: true, get: function () { return index_js_4.TokenizerMode; } }); +// Shorthands +/** + * Parses an HTML string. + * + * @param html Input HTML string. + * @param options Parsing options. + * @returns Document + * + * @example + * + * ```js + * const parse5 = require('parse5'); + * + * const document = parse5.parse('Hi there!'); + * + * console.log(document.childNodes[1].tagName); //> 'html' + *``` + */ +function parse(html, options) { + return index_js_1.Parser.parse(html, options); +} +function parseFragment(fragmentContext, html, options) { + if (typeof fragmentContext === 'string') { + options = html; + html = fragmentContext; + fragmentContext = null; + } + const parser = index_js_1.Parser.getFragmentParser(fragmentContext, options); + parser.tokenizer.write(html, true); + return parser.getFragment(); +} diff --git a/tools/ui/node_modules/parse5/dist/cjs/package.json b/tools/ui/node_modules/parse5/dist/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..729ac4d93b7f2d9be36b44525f02ff6555f9383a --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/package.json @@ -0,0 +1 @@ +{"type":"commonjs"} diff --git a/tools/ui/node_modules/parse5/dist/cjs/parser/formatting-element-list.d.ts b/tools/ui/node_modules/parse5/dist/cjs/parser/formatting-element-list.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d421b6a8d92d158b8db518b0ebdd90b7b728e65 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/parser/formatting-element-list.d.ts @@ -0,0 +1,36 @@ +import type { TagToken } from '../common/token.js'; +import type { TreeAdapter, TreeAdapterTypeMap } from '../tree-adapters/interface.js'; +export declare enum EntryType { + Marker = 0, + Element = 1 +} +interface MarkerEntry { + type: EntryType.Marker; +} +export interface ElementEntry { + type: EntryType.Element; + element: T['element']; + token: TagToken; +} +export type Entry = MarkerEntry | ElementEntry; +export declare class FormattingElementList { + private treeAdapter; + entries: Entry[]; + bookmark: Entry | null; + constructor(treeAdapter: TreeAdapter); + private _getNoahArkConditionCandidates; + private _ensureNoahArkCondition; + insertMarker(): void; + pushElement(element: T['element'], token: TagToken): void; + insertElementAfterBookmark(element: T['element'], token: TagToken): void; + removeEntry(entry: Entry): void; + /** + * Clears the list of formatting elements up to the last marker. + * + * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker + */ + clearToLastMarker(): void; + getElementEntryInScopeWithTagName(tagName: string): ElementEntry | null; + getElementEntry(element: T['element']): ElementEntry | undefined; +} +export {}; diff --git a/tools/ui/node_modules/parse5/dist/cjs/parser/formatting-element-list.js b/tools/ui/node_modules/parse5/dist/cjs/parser/formatting-element-list.js new file mode 100644 index 0000000000000000000000000000000000000000..e97ebfdcfe65803442e40079db5cc789ef8529a5 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/parser/formatting-element-list.js @@ -0,0 +1,114 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FormattingElementList = exports.EntryType = void 0; +//Const +const NOAH_ARK_CAPACITY = 3; +var EntryType; +(function (EntryType) { + EntryType[EntryType["Marker"] = 0] = "Marker"; + EntryType[EntryType["Element"] = 1] = "Element"; +})(EntryType || (exports.EntryType = EntryType = {})); +const MARKER = { type: EntryType.Marker }; +//List of formatting elements +class FormattingElementList { + constructor(treeAdapter) { + this.treeAdapter = treeAdapter; + this.entries = []; + this.bookmark = null; + } + //Noah Ark's condition + //OPTIMIZATION: at first we try to find possible candidates for exclusion using + //lightweight heuristics without thorough attributes check. + _getNoahArkConditionCandidates(newElement, neAttrs) { + const candidates = []; + const neAttrsLength = neAttrs.length; + const neTagName = this.treeAdapter.getTagName(newElement); + const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement); + for (let i = 0; i < this.entries.length; i++) { + const entry = this.entries[i]; + if (entry.type === EntryType.Marker) { + break; + } + const { element } = entry; + if (this.treeAdapter.getTagName(element) === neTagName && + this.treeAdapter.getNamespaceURI(element) === neNamespaceURI) { + const elementAttrs = this.treeAdapter.getAttrList(element); + if (elementAttrs.length === neAttrsLength) { + candidates.push({ idx: i, attrs: elementAttrs }); + } + } + } + return candidates; + } + _ensureNoahArkCondition(newElement) { + if (this.entries.length < NOAH_ARK_CAPACITY) + return; + const neAttrs = this.treeAdapter.getAttrList(newElement); + const candidates = this._getNoahArkConditionCandidates(newElement, neAttrs); + if (candidates.length < NOAH_ARK_CAPACITY) + return; + //NOTE: build attrs map for the new element, so we can perform fast lookups + const neAttrsMap = new Map(neAttrs.map((neAttr) => [neAttr.name, neAttr.value])); + let validCandidates = 0; + //NOTE: remove bottommost candidates, until Noah's Ark condition will not be met + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i]; + // We know that `candidate.attrs.length === neAttrs.length` + if (candidate.attrs.every((cAttr) => neAttrsMap.get(cAttr.name) === cAttr.value)) { + validCandidates += 1; + if (validCandidates >= NOAH_ARK_CAPACITY) { + this.entries.splice(candidate.idx, 1); + } + } + } + } + //Mutations + insertMarker() { + this.entries.unshift(MARKER); + } + pushElement(element, token) { + this._ensureNoahArkCondition(element); + this.entries.unshift({ + type: EntryType.Element, + element, + token, + }); + } + insertElementAfterBookmark(element, token) { + const bookmarkIdx = this.entries.indexOf(this.bookmark); + this.entries.splice(bookmarkIdx, 0, { + type: EntryType.Element, + element, + token, + }); + } + removeEntry(entry) { + const entryIndex = this.entries.indexOf(entry); + if (entryIndex !== -1) { + this.entries.splice(entryIndex, 1); + } + } + /** + * Clears the list of formatting elements up to the last marker. + * + * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker + */ + clearToLastMarker() { + const markerIdx = this.entries.indexOf(MARKER); + if (markerIdx === -1) { + this.entries.length = 0; + } + else { + this.entries.splice(0, markerIdx + 1); + } + } + //Search + getElementEntryInScopeWithTagName(tagName) { + const entry = this.entries.find((entry) => entry.type === EntryType.Marker || this.treeAdapter.getTagName(entry.element) === tagName); + return entry && entry.type === EntryType.Element ? entry : null; + } + getElementEntry(element) { + return this.entries.find((entry) => entry.type === EntryType.Element && entry.element === element); + } +} +exports.FormattingElementList = FormattingElementList; diff --git a/tools/ui/node_modules/parse5/dist/cjs/parser/index.d.ts b/tools/ui/node_modules/parse5/dist/cjs/parser/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..04c6a5949392aac717c9966feab1cdcd8976eb53 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/parser/index.d.ts @@ -0,0 +1,221 @@ +import { Tokenizer, TokenizerMode, type TokenHandler } from '../tokenizer/index.js'; +import { OpenElementStack, type StackHandler } from './open-element-stack.js'; +import { FormattingElementList } from './formatting-element-list.js'; +import { ERR, type ParserErrorHandler } from '../common/error-codes.js'; +import { TAG_ID as $, NS } from '../common/html.js'; +import type { TreeAdapter, TreeAdapterTypeMap } from '../tree-adapters/interface.js'; +import { type Token, type CommentToken, type CharacterToken, type TagToken, type DoctypeToken, type EOFToken, type LocationWithAttributes } from '../common/token.js'; +declare enum InsertionMode { + INITIAL = 0, + BEFORE_HTML = 1, + BEFORE_HEAD = 2, + IN_HEAD = 3, + IN_HEAD_NO_SCRIPT = 4, + AFTER_HEAD = 5, + IN_BODY = 6, + TEXT = 7, + IN_TABLE = 8, + IN_TABLE_TEXT = 9, + IN_CAPTION = 10, + IN_COLUMN_GROUP = 11, + IN_TABLE_BODY = 12, + IN_ROW = 13, + IN_CELL = 14, + IN_SELECT = 15, + IN_SELECT_IN_TABLE = 16, + IN_TEMPLATE = 17, + AFTER_BODY = 18, + IN_FRAMESET = 19, + AFTER_FRAMESET = 20, + AFTER_AFTER_BODY = 21, + AFTER_AFTER_FRAMESET = 22 +} +export interface ParserOptions { + /** + * The [scripting flag](https://html.spec.whatwg.org/multipage/parsing.html#scripting-flag). If set + * to `true`, `noscript` element content will be parsed as text. + * + * @default `true` + */ + scriptingEnabled?: boolean; + /** + * Enables source code location information. When enabled, each node (except the root node) + * will have a `sourceCodeLocation` property. If the node is not an empty element, `sourceCodeLocation` will + * be a {@link ElementLocation} object, otherwise it will be {@link Location}. + * If the element was implicitly created by the parser (as part of + * [tree correction](https://html.spec.whatwg.org/multipage/syntax.html#an-introduction-to-error-handling-and-strange-cases-in-the-parser)), + * its `sourceCodeLocation` property will be `undefined`. + * + * @default `false` + */ + sourceCodeLocationInfo?: boolean; + /** + * Specifies the resulting tree format. + * + * @default `treeAdapters.default` + */ + treeAdapter?: TreeAdapter; + /** + * Callback for parse errors. + * + * @default `null` + */ + onParseError?: ParserErrorHandler | null; +} +export declare class Parser implements TokenHandler, StackHandler { + /** @internal */ + fragmentContext: T['element'] | null; + /** @internal */ + scriptHandler: null | ((pendingScript: T['element']) => void); + treeAdapter: TreeAdapter; + /** @internal */ + onParseError: ParserErrorHandler | null; + protected currentToken: Token | null; + options: Required>; + document: T['document']; + constructor(options?: ParserOptions, document?: T['document'], + /** @internal */ + fragmentContext?: T['element'] | null, + /** @internal */ + scriptHandler?: null | ((pendingScript: T['element']) => void)); + static parse(html: string, options?: ParserOptions): T['document']; + static getFragmentParser(fragmentContext?: T['parentNode'] | null, options?: ParserOptions): Parser; + getFragment(): T['documentFragment']; + tokenizer: Tokenizer; + stopped: boolean; + /** @internal */ + insertionMode: InsertionMode; + /** @internal */ + originalInsertionMode: InsertionMode; + /** @internal */ + fragmentContextID: $; + /** @internal */ + headElement: null | T['element']; + /** @internal */ + formElement: null | T['element']; + /** @internal */ + openElements: OpenElementStack; + /** @internal */ + activeFormattingElements: FormattingElementList; + /** Indicates that the current node is not an element in the HTML namespace */ + protected currentNotInHTML: boolean; + /** + * The template insertion mode stack is maintained from the left. + * Ie. the topmost element will always have index 0. + * + * @internal + */ + tmplInsertionModeStack: InsertionMode[]; + /** @internal */ + pendingCharacterTokens: CharacterToken[]; + /** @internal */ + hasNonWhitespacePendingCharacterToken: boolean; + /** @internal */ + framesetOk: boolean; + /** @internal */ + skipNextNewLine: boolean; + /** @internal */ + fosterParentingEnabled: boolean; + /** @internal */ + _err(token: Token, code: ERR, beforeToken?: boolean): void; + /** @internal */ + onItemPush(node: T['parentNode'], tid: number, isTop: boolean): void; + /** @internal */ + onItemPop(node: T['parentNode'], isTop: boolean): void; + protected _setContextModes(current: T['parentNode'] | undefined, tid: number | undefined): void; + /** @protected */ + _switchToTextParsing(currentToken: TagToken, nextTokenizerState: (typeof TokenizerMode)[keyof typeof TokenizerMode]): void; + switchToPlaintextParsing(): void; + /** @protected */ + _getAdjustedCurrentElement(): T['element']; + /** @protected */ + _findFormInFragmentContext(): void; + protected _initTokenizerForFragmentParsing(): void; + /** @protected */ + _setDocumentType(token: DoctypeToken): void; + /** @protected */ + _attachElementToTree(element: T['element'], location: LocationWithAttributes | null): void; + /** + * For self-closing tags. Add an element to the tree, but skip adding it + * to the stack. + */ + /** @protected */ + _appendElement(token: TagToken, namespaceURI: NS): void; + /** @protected */ + _insertElement(token: TagToken, namespaceURI: NS): void; + /** @protected */ + _insertFakeElement(tagName: string, tagID: $): void; + /** @protected */ + _insertTemplate(token: TagToken): void; + /** @protected */ + _insertFakeRootElement(): void; + /** @protected */ + _appendCommentNode(token: CommentToken, parent: T['parentNode']): void; + /** @protected */ + _insertCharacters(token: CharacterToken): void; + /** @protected */ + _adoptNodes(donor: T['parentNode'], recipient: T['parentNode']): void; + /** @protected */ + _setEndLocation(element: T['element'], closingToken: Token): void; + protected shouldProcessStartTagTokenInForeignContent(token: TagToken): boolean; + /** @protected */ + _processToken(token: Token): void; + /** @protected */ + _isIntegrationPoint(tid: $, element: T['element'], foreignNS?: NS): boolean; + /** @protected */ + _reconstructActiveFormattingElements(): void; + /** @protected */ + _closeTableCell(): void; + /** @protected */ + _closePElement(): void; + /** @protected */ + _resetInsertionMode(): void; + /** @protected */ + _resetInsertionModeForSelect(selectIdx: number): void; + /** @protected */ + _isElementCausesFosterParenting(tn: $): boolean; + /** @protected */ + _shouldFosterParentOnInsertion(): boolean; + /** @protected */ + _findFosterParentingLocation(): { + parent: T['parentNode']; + beforeElement: T['element'] | null; + }; + /** @protected */ + _fosterParentElement(element: T['element']): void; + /** @protected */ + _isSpecialElement(element: T['element'], id: $): boolean; + /** @internal */ + onCharacter(token: CharacterToken): void; + /** @internal */ + onNullCharacter(token: CharacterToken): void; + /** @internal */ + onComment(token: CommentToken): void; + /** @internal */ + onDoctype(token: DoctypeToken): void; + /** @internal */ + onStartTag(token: TagToken): void; + /** + * Processes a given start tag. + * + * `onStartTag` checks if a self-closing tag was recognized. When a token + * is moved inbetween multiple insertion modes, this check for self-closing + * could lead to false positives. To avoid this, `_processStartTag` is used + * for nested calls. + * + * @param token The token to process. + * @protected + */ + _processStartTag(token: TagToken): void; + /** @protected */ + _startTagOutsideForeignContent(token: TagToken): void; + /** @internal */ + onEndTag(token: TagToken): void; + /** @protected */ + _endTagOutsideForeignContent(token: TagToken): void; + /** @internal */ + onEof(token: EOFToken): void; + /** @internal */ + onWhitespaceCharacter(token: CharacterToken): void; +} +export {}; diff --git a/tools/ui/node_modules/parse5/dist/cjs/parser/index.js b/tools/ui/node_modules/parse5/dist/cjs/parser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5297fa2bc7d9cefccbc93085e453ef2bc4560ab4 --- /dev/null +++ b/tools/ui/node_modules/parse5/dist/cjs/parser/index.js @@ -0,0 +1,3240 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Parser = void 0; +const index_js_1 = require("../tokenizer/index.js"); +const open_element_stack_js_1 = require("./open-element-stack.js"); +const formatting_element_list_js_1 = require("./formatting-element-list.js"); +const default_js_1 = require("../tree-adapters/default.js"); +const doctype = require("../common/doctype.js"); +const foreignContent = require("../common/foreign-content.js"); +const error_codes_js_1 = require("../common/error-codes.js"); +const unicode = require("../common/unicode.js"); +const html_js_1 = require("../common/html.js"); +const token_js_1 = require("../common/token.js"); +//Misc constants +const HIDDEN_INPUT_TYPE = 'hidden'; +//Adoption agency loops iteration count +const AA_OUTER_LOOP_ITER = 8; +const AA_INNER_LOOP_ITER = 3; +//Insertion modes +var InsertionMode; +(function (InsertionMode) { + InsertionMode[InsertionMode["INITIAL"] = 0] = "INITIAL"; + InsertionMode[InsertionMode["BEFORE_HTML"] = 1] = "BEFORE_HTML"; + InsertionMode[InsertionMode["BEFORE_HEAD"] = 2] = "BEFORE_HEAD"; + InsertionMode[InsertionMode["IN_HEAD"] = 3] = "IN_HEAD"; + InsertionMode[InsertionMode["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT"; + InsertionMode[InsertionMode["AFTER_HEAD"] = 5] = "AFTER_HEAD"; + InsertionMode[InsertionMode["IN_BODY"] = 6] = "IN_BODY"; + InsertionMode[InsertionMode["TEXT"] = 7] = "TEXT"; + InsertionMode[InsertionMode["IN_TABLE"] = 8] = "IN_TABLE"; + InsertionMode[InsertionMode["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT"; + InsertionMode[InsertionMode["IN_CAPTION"] = 10] = "IN_CAPTION"; + InsertionMode[InsertionMode["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP"; + InsertionMode[InsertionMode["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY"; + InsertionMode[InsertionMode["IN_ROW"] = 13] = "IN_ROW"; + InsertionMode[InsertionMode["IN_CELL"] = 14] = "IN_CELL"; + InsertionMode[InsertionMode["IN_SELECT"] = 15] = "IN_SELECT"; + InsertionMode[InsertionMode["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE"; + InsertionMode[InsertionMode["IN_TEMPLATE"] = 17] = "IN_TEMPLATE"; + InsertionMode[InsertionMode["AFTER_BODY"] = 18] = "AFTER_BODY"; + InsertionMode[InsertionMode["IN_FRAMESET"] = 19] = "IN_FRAMESET"; + InsertionMode[InsertionMode["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET"; + InsertionMode[InsertionMode["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY"; + InsertionMode[InsertionMode["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET"; +})(InsertionMode || (InsertionMode = {})); +const BASE_LOC = { + startLine: -1, + startCol: -1, + startOffset: -1, + endLine: -1, + endCol: -1, + endOffset: -1, +}; +const TABLE_STRUCTURE_TAGS = new Set([html_js_1.TAG_ID.TABLE, html_js_1.TAG_ID.TBODY, html_js_1.TAG_ID.TFOOT, html_js_1.TAG_ID.THEAD, html_js_1.TAG_ID.TR]); +const defaultParserOptions = { + scriptingEnabled: true, + sourceCodeLocationInfo: false, + treeAdapter: default_js_1.defaultTreeAdapter, + onParseError: null, +}; +//Parser +class Parser { + constructor(options, document, + /** @internal */ + fragmentContext = null, + /** @internal */ + scriptHandler = null) { + this.fragmentContext = fragmentContext; + this.scriptHandler = scriptHandler; + this.currentToken = null; + this.stopped = false; + /** @internal */ + this.insertionMode = InsertionMode.INITIAL; + /** @internal */ + this.originalInsertionMode = InsertionMode.INITIAL; + /** @internal */ + this.headElement = null; + /** @internal */ + this.formElement = null; + /** Indicates that the current node is not an element in the HTML namespace */ + this.currentNotInHTML = false; + /** + * The template insertion mode stack is maintained from the left. + * Ie. the topmost element will always have index 0. + * + * @internal + */ + this.tmplInsertionModeStack = []; + /** @internal */ + this.pendingCharacterTokens = []; + /** @internal */ + this.hasNonWhitespacePendingCharacterToken = false; + /** @internal */ + this.framesetOk = true; + /** @internal */ + this.skipNextNewLine = false; + /** @internal */ + this.fosterParentingEnabled = false; + this.options = Object.assign(Object.assign({}, defaultParserOptions), options); + this.treeAdapter = this.options.treeAdapter; + this.onParseError = this.options.onParseError; + // Always enable location info if we report parse errors. + if (this.onParseError) { + this.options.sourceCodeLocationInfo = true; + } + this.document = document !== null && document !== void 0 ? document : this.treeAdapter.createDocument(); + this.tokenizer = new index_js_1.Tokenizer(this.options, this); + this.activeFormattingElements = new formatting_element_list_js_1.FormattingElementList(this.treeAdapter); + this.fragmentContextID = fragmentContext ? (0, html_js_1.getTagID)(this.treeAdapter.getTagName(fragmentContext)) : html_js_1.TAG_ID.UNKNOWN; + this._setContextModes(fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : this.document, this.fragmentContextID); + this.openElements = new open_element_stack_js_1.OpenElementStack(this.document, this.treeAdapter, this); + } + // API + static parse(html, options) { + const parser = new this(options); + parser.tokenizer.write(html, true); + return parser.document; + } + static getFragmentParser(fragmentContext, options) { + const opts = Object.assign(Object.assign({}, defaultParserOptions), options); + //NOTE: use a
Shake it, baby