WIP: bootstrap and partial real Solana watcher implementation

This commit is contained in:
2026-08-16 09:17:45 +00:00
commit dc23412c3f
7232 changed files with 1687637 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = '00000000-0000-0000-0000-000000000000';
exports.default = _default;

View File

@@ -0,0 +1,440 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__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.deserializeUnchecked = exports.deserialize = exports.serialize = exports.BinaryReader = exports.BinaryWriter = exports.BorshError = exports.baseDecode = exports.baseEncode = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const bs58_1 = __importDefault(require("bs58"));
// TODO: Make sure this polyfill not included when not required
const encoding = __importStar(require("text-encoding-utf-8"));
const ResolvedTextDecoder = typeof TextDecoder !== "function" ? encoding.TextDecoder : TextDecoder;
const textDecoder = new ResolvedTextDecoder("utf-8", { fatal: true });
function baseEncode(value) {
if (typeof value === "string") {
value = Buffer.from(value, "utf8");
}
return bs58_1.default.encode(Buffer.from(value));
}
exports.baseEncode = baseEncode;
function baseDecode(value) {
return Buffer.from(bs58_1.default.decode(value));
}
exports.baseDecode = baseDecode;
const INITIAL_LENGTH = 1024;
class BorshError extends Error {
constructor(message) {
super(message);
this.fieldPath = [];
this.originalMessage = message;
}
addToFieldPath(fieldName) {
this.fieldPath.splice(0, 0, fieldName);
// NOTE: Modifying message directly as jest doesn't use .toString()
this.message = this.originalMessage + ": " + this.fieldPath.join(".");
}
}
exports.BorshError = BorshError;
/// Binary encoder.
class BinaryWriter {
constructor() {
this.buf = Buffer.alloc(INITIAL_LENGTH);
this.length = 0;
}
maybeResize() {
if (this.buf.length < 16 + this.length) {
this.buf = Buffer.concat([this.buf, Buffer.alloc(INITIAL_LENGTH)]);
}
}
writeU8(value) {
this.maybeResize();
this.buf.writeUInt8(value, this.length);
this.length += 1;
}
writeU16(value) {
this.maybeResize();
this.buf.writeUInt16LE(value, this.length);
this.length += 2;
}
writeU32(value) {
this.maybeResize();
this.buf.writeUInt32LE(value, this.length);
this.length += 4;
}
writeU64(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 8)));
}
writeU128(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 16)));
}
writeU256(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 32)));
}
writeU512(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 64)));
}
writeBuffer(buffer) {
// Buffer.from is needed as this.buf.subarray can return plain Uint8Array in browser
this.buf = Buffer.concat([
Buffer.from(this.buf.subarray(0, this.length)),
buffer,
Buffer.alloc(INITIAL_LENGTH),
]);
this.length += buffer.length;
}
writeString(str) {
this.maybeResize();
const b = Buffer.from(str, "utf8");
this.writeU32(b.length);
this.writeBuffer(b);
}
writeFixedArray(array) {
this.writeBuffer(Buffer.from(array));
}
writeArray(array, fn) {
this.maybeResize();
this.writeU32(array.length);
for (const elem of array) {
this.maybeResize();
fn(elem);
}
}
toArray() {
return this.buf.subarray(0, this.length);
}
}
exports.BinaryWriter = BinaryWriter;
function handlingRangeError(target, propertyKey, propertyDescriptor) {
const originalMethod = propertyDescriptor.value;
propertyDescriptor.value = function (...args) {
try {
return originalMethod.apply(this, args);
}
catch (e) {
if (e instanceof RangeError) {
const code = e.code;
if (["ERR_BUFFER_OUT_OF_BOUNDS", "ERR_OUT_OF_RANGE"].indexOf(code) >= 0) {
throw new BorshError("Reached the end of buffer when deserializing");
}
}
throw e;
}
};
}
class BinaryReader {
constructor(buf) {
this.buf = buf;
this.offset = 0;
}
readU8() {
const value = this.buf.readUInt8(this.offset);
this.offset += 1;
return value;
}
readU16() {
const value = this.buf.readUInt16LE(this.offset);
this.offset += 2;
return value;
}
readU32() {
const value = this.buf.readUInt32LE(this.offset);
this.offset += 4;
return value;
}
readU64() {
const buf = this.readBuffer(8);
return new bn_js_1.default(buf, "le");
}
readU128() {
const buf = this.readBuffer(16);
return new bn_js_1.default(buf, "le");
}
readU256() {
const buf = this.readBuffer(32);
return new bn_js_1.default(buf, "le");
}
readU512() {
const buf = this.readBuffer(64);
return new bn_js_1.default(buf, "le");
}
readBuffer(len) {
if (this.offset + len > this.buf.length) {
throw new BorshError(`Expected buffer length ${len} isn't within bounds`);
}
const result = this.buf.slice(this.offset, this.offset + len);
this.offset += len;
return result;
}
readString() {
const len = this.readU32();
const buf = this.readBuffer(len);
try {
// NOTE: Using TextDecoder to fail on invalid UTF-8
return textDecoder.decode(buf);
}
catch (e) {
throw new BorshError(`Error decoding UTF-8 string: ${e}`);
}
}
readFixedArray(len) {
return new Uint8Array(this.readBuffer(len));
}
readArray(fn) {
const len = this.readU32();
const result = Array();
for (let i = 0; i < len; ++i) {
result.push(fn());
}
return result;
}
}
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU8", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU16", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU32", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU64", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU128", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU256", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU512", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readString", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readFixedArray", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readArray", null);
exports.BinaryReader = BinaryReader;
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function serializeField(schema, fieldName, value, fieldType, writer) {
try {
// TODO: Handle missing values properly (make sure they never result in just skipped write)
if (typeof fieldType === "string") {
writer[`write${capitalizeFirstLetter(fieldType)}`](value);
}
else if (fieldType instanceof Array) {
if (typeof fieldType[0] === "number") {
if (value.length !== fieldType[0]) {
throw new BorshError(`Expecting byte array of length ${fieldType[0]}, but got ${value.length} bytes`);
}
writer.writeFixedArray(value);
}
else if (fieldType.length === 2 && typeof fieldType[1] === "number") {
if (value.length !== fieldType[1]) {
throw new BorshError(`Expecting byte array of length ${fieldType[1]}, but got ${value.length} bytes`);
}
for (let i = 0; i < fieldType[1]; i++) {
serializeField(schema, null, value[i], fieldType[0], writer);
}
}
else {
writer.writeArray(value, (item) => {
serializeField(schema, fieldName, item, fieldType[0], writer);
});
}
}
else if (fieldType.kind !== undefined) {
switch (fieldType.kind) {
case "option": {
if (value === null || value === undefined) {
writer.writeU8(0);
}
else {
writer.writeU8(1);
serializeField(schema, fieldName, value, fieldType.type, writer);
}
break;
}
case "map": {
writer.writeU32(value.size);
value.forEach((val, key) => {
serializeField(schema, fieldName, key, fieldType.key, writer);
serializeField(schema, fieldName, val, fieldType.value, writer);
});
break;
}
default:
throw new BorshError(`FieldType ${fieldType} unrecognized`);
}
}
else {
serializeStruct(schema, value, writer);
}
}
catch (error) {
if (error instanceof BorshError) {
error.addToFieldPath(fieldName);
}
throw error;
}
}
function serializeStruct(schema, obj, writer) {
if (typeof obj.borshSerialize === "function") {
obj.borshSerialize(writer);
return;
}
const structSchema = schema.get(obj.constructor);
if (!structSchema) {
throw new BorshError(`Class ${obj.constructor.name} is missing in schema`);
}
if (structSchema.kind === "struct") {
structSchema.fields.map(([fieldName, fieldType]) => {
serializeField(schema, fieldName, obj[fieldName], fieldType, writer);
});
}
else if (structSchema.kind === "enum") {
const name = obj[structSchema.field];
for (let idx = 0; idx < structSchema.values.length; ++idx) {
const [fieldName, fieldType] = structSchema.values[idx];
if (fieldName === name) {
writer.writeU8(idx);
serializeField(schema, fieldName, obj[fieldName], fieldType, writer);
break;
}
}
}
else {
throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`);
}
}
/// Serialize given object using schema of the form:
/// { class_name -> [ [field_name, field_type], .. ], .. }
function serialize(schema, obj, Writer = BinaryWriter) {
const writer = new Writer();
serializeStruct(schema, obj, writer);
return writer.toArray();
}
exports.serialize = serialize;
function deserializeField(schema, fieldName, fieldType, reader) {
try {
if (typeof fieldType === "string") {
return reader[`read${capitalizeFirstLetter(fieldType)}`]();
}
if (fieldType instanceof Array) {
if (typeof fieldType[0] === "number") {
return reader.readFixedArray(fieldType[0]);
}
else if (typeof fieldType[1] === "number") {
const arr = [];
for (let i = 0; i < fieldType[1]; i++) {
arr.push(deserializeField(schema, null, fieldType[0], reader));
}
return arr;
}
else {
return reader.readArray(() => deserializeField(schema, fieldName, fieldType[0], reader));
}
}
if (fieldType.kind === "option") {
const option = reader.readU8();
if (option) {
return deserializeField(schema, fieldName, fieldType.type, reader);
}
return undefined;
}
if (fieldType.kind === "map") {
let map = new Map();
const length = reader.readU32();
for (let i = 0; i < length; i++) {
const key = deserializeField(schema, fieldName, fieldType.key, reader);
const val = deserializeField(schema, fieldName, fieldType.value, reader);
map.set(key, val);
}
return map;
}
return deserializeStruct(schema, fieldType, reader);
}
catch (error) {
if (error instanceof BorshError) {
error.addToFieldPath(fieldName);
}
throw error;
}
}
function deserializeStruct(schema, classType, reader) {
if (typeof classType.borshDeserialize === "function") {
return classType.borshDeserialize(reader);
}
const structSchema = schema.get(classType);
if (!structSchema) {
throw new BorshError(`Class ${classType.name} is missing in schema`);
}
if (structSchema.kind === "struct") {
const result = {};
for (const [fieldName, fieldType] of schema.get(classType).fields) {
result[fieldName] = deserializeField(schema, fieldName, fieldType, reader);
}
return new classType(result);
}
if (structSchema.kind === "enum") {
const idx = reader.readU8();
if (idx >= structSchema.values.length) {
throw new BorshError(`Enum index: ${idx} is out of range`);
}
const [fieldName, fieldType] = structSchema.values[idx];
const fieldValue = deserializeField(schema, fieldName, fieldType, reader);
return new classType({ [fieldName]: fieldValue });
}
throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`);
}
/// Deserializes object from bytes using schema.
function deserialize(schema, classType, buffer, Reader = BinaryReader) {
const reader = new Reader(buffer);
const result = deserializeStruct(schema, classType, reader);
if (reader.offset < buffer.length) {
throw new BorshError(`Unexpected ${buffer.length - reader.offset} bytes after deserialized data`);
}
return result;
}
exports.deserialize = deserialize;
/// Deserializes object from bytes using schema, without checking the length read
function deserializeUnchecked(schema, classType, buffer, Reader = BinaryReader) {
const reader = new Reader(buffer);
return deserializeStruct(schema, classType, reader);
}
exports.deserializeUnchecked = deserializeUnchecked;

View File

@@ -0,0 +1,11 @@
import type { VisitorKeys } from '@typescript-eslint/visitor-keys';
import type { TSESTree } from './ts-estree';
type SimpleTraverseOptions = Readonly<{
enter: (node: TSESTree.Node, parent: TSESTree.Node | undefined) => void;
visitorKeys?: Readonly<VisitorKeys>;
} | {
visitorKeys?: Readonly<VisitorKeys>;
visitors: Record<string, (node: TSESTree.Node, parent: TSESTree.Node | undefined) => void>;
}>;
export declare function simpleTraverse(startingNode: TSESTree.Node, options: SimpleTraverseOptions, setParentPointers?: boolean): void;
export {};

View File

@@ -0,0 +1,32 @@
import type { RuleContext, RuleListener, RuleMetaData, RuleMetaDataDocs, RuleModule } from '../ts-eslint/Rule';
export type NamedCreateRuleMetaDocs = Omit<RuleMetaDataDocs, 'url'>;
export type NamedCreateRuleMeta<MessageIds extends string, PluginDocs = unknown, Options extends readonly unknown[] = []> = {
docs: PluginDocs & RuleMetaDataDocs;
} & Omit<RuleMetaData<MessageIds, PluginDocs, Options>, 'docs'>;
export interface RuleCreateAndOptions<Options extends readonly unknown[], MessageIds extends string> {
create: (context: Readonly<RuleContext<MessageIds, Options>>, optionsWithDefault: Readonly<Options>) => RuleListener;
/** @deprecated Use meta.defaultOptions instead */
defaultOptions?: Readonly<Options>;
}
export interface RuleWithMeta<Options extends readonly unknown[], MessageIds extends string, Docs = unknown> extends RuleCreateAndOptions<Options, MessageIds> {
meta: RuleMetaData<MessageIds, Docs, Options>;
name?: string;
}
export interface RuleWithMetaAndName<Options extends readonly unknown[], MessageIds extends string, Docs = unknown> extends RuleCreateAndOptions<Options, MessageIds> {
meta: NamedCreateRuleMeta<MessageIds, Docs, Options>;
name: string;
}
type RuleModuleWithName<MessageIds extends string, Options extends readonly unknown[] = [], Docs = unknown, ExtendedRuleListener extends RuleListener = RuleListener> = RuleModule<MessageIds, Options, Docs, ExtendedRuleListener> & {
name: string;
};
/**
* Creates reusable function to create rules with default options and docs URLs.
*
* @param urlCreator Creates a documentation URL for a given rule name.
* @returns Function to create a rule with the docs URL format.
*/
export declare function RuleCreator<PluginDocs = unknown>(urlCreator: (ruleName: string) => string): <Options extends readonly unknown[], MessageIds extends string>({ meta, name, ...rule }: Readonly<RuleWithMetaAndName<Options, MessageIds, PluginDocs>>) => RuleModuleWithName<MessageIds, Options, PluginDocs>;
export declare namespace RuleCreator {
var withoutDocs: <Options extends readonly unknown[], MessageIds extends string>(args: Readonly<RuleWithMeta<Options, MessageIds>>) => RuleModule<MessageIds, Options>;
}
export { type RuleListener, type RuleModule } from '../ts-eslint/Rule';

View File

@@ -0,0 +1,19 @@
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}

View File

@@ -0,0 +1,8 @@
export { c as createManualModuleSource, h as hoistMocks } from './hoistMocks.d-w2ILr1dG.js';
export { automockModule } from './automock.js';
import 'magic-string';
declare function initSyntaxLexers(): Promise<void>;
declare function collectModuleExports(filename: string, code: string, format: "module" | "commonjs", exports?: string[]): string[];
export { collectModuleExports, initSyntaxLexers };

View File

@@ -0,0 +1,19 @@
"use strict";
var _get_prototype_of = require("./_get_prototype_of.cjs");
var _is_native_reflect_construct = require("./_is_native_reflect_construct.cjs");
var _possible_constructor_return = require("./_possible_constructor_return.cjs");
function _call_super(_this, derived, args) {
// Super
derived = _get_prototype_of._(derived);
return _possible_constructor_return._(
_this,
_is_native_reflect_construct._()
// NOTE: This doesn't work if this.__proto__.constructor has been modified.
? Reflect.construct(derived, args || [], _get_prototype_of._(_this).constructor)
: derived.apply(_this, args)
);
}
exports._ = _call_super;

View File

@@ -0,0 +1,42 @@
type ParseOpts = {
name?: string;
types?: number[];
text: string;
};
type ValueMapper = (param: any, index: number) => any;
type BindOpts = {
portal?: string;
binary?: boolean;
statement?: string;
values?: any[];
valueMapper?: ValueMapper;
};
type ExecOpts = {
portal?: string;
rows?: number;
};
type PortalOpts = {
type: 'S' | 'P';
name?: string;
};
declare const serialize: {
startup: (opts: Record<string, string>) => Buffer;
password: (password: string) => Buffer;
requestSsl: () => Buffer;
sendSASLInitialResponseMessage: (mechanism: string, initialResponse: string) => Buffer;
sendSCRAMClientFinalMessage: (additionalData: string) => Buffer;
query: (text: string) => Buffer;
parse: (query: ParseOpts) => Buffer;
bind: (config?: BindOpts) => Buffer;
execute: (config?: ExecOpts) => Buffer;
describe: (msg: PortalOpts) => Buffer;
close: (msg: PortalOpts) => Buffer;
flush: () => Buffer<ArrayBufferLike>;
sync: () => Buffer<ArrayBufferLike>;
end: () => Buffer<ArrayBufferLike>;
copyData: (chunk: Buffer) => Buffer;
copyDone: () => Buffer<ArrayBufferLike>;
copyFail: (message: string) => Buffer;
cancel: (processID: number, secretKey: number) => Buffer;
};
export { serialize };

View File

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

View File

@@ -0,0 +1,249 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
const getESLintCoreRule_1 = require("../util/getESLintCoreRule");
const baseRule = (0, getESLintCoreRule_1.getESLintCoreRule)('no-magic-numbers');
// Extend base schema with additional property to ignore TS numeric literal types
const schema = (0, util_1.deepMerge)(
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- https://github.com/microsoft/TypeScript/issues/17002
Array.isArray(baseRule.meta.schema)
? baseRule.meta.schema[0]
: baseRule.meta.schema, {
properties: {
ignoreEnums: {
type: 'boolean',
description: 'Whether enums used in TypeScript are considered okay.',
},
ignoreNumericLiteralTypes: {
type: 'boolean',
description: 'Whether numbers used in TypeScript numeric literal types are considered okay.',
},
ignoreReadonlyClassProperties: {
type: 'boolean',
description: 'Whether `readonly` class properties are considered okay.',
},
ignoreTypeIndexes: {
type: 'boolean',
description: 'Whether numbers used to index types are okay.',
},
},
});
const defaultOptions = [
{
detectObjects: false,
enforceConst: false,
ignore: [],
ignoreArrayIndexes: false,
ignoreEnums: false,
ignoreNumericLiteralTypes: false,
ignoreReadonlyClassProperties: false,
ignoreTypeIndexes: false,
},
];
exports.default = (0, util_1.createRule)({
name: 'no-magic-numbers',
meta: {
type: 'suggestion',
defaultOptions,
docs: {
description: 'Disallow magic numbers',
extendsBaseRule: true,
frozen: true,
},
messages: baseRule.meta.messages,
schema: [schema],
},
defaultOptions,
create(context, [options]) {
const rules = baseRule.create(context);
const ignored = new Set((options.ignore ?? []).map(normalizeIgnoreValue));
return {
Literal(node) {
// If its not a numeric literal were not interested
if (typeof node.value !== 'number' && typeof node.value !== 'bigint') {
return;
}
// This will be `true` if were configured to ignore this case (eg. its
// an enum and `ignoreEnums` is `true`). It will be `false` if were not
// configured to ignore this case. It will remain `undefined` if this is
// not one of our exception cases, and well fall back to the base rule.
let isAllowed;
// Check if the node is ignored
if (ignored.has(normalizeLiteralValue(node, node.value))) {
isAllowed = true;
}
// Check if the node is a TypeScript enum declaration
else if (isParentTSEnumDeclaration(node)) {
isAllowed = options.ignoreEnums === true;
}
// Check TypeScript specific nodes for Numeric Literal
else if (isTSNumericLiteralType(node)) {
isAllowed = options.ignoreNumericLiteralTypes === true;
}
// Check if the node is a type index
else if (isAncestorTSIndexedAccessType(node)) {
isAllowed = options.ignoreTypeIndexes === true;
}
// Check if the node is a readonly class property
else if (isParentTSReadonlyPropertyDefinition(node)) {
isAllowed = options.ignoreReadonlyClassProperties === true;
}
// If weve hit a case where the ignore option is true we can return now
if (isAllowed === true) {
return;
}
// If the ignore option is *not* set we can report it now
if (isAllowed === false) {
let fullNumberNode = node;
let raw = node.raw;
if (node.parent.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
// the base rule only shows the operator for negative numbers
// https://github.com/eslint/eslint/blob/9dfc8501fb1956c90dc11e6377b4cb38a6bea65d/lib/rules/no-magic-numbers.js#L126
node.parent.operator === '-') {
fullNumberNode = node.parent;
raw = `${node.parent.operator}${node.raw}`;
}
context.report({
node: fullNumberNode,
messageId: 'noMagic',
data: { raw },
});
return;
}
// Let the base rule deal with the rest
rules.Literal(node);
},
};
},
});
/**
* Convert the value to bigint if it's a string. Otherwise, return the value as-is.
* @param value The value to normalize.
* @returns The normalized value.
*/
function normalizeIgnoreValue(value) {
if (typeof value === 'string') {
return BigInt(value.slice(0, -1));
}
return value;
}
/**
* Converts the node to its numeric value, handling prefixed numbers (-1 / +1)
* @param node the node to normalize.
* @param value the node's value.
*/
function normalizeLiteralValue(node, value) {
if (node.parent.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
['-', '+'].includes(node.parent.operator) &&
node.parent.operator === '-') {
return -value;
}
return value;
}
/**
* Gets the true parent of the literal, handling prefixed numbers (-1 / +1)
*/
function getLiteralParent(node) {
if (node.parent.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
['-', '+'].includes(node.parent.operator)) {
return node.parent.parent;
}
return node.parent;
}
/**
* Checks if the node grandparent is a Typescript type alias declaration
* @param node the node to be validated.
* @returns true if the node grandparent is a Typescript type alias declaration
* @private
*/
function isGrandparentTSTypeAliasDeclaration(node) {
return node.parent?.parent?.type === utils_1.AST_NODE_TYPES.TSTypeAliasDeclaration;
}
/**
* Checks if the node grandparent is a Typescript union type and its parent is a type alias declaration
* @param node the node to be validated.
* @returns true if the node grandparent is a Typescript union type and its parent is a type alias declaration
* @private
*/
function isGrandparentTSUnionType(node) {
if (node.parent?.parent?.type === utils_1.AST_NODE_TYPES.TSUnionType) {
return isGrandparentTSTypeAliasDeclaration(node.parent);
}
return false;
}
/**
* Checks if the node parent is a Typescript enum member
* @param node the node to be validated.
* @returns true if the node parent is a Typescript enum member
* @private
*/
function isParentTSEnumDeclaration(node) {
const parent = getLiteralParent(node);
return parent?.type === utils_1.AST_NODE_TYPES.TSEnumMember;
}
/**
* Checks if the node parent is a Typescript literal type
* @param node the node to be validated.
* @returns true if the node parent is a Typescript literal type
* @private
*/
function isParentTSLiteralType(node) {
return node.parent?.type === utils_1.AST_NODE_TYPES.TSLiteralType;
}
/**
* Checks if the node is a valid TypeScript numeric literal type.
* @param node the node to be validated.
* @returns true if the node is a TypeScript numeric literal type.
* @private
*/
function isTSNumericLiteralType(node) {
// For negative numbers, use the parent node
if (node.parent?.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
node.parent.operator === '-') {
node = node.parent;
}
// If the parent node is not a TSLiteralType, early return
if (!isParentTSLiteralType(node)) {
return false;
}
// If the grandparent is a TSTypeAliasDeclaration, ignore
if (isGrandparentTSTypeAliasDeclaration(node)) {
return true;
}
// If the grandparent is a TSUnionType and it's parent is a TSTypeAliasDeclaration, ignore
if (isGrandparentTSUnionType(node)) {
return true;
}
return false;
}
/**
* Checks if the node parent is a readonly class property
* @param node the node to be validated.
* @returns true if the node parent is a readonly class property
* @private
*/
function isParentTSReadonlyPropertyDefinition(node) {
const parent = getLiteralParent(node);
if (parent?.type === utils_1.AST_NODE_TYPES.PropertyDefinition && parent.readonly) {
return true;
}
return false;
}
/**
* Checks if the node is part of a type indexed access (eg. Foo[4])
* @param node the node to be validated.
* @returns true if the node is part of an indexed access
* @private
*/
function isAncestorTSIndexedAccessType(node) {
// Handle unary expressions (eg. -4)
let ancestor = getLiteralParent(node);
// Go up another level while were part of a type union (eg. 1 | 2) or
// intersection (eg. 1 & 2)
while (ancestor?.parent?.type === utils_1.AST_NODE_TYPES.TSUnionType ||
ancestor?.parent?.type === utils_1.AST_NODE_TYPES.TSIntersectionType) {
ancestor = ancestor.parent;
}
return ancestor?.parent?.type === utils_1.AST_NODE_TYPES.TSIndexedAccessType;
}

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImportBindingDefinition = void 0;
const DefinitionBase_1 = require("./DefinitionBase");
const DefinitionType_1 = require("./DefinitionType");
class ImportBindingDefinition extends DefinitionBase_1.DefinitionBase {
isTypeDefinition = true;
isVariableDefinition = true;
constructor(name, node, decl) {
super(DefinitionType_1.DefinitionType.ImportBinding, name, node, decl);
}
}
exports.ImportBindingDefinition = ImportBindingDefinition;

View File

@@ -0,0 +1,15 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2023 = void 0;
const es2022_1 = require("./es2022");
const es2023_array_1 = require("./es2023.array");
const es2023_collection_1 = require("./es2023.collection");
const es2023_intl_1 = require("./es2023.intl");
exports.es2023 = {
libs: [es2022_1.es2022, es2023_array_1.es2023_array, es2023_collection_1.es2023_collection, es2023_intl_1.es2023_intl],
variables: [],
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/internal/utils.ts"],"names":[],"mappings":"AAKA;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,IAAI,CAAC;AAErD;;;;GAIG;AACH,MAAM,WAAW,OAAO,CAAC,CAAC;IACtB,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAEnE;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,SAAmB,EAAE,cAAc,CAAC,EAAE,WAAW,GAAG,KAAK,CAG1G;AAED,wBAAgB,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,WAAW,GAAG,KAAK,CAQ1E"}

View File

@@ -0,0 +1,5 @@
import { DatabaseError } from './messages';
import { serialize } from './serializer';
import { MessageCallback } from './parser';
export declare function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise<void>;
export { serialize, DatabaseError };

View File

@@ -0,0 +1,27 @@
import getPrototypeOf from "./getPrototypeOf.js";
import setPrototypeOf from "./setPrototypeOf.js";
import isNativeFunction from "./isNativeFunction.js";
import construct from "./construct.js";
function _wrapNativeSuper(t) {
var r = "function" == typeof Map ? new Map() : void 0;
return _wrapNativeSuper = function _wrapNativeSuper(t) {
if (null === t || !isNativeFunction(t)) return t;
if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
if (void 0 !== r) {
if (r.has(t)) return r.get(t);
r.set(t, Wrapper);
}
function Wrapper() {
return construct(t, arguments, getPrototypeOf(this).constructor);
}
return Wrapper.prototype = Object.create(t.prototype, {
constructor: {
value: Wrapper,
enumerable: !1,
writable: !0,
configurable: !0
}
}), setPrototypeOf(Wrapper, t);
}, _wrapNativeSuper(t);
}
export { _wrapNativeSuper as default };

View File

@@ -0,0 +1,68 @@
import { expect, test } from "vitest";
import * as z from "zod/v4";
test("async refine .parse()", async () => {
// throws ZodAsyncError
const s1 = z.string().refine(async (_val) => true);
expect(() => s1.safeParse("asdf")).toThrow();
});
test("async refine", async () => {
const s1 = z.string().refine(async (_val) => true);
const r1 = await s1.parseAsync("asdf");
expect(r1).toEqual("asdf");
const s2 = z.string().refine(async (_val) => false);
const r2 = await s2.safeParseAsync("asdf");
expect(r2.success).toBe(false);
expect(r2).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"path": [],
"message": "Invalid input"
}
]],
"success": false,
}
`);
});
test("async refine with Promises", async () => {
// expect.assertions(2);
const schema1 = z.string().refine((_val) => Promise.resolve(true));
const v1 = await schema1.parseAsync("asdf");
expect(v1).toEqual("asdf");
const schema2 = z.string().refine((_val) => Promise.resolve(false));
await expect(schema2.parseAsync("asdf")).rejects.toBeDefined();
const schema3 = z.string().refine((_val) => Promise.resolve(true));
await expect(schema3.parseAsync("asdf")).resolves.toEqual("asdf");
return await expect(schema3.parseAsync("qwer")).resolves.toEqual("qwer");
});
test("async refine that uses value", async () => {
const schema1 = z.string().refine(async (val) => {
return val.length > 5;
});
const r1 = await schema1.safeParseAsync("asdf");
expect(r1.success).toBe(false);
expect(r1.error).toMatchInlineSnapshot(`
[ZodError: [
{
"code": "custom",
"path": [],
"message": "Invalid input"
}
]]
`);
const r2 = await schema1.safeParseAsync("asdf123");
expect(r2.success).toBe(true);
expect(r2.data).toEqual("asdf123");
});

View File

@@ -0,0 +1,15 @@
import * as fs from 'node:fs'
import { once } from 'node:events'
interface TransportOptions {
destination?: fs.PathLike
}
async function run (opts: TransportOptions): Promise<fs.WriteStream> {
if (!opts.destination) throw new Error('destination is required')
const stream = fs.createWriteStream(opts.destination, { encoding: 'utf8' })
await once(stream, 'open')
return stream
}
export default run

View File

@@ -0,0 +1,54 @@
'use strict'
const test = require('node:test')
const assert = require('node:assert')
const { join } = require('node:path')
const { pathToFileURL } = require('node:url')
const { readFile } = require('node:fs').promises
const execa = require('execa')
const { file, watchFileCreated } = require('../helper')
test('pino.transport works when loaded via --import=preload', async () => {
const destination = file()
const preload = pathToFileURL(join(__dirname, '..', 'fixtures', 'transport-preload.mjs')).href
const main = join(__dirname, '..', 'fixtures', 'transport-preload-main.mjs')
await execa(process.argv[0], [
`--import=${preload}`,
main,
destination
], { timeout: 10000 })
await watchFileCreated(destination)
const result = JSON.parse(await readFile(destination))
assert.equal(result.msg, 'hello from main')
})
test('pino.transport works when loaded via --import preload (space separated)', async () => {
const destination = file()
const preload = pathToFileURL(join(__dirname, '..', 'fixtures', 'transport-preload.mjs')).href
const main = join(__dirname, '..', 'fixtures', 'transport-preload-main.mjs')
await execa(process.argv[0], [
'--import',
preload,
main,
destination
], { timeout: 10000 })
await watchFileCreated(destination)
const result = JSON.parse(await readFile(destination))
assert.equal(result.msg, 'hello from main')
})
test('pino.transport ignores missing absolute preload from NODE_OPTIONS in worker', async () => {
const destination = file()
const main = join(__dirname, '..', 'fixtures', 'transport-invalid-node-options.js')
await execa(process.argv[0], [main, destination], { timeout: 10000 })
await watchFileCreated(destination)
const result = JSON.parse(await readFile(destination))
assert.equal(result.msg, 'hello with invalid node options preload')
})

View File

@@ -0,0 +1,14 @@
'use strict';
module.exports = {
// agent
CURRENT_ID: Symbol('agentkeepalive#currentId'),
CREATE_ID: Symbol('agentkeepalive#createId'),
INIT_SOCKET: Symbol('agentkeepalive#initSocket'),
CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'),
// socket
SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'),
SOCKET_NAME: Symbol('agentkeepalive#socketName'),
SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'),
SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'),
};

View File

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

View File

@@ -0,0 +1,48 @@
'use strict'
const seen = Symbol('circular-ref-tag')
const rawSymbol = Symbol('pino-raw-err-ref')
const pinoErrProto = Object.create({}, {
type: {
enumerable: true,
writable: true,
value: undefined
},
message: {
enumerable: true,
writable: true,
value: undefined
},
stack: {
enumerable: true,
writable: true,
value: undefined
},
aggregateErrors: {
enumerable: true,
writable: true,
value: undefined
},
raw: {
enumerable: false,
get: function () {
return this[rawSymbol]
},
set: function (val) {
this[rawSymbol] = val
}
}
})
Object.defineProperty(pinoErrProto, rawSymbol, {
writable: true,
value: {}
})
module.exports = {
pinoErrProto,
pinoErrorSymbols: {
seen,
rawSymbol
}
}

View File

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

View File

@@ -0,0 +1,23 @@
const UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
const UUID_PARSE = /^[0-9A-Fa-f\-]{36}/;
//RFC 4122
const handler = {
scheme: "urn:uuid",
parse: function (urnComponents, options) {
const uuidComponents = urnComponents;
uuidComponents.uuid = uuidComponents.nss;
uuidComponents.nss = undefined;
if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
uuidComponents.error = uuidComponents.error || "UUID is not valid.";
}
return uuidComponents;
},
serialize: function (uuidComponents, options) {
const urnComponents = uuidComponents;
//normalize UUID
urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
return urnComponents;
},
};
export default handler;
//# sourceMappingURL=urn-uuid.js.map

View File

@@ -0,0 +1,124 @@
import {
isArray,
isMaybeThenable
} from './utils';
import {
noop,
reject,
fulfill,
subscribe,
FULFILLED,
REJECTED,
PENDING,
handleMaybeThenable
} from './-internal';
import then from './then';
import Promise from './promise';
import originalResolve from './promise/resolve';
import originalThen from './then';
import { makePromise, PROMISE_ID } from './-internal';
function validationError() {
return new Error('Array Methods must be provided an Array');
};
export default class Enumerator {
constructor(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
_enumerate(input) {
for (let i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
}
_eachEntry(entry, i) {
let c = this._instanceConstructor;
let { resolve } = c;
if (resolve === originalResolve) {
let then;
let error;
let didError = false;
try {
then = entry.then;
} catch (e) {
didError = true;
error = e;
}
if (then === originalThen &&
entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
let promise = new c(noop);
if (didError) {
reject(promise, error);
} else {
handleMaybeThenable(promise, entry, then);
}
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
}
_settledAt(state, i, value) {
let { promise } = this;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
}
_willSettleAt(promise, i) {
let enumerator = this;
subscribe(
promise, undefined,
value => enumerator._settledAt(FULFILLED, i, value),
reason => enumerator._settledAt(REJECTED, i, reason)
);
}
};