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,13 @@
const { Writable } = require('node:stream')
module.exports = () =>
new Writable({
autoDestroy: true,
write (chunk, enc, cb) {
setImmediate(() => {
/* eslint-disable no-empty */
for (let i = 0; i < 1e3; i++) {}
process.exit(0)
})
}
})

View File

@@ -0,0 +1,109 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "harf", verb: "olmalıdır" },
file: { unit: "bayt", verb: "olmalıdır" },
array: { unit: "unsur", verb: "olmalıdır" },
set: { unit: "unsur", verb: "olmalıdır" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "giren",
email: "epostagâh",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO hengâmı",
date: "ISO tarihi",
time: "ISO zamanı",
duration: "ISO müddeti",
ipv4: "IPv4 nişânı",
ipv6: "IPv6 nişânı",
cidrv4: "IPv4 menzili",
cidrv6: "IPv6 menzili",
base64: "base64-şifreli metin",
base64url: "base64url-şifreli metin",
json_string: "JSON metin",
e164: "E.164 sayısı",
jwt: "JWT",
template_literal: "giren",
};
const TypeDictionary = {
nan: "NaN",
number: "numara",
array: "saf",
null: "gayb",
};
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = TypeDictionary[issue.expected] ?? issue.expected;
const receivedType = util.parsedType(issue.input);
const received = TypeDictionary[receivedType] ?? receivedType;
if (/^[A-Z]/.test(issue.expected)) {
return `Fâsit giren: umulan instanceof ${issue.expected}, alınan ${received}`;
}
return `Fâsit giren: umulan ${expected}, alınan ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Fâsit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`;
return `Fâsit tercih: mûteberler ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`;
return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;
}
return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`;
if (_issue.format === "ends_with")
return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`;
if (_issue.format === "includes")
return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;
if (_issue.format === "regex")
return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`;
return `Fâsit ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`;
case "unrecognized_keys":
return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `${issue.origin} için tanınmayan anahtar var.`;
case "invalid_union":
return "Giren tanınamadı.";
case "invalid_element":
return `${issue.origin} için tanınmayan kıymet var.`;
default:
return `Kıymet tanınamadı.`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,93 @@
import Dispatcher from './dispatcher'
import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher'
import { setGlobalOrigin, getGlobalOrigin } from './global-origin'
import Pool from './pool'
import { RedirectHandler, DecoratorHandler } from './handlers'
import BalancedPool from './balanced-pool'
import RoundRobinPool from './round-robin-pool'
import Client from './client'
import H2CClient from './h2c-client'
import buildConnector from './connector'
import errors from './errors'
import Agent from './agent'
import Dispatcher1Wrapper from './dispatcher1-wrapper'
import MockClient from './mock-client'
import MockPool from './mock-pool'
import MockAgent from './mock-agent'
import { SnapshotAgent } from './snapshot-agent'
import { MockCallHistory, MockCallHistoryLog } from './mock-call-history'
import mockErrors from './mock-errors'
import ProxyAgent from './proxy-agent'
import Socks5ProxyAgent from './socks5-proxy-agent'
import EnvHttpProxyAgent from './env-http-proxy-agent'
import RetryHandler from './retry-handler'
import RetryAgent from './retry-agent'
import { request, pipeline, stream, connect, upgrade } from './api'
import interceptors from './interceptors'
import CacheInterceptor from './cache-interceptor'
declare const cacheStores: {
MemoryCacheStore: typeof CacheInterceptor.MemoryCacheStore;
SqliteCacheStore: typeof CacheInterceptor.SqliteCacheStore;
}
export * from './util'
export * from './cookies'
export * from './eventsource'
export * from './fetch'
export * from './formdata'
export * from './diagnostics-channel'
export * from './websocket'
export * from './content-type'
export * from './cache'
export { Interceptable } from './mock-interceptor'
declare function globalThisInstall (): void
export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, Dispatcher1Wrapper, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, Socks5ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install }
export default Undici
declare namespace Undici {
const Dispatcher: typeof import('./dispatcher').default
const Pool: typeof import('./pool').default
const RedirectHandler: typeof import ('./handlers').RedirectHandler
const DecoratorHandler: typeof import ('./handlers').DecoratorHandler
const RetryHandler: typeof import ('./retry-handler').default
const BalancedPool: typeof import('./balanced-pool').default
const RoundRobinPool: typeof import('./round-robin-pool').default
const Client: typeof import('./client').default
const H2CClient: typeof import('./h2c-client').default
const buildConnector: typeof import('./connector').default
const errors: typeof import('./errors').default
const Agent: typeof import('./agent').default
const Dispatcher1Wrapper: typeof import('./dispatcher1-wrapper').default
const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher
const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher
const request: typeof import('./api').request
const stream: typeof import('./api').stream
const pipeline: typeof import('./api').pipeline
const connect: typeof import('./api').connect
const upgrade: typeof import('./api').upgrade
const MockClient: typeof import('./mock-client').default
const MockPool: typeof import('./mock-pool').default
const MockAgent: typeof import('./mock-agent').default
const SnapshotAgent: typeof import('./snapshot-agent').SnapshotAgent
const MockCallHistory: typeof import('./mock-call-history').MockCallHistory
const MockCallHistoryLog: typeof import('./mock-call-history').MockCallHistoryLog
const mockErrors: typeof import('./mock-errors').default
const ProxyAgent: typeof import('./proxy-agent').default
const Socks5ProxyAgent: typeof import('./socks5-proxy-agent').default
const fetch: typeof import('./fetch').fetch
const Headers: typeof import('./fetch').Headers
const Response: typeof import('./fetch').Response
const Request: typeof import('./fetch').Request
const FormData: typeof import('./formdata').FormData
const caches: typeof import('./cache').caches
const interceptors: typeof import('./interceptors').default
const cacheStores: {
MemoryCacheStore: typeof import('./cache-interceptor').default.MemoryCacheStore,
SqliteCacheStore: typeof import('./cache-interceptor').default.SqliteCacheStore
}
const install: typeof globalThisInstall
}

View File

@@ -0,0 +1,204 @@
/**
* @fileoverview Rule to disallow unnecessary computed property keys in object literals
* @author Burak Yigit Kaya
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Determines whether the computed key syntax is unnecessarily used for the given node.
* In particular, it determines whether removing the square brackets and using the content between them
* directly as the key (e.g. ['foo'] -> 'foo') would produce valid syntax and preserve the same behavior.
* Valid non-computed keys are only: identifiers, number literals and string literals.
* Only literals can preserve the same behavior, with a few exceptions for specific node types:
* Property
* - { ["__proto__"]: foo } defines a property named "__proto__"
* { "__proto__": foo } defines object's prototype
* PropertyDefinition
* - class C { ["constructor"]; } defines an instance field named "constructor"
* class C { "constructor"; } produces a parsing error
* - class C { static ["constructor"]; } defines a static field named "constructor"
* class C { static "constructor"; } produces a parsing error
* - class C { static ["prototype"]; } produces a runtime error (doesn't break the whole script)
* class C { static "prototype"; } produces a parsing error (breaks the whole script)
* MethodDefinition
* - class C { ["constructor"]() {} } defines a prototype method named "constructor"
* class C { "constructor"() {} } defines the constructor
* - class C { static ["prototype"]() {} } produces a runtime error (doesn't break the whole script)
* class C { static "prototype"() {} } produces a parsing error (breaks the whole script)
* @param {ASTNode} node The node to check. It can be `Property`, `PropertyDefinition` or `MethodDefinition`.
* @throws {Error} (Unreachable.)
* @returns {void} `true` if the node has useless computed key.
*/
function hasUselessComputedKey(node) {
if (!node.computed) {
return false;
}
const { key } = node;
if (key.type !== "Literal") {
return false;
}
const { value } = key;
if (typeof value !== "number" && typeof value !== "string") {
return false;
}
switch (node.type) {
case "Property":
if (node.parent.type === "ObjectExpression") {
return value !== "__proto__";
}
return true;
case "PropertyDefinition":
if (node.static) {
return value !== "constructor" && value !== "prototype";
}
return value !== "constructor";
case "MethodDefinition":
if (node.static) {
return value !== "prototype";
}
return value !== "constructor";
/* c8 ignore next */
default:
throw new Error(`Unexpected node type: ${node.type}`);
}
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
{
enforceForClassMembers: true,
},
],
docs: {
description:
"Disallow unnecessary computed property keys in objects and classes",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/no-useless-computed-key",
},
schema: [
{
type: "object",
properties: {
enforceForClassMembers: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
unnecessarilyComputedProperty:
"Unnecessarily computed property [{{property}}] found.",
},
},
create(context) {
const sourceCode = context.sourceCode;
const [{ enforceForClassMembers }] = context.options;
/**
* Reports a given node if it violated this rule.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function check(node) {
if (hasUselessComputedKey(node)) {
const { key } = node;
context.report({
node,
messageId: "unnecessarilyComputedProperty",
data: { property: sourceCode.getText(key) },
fix(fixer) {
const leftSquareBracket = sourceCode.getTokenBefore(
key,
astUtils.isOpeningBracketToken,
);
const rightSquareBracket = sourceCode.getTokenAfter(
key,
astUtils.isClosingBracketToken,
);
// If there are comments between the brackets and the property name, don't do a fix.
if (
sourceCode.commentsExistBetween(
leftSquareBracket,
rightSquareBracket,
)
) {
return null;
}
const tokenBeforeLeftBracket =
sourceCode.getTokenBefore(leftSquareBracket);
// Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
const needsSpaceBeforeKey =
tokenBeforeLeftBracket.range[1] ===
leftSquareBracket.range[0] &&
!astUtils.canTokensBeAdjacent(
tokenBeforeLeftBracket,
sourceCode.getFirstToken(key),
);
const replacementKey =
(needsSpaceBeforeKey ? " " : "") + key.raw;
return fixer.replaceTextRange(
[
leftSquareBracket.range[0],
rightSquareBracket.range[1],
],
replacementKey,
);
},
});
}
}
/**
* A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`.
* @returns {void}
* @private
*/
function noop() {}
return {
Property: check,
MethodDefinition: enforceForClassMembers ? check : noop,
PropertyDefinition: enforceForClassMembers ? check : noop,
};
},
};

View File

@@ -0,0 +1,8 @@
global.process = { __proto__: process, pid: 123456 }
Date.now = function () { return 1459875739796 }
require('node:os').hostname = function () { return 'abcdefghijklmnopqr' }
const pino = require(require.resolve('./../../'))
const logger = pino()
logger.info('hello')
logger.info('world')
process.exit(0)

View File

@@ -0,0 +1,48 @@
import * as core from "../core/index.js";
import { $ZodError } from "../core/index.js";
import * as util from "../core/util.js";
const initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
Object.defineProperties(inst, {
format: {
value: (mapper) => core.formatError(inst, mapper),
// enumerable: false,
},
flatten: {
value: (mapper) => core.flattenError(inst, mapper),
// enumerable: false,
},
addIssue: {
value: (issue) => {
inst.issues.push(issue);
inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);
},
// enumerable: false,
},
addIssues: {
value: (issues) => {
inst.issues.push(...issues);
inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);
},
// enumerable: false,
},
isEmpty: {
get() {
return inst.issues.length === 0;
},
// enumerable: false,
},
});
// Object.defineProperty(inst, "isEmpty", {
// get() {
// return inst.issues.length === 0;
// },
// });
};
export const ZodError = /*@__PURE__*/ core.$constructor("ZodError", initializer);
export const ZodRealError = /*@__PURE__*/ core.$constructor("ZodError", initializer, {
Parent: Error,
});
// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
// export type ErrorMapCtx = core.$ZodErrorMapCtx;

View File

@@ -0,0 +1,198 @@
import { expect, expectTypeOf, test } from "vitest";
import type { util } from "zod/v4/core";
import * as z from "zod/v4";
test("object intersection", () => {
const A = z.object({ a: z.string() });
const B = z.object({ b: z.string() });
const C = z.intersection(A, B); // BaseC.merge(HasID);
type C = z.infer<typeof C>;
expectTypeOf<C>().toEqualTypeOf<{ a: string } & { b: string }>();
const data = { a: "foo", b: "foo" };
expect(C.parse(data)).toEqual(data);
expect(() => C.parse({ a: "foo" })).toThrow();
});
test("object intersection: loose", () => {
const A = z.looseObject({ a: z.string() });
const B = z.object({ b: z.string() });
const C = z.intersection(A, B); // BaseC.merge(HasID);
type C = z.infer<typeof C>;
expectTypeOf<C>().toEqualTypeOf<{ a: string; [x: string]: unknown } & { b: string }>();
const data = { a: "foo", b: "foo", c: "extra" };
expect(C.parse(data)).toEqual(data);
expect(() => C.parse({ a: "foo" })).toThrow();
});
test("object intersection: strict + strip", () => {
const A = z.strictObject({ a: z.string() });
const B = z.object({ b: z.string() });
const C = z.intersection(A, B);
type C = z.infer<typeof C>;
expectTypeOf<C>().toEqualTypeOf<{ a: string } & { b: string }>();
// Keys recognized by either side should work
expect(C.parse({ a: "foo", b: "bar" })).toEqual({ a: "foo", b: "bar" });
// Extra keys are stripped (follows strip behavior from B)
expect(C.parse({ a: "foo", b: "bar", c: "extra" })).toEqual({ a: "foo", b: "bar" });
});
test("object intersection: strict + strict", () => {
const A = z.strictObject({ a: z.string() });
const B = z.strictObject({ b: z.string() });
const C = z.intersection(A, B);
// Keys recognized by either side should work
expect(C.parse({ a: "foo", b: "bar" })).toEqual({ a: "foo", b: "bar" });
// Keys unrecognized by BOTH sides should error
const result = C.safeParse({ a: "foo", b: "bar", c: "extra" });
expect(result.error?.issues).toMatchInlineSnapshot(`
[
{
"code": "unrecognized_keys",
"keys": [
"c",
],
"message": "Unrecognized key: "c"",
"path": [],
},
]
`);
});
test("deep intersection", () => {
const Animal = z.object({
properties: z.object({
is_animal: z.boolean(),
}),
});
const Cat = z.intersection(
z.object({
properties: z.object({
jumped: z.boolean(),
}),
}),
Animal
);
type Cat = util.Flatten<z.infer<typeof Cat>>;
expectTypeOf<Cat>().toEqualTypeOf<{ properties: { is_animal: boolean } & { jumped: boolean } }>();
const a = Cat.safeParse({ properties: { is_animal: true, jumped: true } });
expect(a.data!.properties).toEqual({ is_animal: true, jumped: true });
});
test("deep intersection of arrays", async () => {
const Author = z.object({
posts: z.array(
z.object({
post_id: z.number(),
})
),
});
const Registry = z.intersection(
Author,
z.object({
posts: z.array(
z.object({
title: z.string(),
})
),
})
);
const posts = [
{ post_id: 1, title: "Novels" },
{ post_id: 2, title: "Fairy tales" },
];
const cat = Registry.parse({ posts });
expect(cat.posts).toEqual(posts);
const asyncCat = await Registry.parseAsync({ posts });
expect(asyncCat.posts).toEqual(posts);
});
test("invalid intersection types", async () => {
const numberIntersection = z.intersection(
z.number(),
z.number().transform((x) => x + 1)
);
expect(() => {
numberIntersection.parse(1234);
}).toThrowErrorMatchingInlineSnapshot(`[Error: Unmergable intersection. Error path: []]`);
});
test("invalid array merge (incompatible lengths)", async () => {
const stringArrInt = z.intersection(
z.string().array(),
z
.string()
.array()
.transform((val) => [...val, "asdf"])
);
expect(() => stringArrInt.safeParse(["asdf", "qwer"])).toThrowErrorMatchingInlineSnapshot(
`[Error: Unmergable intersection. Error path: []]`
);
});
test("invalid array merge (incompatible elements)", async () => {
const stringArrInt = z.intersection(
z.string().array(),
z
.string()
.array()
.transform((val) => [...val.slice(0, -1), "asdf"])
);
expect(() => stringArrInt.safeParse(["asdf", "qwer"])).toThrowErrorMatchingInlineSnapshot(
`[Error: Unmergable intersection. Error path: [1]]`
);
});
test("invalid object merge", async () => {
const Cat = z.object({
phrase: z.string().transform((val) => `${val} Meow`),
});
const Dog = z.object({
phrase: z.string().transform((val) => `${val} Woof`),
});
const CatDog = z.intersection(Cat, Dog);
expect(() => CatDog.parse({ phrase: "Hello, my name is CatDog." })).toThrowErrorMatchingInlineSnapshot(
`[Error: Unmergable intersection. Error path: ["phrase"]]`
);
});
test("invalid deep merge of object and array combination", async () => {
const University = z.object({
students: z.array(
z.object({
name: z.string().transform((val) => `Student name: ${val}`),
})
),
});
const Registry = z.intersection(
University,
z.object({
students: z.array(
z.object({
name: z.string(),
surname: z.string(),
})
),
})
);
const students = [{ name: "John", surname: "Doe" }];
expect(() => Registry.parse({ students })).toThrowErrorMatchingInlineSnapshot(
`[Error: Unmergable intersection. Error path: ["students",0,"name"]]`
);
});

View File

@@ -0,0 +1,33 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
interface ArrayConstructor {
/**
* Creates an array from an async iterator or iterable object.
* @param iterableOrArrayLike An async iterator or array-like object to convert to an array.
*/
fromAsync<T>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T | PromiseLike<T>> | ArrayLike<T | PromiseLike<T>>): Promise<T[]>;
/**
* Creates an array from an async iterator or iterable object.
*
* @param iterableOrArrayLike An async iterator or array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of itarableOrArrayLike.
* Each return value is awaited before being added to result array.
* @param thisArg Value of 'this' used when executing mapfn.
*/
fromAsync<T, U>(iterableOrArrayLike: AsyncIterable<T> | Iterable<T> | ArrayLike<T>, mapFn: (value: Awaited<T>, index: number) => U, thisArg?: any): Promise<Awaited<U>[]>;
}

View File

@@ -0,0 +1,85 @@
# Split2(matcher, mapper, options)
![ci](https://github.com/mcollina/split2/workflows/ci/badge.svg)
Break up a stream and reassemble it so that each line is a chunk.
`split2` is inspired by [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) module,
and it is totally API compatible with it.
However, it is based on Node.js core [`Transform`](https://nodejs.org/api/stream.html#stream_new_stream_transform_options).
`matcher` may be a `String`, or a `RegExp`. Example, read every line in a file ...
``` js
fs.createReadStream(file)
.pipe(split2())
.on('data', function (line) {
//each chunk now is a separate line!
})
```
`split` takes the same arguments as `string.split` except it defaults to '/\r?\n/', and the optional `limit` paremeter is ignored.
[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)
`split` takes an optional options object on it's third argument, which
is directly passed as a
[Transform](https://nodejs.org/api/stream.html#stream_new_stream_transform_options)
option.
Additionally, the `.maxLength` and `.skipOverflow` options are implemented, which set limits on the internal
buffer size and the stream's behavior when the limit is exceeded. There is no limit unless `maxLength` is set. When
the internal buffer size exceeds `maxLength`, the stream emits an error by default. You may also set `skipOverflow` to
true to suppress the error and instead skip past any lines that cause the internal buffer to exceed `maxLength`.
Calling `.destroy` will make the stream emit `close`. Use this to perform cleanup logic
``` js
var splitFile = function(filename) {
var file = fs.createReadStream(filename)
return file
.pipe(split2())
.on('close', function() {
// destroy the file stream in case the split stream was destroyed
file.destroy()
})
}
var stream = splitFile('my-file.txt')
stream.destroy() // will destroy the input file stream
```
# NDJ - Newline Delimited Json
`split2` accepts a function which transforms each line.
``` js
fs.createReadStream(file)
.pipe(split2(JSON.parse))
.on('data', function (obj) {
//each chunk now is a js object
})
.on("error", function(error) {
//handling parsing errors
})
```
However, in [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) the mapper
is wrapped in a try-catch, while here it is not: if your parsing logic can throw, wrap it yourself. Otherwise, you can also use the stream error handling when mapper function throw.
# License
Copyright (c) 2014-2021, Matteo Collina <hello@matteocollina.com>
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.

View File

@@ -0,0 +1,10 @@
"use strict";
module.exports = function (it) {
const { pattern, globDisabled } = it;
return `
No files matching the pattern "${pattern}"${globDisabled ? " (with disabling globs)" : ""} were found.
Please check for typing mistakes in the pattern.
`.trimStart();
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"internalSymbolName.enum.js","sourceRoot":"","sources":["../../src/enums/internalSymbolName.enum.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAE5F,MAAM,CAAN,IAAY,kBAqBX;AArBD,WAAY,kBAAkB;IAC1B,qCAAe,CAAA;IACf,mDAA6B,CAAA;IAC7B,mCAAa,CAAA;IACb,uCAAiB,CAAA;IACjB,6CAAuB,CAAA;IACvB,yCAAmB,CAAA;IACnB,2CAAqB,CAAA;IACrB,qCAAe,CAAA;IACf,yCAAmB,CAAA;IACnB,uDAAiC,CAAA;IACjC,uCAAiB,CAAA;IACjB,6CAAuB,CAAA;IACvB,6CAAuB,CAAA;IACvB,4DAAsC,CAAA;IACtC,2EAAqD,CAAA;IACrD,6DAAuC,CAAA;IACvC,8CAAwB,CAAA;IACxB,yCAAmB,CAAA;IACnB,mCAAa,CAAA;IACb,sDAAgC,CAAA;AACpC,CAAC,EArBW,kBAAkB,KAAlB,kBAAkB,QAqB7B"}

View File

@@ -0,0 +1,9 @@
import type { TSESLint } from '@typescript-eslint/utils';
export declare function getFixOrSuggest<MessageId extends string>({ fixOrSuggest, suggestion, }: {
fixOrSuggest: 'fix' | 'none' | 'suggest';
suggestion: TSESLint.SuggestionReportDescriptor<MessageId>;
}): {
fix: TSESLint.ReportFixFunction;
} | {
suggest: TSESLint.SuggestionReportDescriptor<MessageId>[];
} | undefined;

View File

@@ -0,0 +1,144 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Reflect {
/**
* Calls the function with the specified object as the this value
* and the elements of specified array as the arguments.
* @param target The function to call.
* @param thisArgument The object to be used as the this object.
* @param argumentsList An array of argument values to be passed to the function.
*/
function apply<T, A extends readonly any[], R>(
target: (this: T, ...args: A) => R,
thisArgument: T,
argumentsList: Readonly<A>,
): R;
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
/**
* Constructs the target with the elements of specified array as the arguments
* and the specified constructor as the `new.target` value.
* @param target The constructor to invoke.
* @param argumentsList An array of argument values to be passed to the constructor.
* @param newTarget The constructor to be used as the `new.target` object.
*/
function construct<A extends readonly any[], R>(
target: new (...args: A) => R,
argumentsList: Readonly<A>,
newTarget?: new (...args: any) => any,
): R;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: Function): any;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param target Object on which to add or modify the property. This can be a native JavaScript object
* (that is, a user-defined object or a built in object) or a DOM object.
* @param propertyKey The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor property.
*/
function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor & ThisType<any>): boolean;
/**
* Removes a property from an object, equivalent to `delete target[propertyKey]`,
* except it won't throw if `target[propertyKey]` is non-configurable.
* @param target Object from which to remove the own property.
* @param propertyKey The property name.
*/
function deleteProperty(target: object, propertyKey: PropertyKey): boolean;
/**
* Gets the property of target, equivalent to `target[propertyKey]` when `receiver === target`.
* @param target Object that contains the property on itself or in its prototype chain.
* @param propertyKey The property name.
* @param receiver The reference to use as the `this` value in the getter function,
* if `target[propertyKey]` is an accessor property.
*/
function get<T extends object, P extends PropertyKey>(
target: T,
propertyKey: P,
receiver?: unknown,
): P extends keyof T ? T[P] : any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.
* @param target Object that contains the property.
* @param propertyKey The property name.
*/
function getOwnPropertyDescriptor<T extends object, P extends PropertyKey>(
target: T,
propertyKey: P,
): TypedPropertyDescriptor<P extends keyof T ? T[P] : any> | undefined;
/**
* Returns the prototype of an object.
* @param target The object that references the prototype.
*/
function getPrototypeOf(target: object): object | null;
/**
* Equivalent to `propertyKey in target`.
* @param target Object that contains the property on itself or in its prototype chain.
* @param propertyKey Name of the property.
*/
function has(target: object, propertyKey: PropertyKey): boolean;
/**
* Returns a value that indicates whether new properties can be added to an object.
* @param target Object to test.
*/
function isExtensible(target: object): boolean;
/**
* Returns the string and symbol keys of the own properties of an object. The own properties of an object
* are those that are defined directly on that object, and are not inherited from the object's prototype.
* @param target Object that contains the own properties.
*/
function ownKeys(target: object): (string | symbol)[];
/**
* Prevents the addition of new properties to an object.
* @param target Object to make non-extensible.
* @return Whether the object has been made non-extensible.
*/
function preventExtensions(target: object): boolean;
/**
* Sets the property of target, equivalent to `target[propertyKey] = value` when `receiver === target`.
* @param target Object that contains the property on itself or in its prototype chain.
* @param propertyKey Name of the property.
* @param receiver The reference to use as the `this` value in the setter function,
* if `target[propertyKey]` is an accessor property.
*/
function set<T extends object, P extends PropertyKey>(
target: T,
propertyKey: P,
value: P extends keyof T ? T[P] : any,
receiver?: any,
): boolean;
function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null.
* @param target The object to change its prototype.
* @param proto The value of the new prototype or null.
* @return Whether setting the prototype was successful.
*/
function setPrototypeOf(target: object, proto: object | null): boolean;
}

View File

@@ -0,0 +1,89 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PredefinedFormatToCheckFunction = void 0;
const enums_1 = require("./enums");
/*
These format functions are taken from `tslint-consistent-codestyle/naming-convention`:
https://github.com/ajafff/tslint-consistent-codestyle/blob/ab156cc8881bcc401236d999f4ce034b59039e81/rules/namingConventionRule.ts#L603-L645
The license for the code can be viewed here:
https://github.com/ajafff/tslint-consistent-codestyle/blob/ab156cc8881bcc401236d999f4ce034b59039e81/LICENSE
*/
/*
Why not regex here? Because it's actually really, really difficult to create a regex to handle
all of the unicode cases, and we have many non-english users that use non-english characters.
https://gist.github.com/mathiasbynens/6334847
*/
function isPascalCase(name) {
return (name.length === 0 ||
(name[0] === name[0].toUpperCase() && !name.includes('_')));
}
function isStrictPascalCase(name) {
return (name.length === 0 ||
(name[0] === name[0].toUpperCase() && hasStrictCamelHumps(name, true)));
}
function isCamelCase(name) {
return (name.length === 0 ||
(name[0] === name[0].toLowerCase() && !name.includes('_')));
}
function isStrictCamelCase(name) {
return (name.length === 0 ||
(name[0] === name[0].toLowerCase() && hasStrictCamelHumps(name, false)));
}
function hasStrictCamelHumps(name, isUpper) {
function isUppercaseChar(char) {
return char === char.toUpperCase() && char !== char.toLowerCase();
}
if (name.startsWith('_')) {
return false;
}
for (let i = 1; i < name.length; ++i) {
if (name[i] === '_') {
return false;
}
if (isUpper === isUppercaseChar(name[i])) {
if (isUpper) {
return false;
}
}
else {
isUpper = !isUpper;
}
}
return true;
}
function isSnakeCase(name) {
return (name.length === 0 ||
(name === name.toLowerCase() && validateUnderscores(name)));
}
function isUpperCase(name) {
return (name.length === 0 ||
(name === name.toUpperCase() && validateUnderscores(name)));
}
/** Check for leading trailing and adjacent underscores */
function validateUnderscores(name) {
if (name.startsWith('_')) {
return false;
}
let wasUnderscore = false;
for (let i = 1; i < name.length; ++i) {
if (name[i] === '_') {
if (wasUnderscore) {
return false;
}
wasUnderscore = true;
}
else {
wasUnderscore = false;
}
}
return !wasUnderscore;
}
exports.PredefinedFormatToCheckFunction = {
[enums_1.PredefinedFormats.camelCase]: isCamelCase,
[enums_1.PredefinedFormats.PascalCase]: isPascalCase,
[enums_1.PredefinedFormats.snake_case]: isSnakeCase,
[enums_1.PredefinedFormats.strictCamelCase]: isStrictCamelCase,
[enums_1.PredefinedFormats.StrictPascalCase]: isStrictPascalCase,
[enums_1.PredefinedFormats.UPPER_CASE]: isUpperCase,
};

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sha512_256 = exports.SHA512_256 = exports.sha512_224 = exports.SHA512_224 = exports.sha384 = exports.SHA384 = exports.sha512 = exports.SHA512 = void 0;
/**
* SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.
*
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
* [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).
* @module
* @deprecated
*/
const sha2_ts_1 = require("./sha2.js");
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.SHA512 = sha2_ts_1.SHA512;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.sha512 = sha2_ts_1.sha512;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.SHA384 = sha2_ts_1.SHA384;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.sha384 = sha2_ts_1.sha384;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.SHA512_224 = sha2_ts_1.SHA512_224;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.sha512_224 = sha2_ts_1.sha512_224;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.SHA512_256 = sha2_ts_1.SHA512_256;
/** @deprecated Use import from `noble/hashes/sha2` module */
exports.sha512_256 = sha2_ts_1.sha512_256;
//# sourceMappingURL=sha512.js.map

View File

@@ -0,0 +1,147 @@
/**
* @fileoverview Rule to enforce declarations in program or function body root.
* @author Brandon Mills
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const validParent = new Set([
"Program",
"StaticBlock",
"ExportNamedDeclaration",
"ExportDefaultDeclaration",
]);
const validBlockStatementParent = new Set([
"FunctionDeclaration",
"FunctionExpression",
"ArrowFunctionExpression",
]);
/**
* Finds the nearest enclosing context where this rule allows declarations and returns its description.
* @param {ASTNode} node Node to search from.
* @returns {string} Description. One of "program", "function body", "class static block body".
*/
function getAllowedBodyDescription(node) {
let { parent } = node;
while (parent) {
if (parent.type === "StaticBlock") {
return "class static block body";
}
if (astUtils.isFunction(parent)) {
return "function body";
}
({ parent } = parent);
}
return "program";
}
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: ["functions", { blockScopedFunctions: "allow" }],
docs: {
description:
"Disallow variable or `function` declarations in nested blocks",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-inner-declarations",
},
schema: [
{
enum: ["functions", "both"],
},
{
type: "object",
properties: {
blockScopedFunctions: {
enum: ["allow", "disallow"],
},
},
additionalProperties: false,
},
],
messages: {
moveDeclToRoot: "Move {{type}} declaration to {{body}} root.",
},
},
create(context) {
const both = context.options[0] === "both";
const { blockScopedFunctions } = context.options[1];
const sourceCode = context.sourceCode;
const ecmaVersion = context.languageOptions.ecmaVersion;
/**
* Ensure that a given node is at a program or function body's root.
* @param {ASTNode} node Declaration node to check.
* @returns {void}
*/
function check(node) {
const parent = node.parent;
if (
parent.type === "BlockStatement" &&
validBlockStatementParent.has(parent.parent.type)
) {
return;
}
if (validParent.has(parent.type)) {
return;
}
context.report({
node,
messageId: "moveDeclToRoot",
data: {
type:
node.type === "FunctionDeclaration"
? "function"
: "variable",
body: getAllowedBodyDescription(node),
},
});
}
return {
FunctionDeclaration(node) {
const isInStrictCode = sourceCode.getScope(node).upper.isStrict;
if (
blockScopedFunctions === "allow" &&
ecmaVersion >= 2015 &&
isInStrictCode
) {
return;
}
check(node);
},
VariableDeclaration(node) {
if (both && node.kind === "var") {
check(node);
}
},
};
},
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"newLineKind.d.ts","sourceRoot":"","sources":["../../src/enums/newLineKind.ts"],"names":[],"mappings":"AACA,eAAO,IAAI,WAAW,EAAE,GAAG,CAAC"}

View File

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

View File

@@ -0,0 +1,356 @@
import { n as __toESM, t as require_binding } from "./shared/binding-Zhafd14U.mjs";
import { n as BuiltinPlugin, t as normalizedStringOrRegex } from "./shared/normalize-string-or-regex-BxRYnPRv.mjs";
import { u as transformToRollupOutput } from "./shared/bindingify-input-options-C-Zsy1EG.mjs";
import { l as PluginDriver, s as validateOption, t as createBundlerOptions } from "./shared/create-bundler-option-wRiQzEJ3.mjs";
import { i as unwrapBindingResult, r as normalizeBindingResult } from "./shared/error-CVc7IgvG.mjs";
import { n as parseSync$1, t as parse$1 } from "./shared/parse-DnWvq9XZ.mjs";
import { a as viteDynamicImportVarsPlugin, c as viteLoadFallbackPlugin, d as viteReporterPlugin, f as viteResolvePlugin, i as viteBuildImportAnalysisPlugin, l as viteModulePreloadPolyfillPlugin, n as isolatedDeclarationPlugin, o as viteImportGlobPlugin, p as viteWebWorkerPostPlugin, r as oxcRuntimePlugin, s as viteJsonPlugin, u as viteReactRefreshWrapperPlugin } from "./shared/constructors-u6EEiG8n.mjs";
import { a as minify$1, i as transformSync$1, n as resolveTsconfig, o as minifySync$1, r as transform$1, t as TsconfigCache$1 } from "./shared/resolve-tsconfig-SPewz4V3.mjs";
import { pathToFileURL } from "node:url";
//#region src/api/dev/dev-engine.ts
var import_binding = /* @__PURE__ */ __toESM(require_binding(), 1);
var DevEngine = class DevEngine {
#inner;
#cachedBuildFinishPromise = null;
#asyncRuntimeReleased = false;
static async create(inputOptions, outputOptions = {}, devOptions = {}) {
inputOptions = await PluginDriver.callOptionsHook(inputOptions);
const options = await createBundlerOptions(inputOptions, outputOptions, false);
const userOnHmrUpdates = devOptions.onHmrUpdates;
const bindingOnHmrUpdates = userOnHmrUpdates ? function(rawResult) {
const result = normalizeBindingResult(rawResult);
if (result instanceof Error) {
userOnHmrUpdates(result);
return;
}
const [updates, changedFiles] = result;
userOnHmrUpdates({
updates,
changedFiles
});
} : void 0;
const userOnOutput = devOptions.onOutput;
const bindingOnOutput = userOnOutput ? function(rawResult) {
const result = normalizeBindingResult(rawResult);
if (result instanceof Error) {
userOnOutput(result);
return;
}
userOnOutput(transformToRollupOutput(result));
} : void 0;
const userOnAdditionalAssets = devOptions.onAdditionalAssets;
const bindingDevOptions = {
onHmrUpdates: bindingOnHmrUpdates,
onOutput: bindingOnOutput,
onAdditionalAssets: userOnAdditionalAssets ? function(output) {
userOnAdditionalAssets(transformToRollupOutput(output));
} : void 0,
rebuildStrategy: devOptions.rebuildStrategy ? devOptions.rebuildStrategy === "always" ? import_binding.BindingRebuildStrategy.Always : import_binding.BindingRebuildStrategy.Never : void 0,
watch: devOptions.watch && {
enabled: devOptions.watch.enabled,
skipWrite: devOptions.watch.skipWrite,
usePolling: devOptions.watch.usePolling,
pollInterval: devOptions.watch.pollInterval,
useDebounce: devOptions.watch.useDebounce,
debounceDuration: devOptions.watch.debounceDuration,
compareContentsForPolling: devOptions.watch.compareContentsForPolling,
debounceTickRate: devOptions.watch.debounceTickRate,
include: normalizedStringOrRegex(devOptions.watch.include),
exclude: normalizedStringOrRegex(devOptions.watch.exclude)
}
};
const inner = new import_binding.BindingDevEngine(options.bundlerOptions, bindingDevOptions);
(0, import_binding.startAsyncRuntime)();
return new DevEngine(inner);
}
constructor(inner) {
this.#inner = inner;
}
async run() {
await this.#inner.run();
}
async ensureCurrentBuildFinish() {
if (this.#cachedBuildFinishPromise) return this.#cachedBuildFinishPromise;
const promise = this.#inner.ensureCurrentBuildFinish().then(() => {
this.#cachedBuildFinishPromise = null;
});
this.#cachedBuildFinishPromise = promise;
return promise;
}
async getBundleState() {
return this.#inner.getBundleState();
}
async ensureLatestBuildOutput() {
unwrapBindingResult(await this.#inner.ensureLatestBuildOutput());
}
triggerFullBuild() {
this.#inner.triggerFullBuild();
}
/**
* Client-connect signal (the clientId hello): creates the per-client session
* with an empty ship map. Reconnects arrive as fresh clientIds.
*/
async registerClient(clientId) {
await this.#inner.registerClient(clientId);
}
/**
* Delivery notification from the serving middleware: the response for
* `filename` completed, so record its modules as shipped to that client.
*/
async notifyPayloadDelivered(filename) {
await this.#inner.notifyPayloadDelivered(filename);
}
async removeClient(clientId) {
await this.#inner.removeClient(clientId);
}
async close() {
const shouldRelease = !this.#asyncRuntimeReleased;
this.#asyncRuntimeReleased = true;
try {
await this.#inner.close();
} finally {
if (shouldRelease) (0, import_binding.shutdownAsyncRuntime)();
}
}
/**
* Compile a lazy entry module and return HMR-style patch code.
*
* This is called when a dynamically imported module is first requested at runtime.
* The module was previously stubbed with a proxy, and now we need to compile the
* actual module and its dependencies.
*
* @param moduleId - The absolute file path of the module to compile
* @param clientId - The client ID requesting this compilation
* @returns The compiled chunk: its code plus the filename whose delivery the
* serving middleware reports via {@link notifyPayloadDelivered}
*/
async compileEntry(moduleId, clientId) {
return this.#inner.compileEntry(moduleId, clientId);
}
};
//#endregion
//#region src/api/dev/index.ts
const dev = (...args) => DevEngine.create(...args);
//#endregion
//#region src/types/external-memory-handle.ts
const symbolForExternalMemoryHandle = "__rolldown_external_memory_handle__";
/**
* Frees the external memory held by the given handle.
*
* This is useful when you want to manually release memory held by Rust objects
* (like `OutputChunk` or `OutputAsset`) before they are garbage collected.
*
* @param handle - The object with external memory to free
* @param keepDataAlive - If true, evaluates all lazy fields before freeing memory (default: false).
* This will take time to copy data from Rust to JavaScript, but prevents errors
* when accessing properties after the memory is freed.
* @returns Status object with `freed` boolean and optional `reason` string.
* - `{ freed: true }` if memory was successfully freed
* - `{ freed: false, reason: "..." }` if memory couldn't be freed (e.g., already freed or other references exist)
*
* @example
* ```typescript
* import { freeExternalMemory } from 'rolldown/experimental';
*
* const output = await bundle.generate();
* const chunk = output.output[0];
*
* // Use the chunk...
*
* // Manually free the memory (fast, but accessing properties after will throw)
* const status = freeExternalMemory(chunk); // { freed: true }
* const statusAgain = freeExternalMemory(chunk); // { freed: false, reason: "Memory has already been freed" }
*
* // Keep data alive before freeing (slower, but data remains accessible)
* freeExternalMemory(chunk, true); // Evaluates all lazy fields first
* console.log(chunk.code); // OK - data was copied to JavaScript before freeing
*
* // Without keepDataAlive, accessing chunk properties after freeing will throw an error
* ```
*/
function freeExternalMemory(handle, keepDataAlive = false) {
return handle[symbolForExternalMemoryHandle](keepDataAlive);
}
//#endregion
//#region src/api/experimental.ts
/**
* This is an experimental API. Its behavior may change in the future.
*
* - Calling this API will only execute the `scan/build` stage of rolldown.
* - `scan` will clean up all resources automatically, but if you want to ensure timely cleanup, you need to wait for the returned promise to resolve.
*
* @example To ensure cleanup of resources, use the returned promise to wait for the scan to complete.
* ```ts
* import { scan } from 'rolldown/api/experimental';
*
* const cleanupPromise = await scan(...);
* await cleanupPromise;
* // Now all resources have been cleaned up.
* ```
*/
const scan = async (rawInputOptions, rawOutputOptions = {}) => {
validateOption("input", rawInputOptions);
validateOption("output", rawOutputOptions);
const inputOptions = await PluginDriver.callOptionsHook(rawInputOptions);
const ret = await createBundlerOptions(inputOptions, rawOutputOptions, false);
const bundler = new import_binding.BindingBundler();
(0, import_binding.startAsyncRuntime)();
let cleanedUp = false;
async function cleanup() {
if (cleanedUp) return;
cleanedUp = true;
try {
await bundler.close();
await ret.stopWorkers?.();
} finally {
(0, import_binding.shutdownAsyncRuntime)();
}
}
let cleanupPromise = Promise.resolve();
try {
const result = await bundler.scan(ret.bundlerOptions);
unwrapBindingResult(result);
} catch (err) {
await cleanup();
throw err;
} finally {
cleanupPromise = cleanup();
}
return cleanupPromise;
};
//#endregion
//#region src/plugin/parallel-plugin.ts
function defineParallelPlugin(pluginPath) {
return (options) => {
return { _parallel: {
fileUrl: pathToFileURL(pluginPath).href,
options
} };
};
}
//#endregion
//#region src/builtin-plugin/alias-plugin.ts
function viteAliasPlugin(config) {
return new BuiltinPlugin("builtin:vite-alias", config);
}
//#endregion
//#region src/builtin-plugin/bundle-analyzer-plugin.ts
/**
* A plugin that analyzes bundle composition and generates detailed reports.
*
* The plugin outputs a file containing detailed information about:
* - All chunks and their relationships
* - Modules bundled in each chunk
* - Import dependencies between chunks
* - Reachable modules from each entry point
*
* @example
* ```js
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
*
* export default {
* plugins: [
* bundleAnalyzerPlugin()
* ]
* }
* ```
*
* @example
* **Custom filename**
* ```js
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
*
* export default {
* plugins: [
* bundleAnalyzerPlugin({
* fileName: 'bundle-analysis.json'
* })
* ]
* }
* ```
*
* @example
* **LLM-friendly markdown output**
* ```js
* import { bundleAnalyzerPlugin } from 'rolldown/experimental';
*
* export default {
* plugins: [
* bundleAnalyzerPlugin({
* format: 'md'
* })
* ]
* }
* ```
*/
function bundleAnalyzerPlugin(config) {
return new BuiltinPlugin("builtin:bundle-analyzer", config);
}
//#endregion
//#region src/builtin-plugin/transform-plugin.ts
function viteTransformPlugin(config) {
return new BuiltinPlugin("builtin:vite-transform", {
...config,
include: normalizedStringOrRegex(config.include),
exclude: normalizedStringOrRegex(config.exclude),
jsxRefreshInclude: normalizedStringOrRegex(config.jsxRefreshInclude),
jsxRefreshExclude: normalizedStringOrRegex(config.jsxRefreshExclude),
yarnPnp: typeof process === "object" && !!process.versions?.pnp
});
}
//#endregion
//#region src/builtin-plugin/vite-manifest-plugin.ts
function viteManifestPlugin(config) {
return new BuiltinPlugin("builtin:vite-manifest", config);
}
//#endregion
//#region src/experimental-index.ts
/**
* In-memory file system for browser builds.
*
* This is a re-export of the {@link https://github.com/streamich/memfs | memfs} package used by the WASI runtime.
* It allows you to read and write files to a virtual filesystem when using rolldown in browser environments.
*
* - `fs`: A Node.js-compatible filesystem API (`IFs` from memfs)
* - `volume`: The underlying `Volume` instance that stores the filesystem state
*
* Returns `undefined` in Node.js builds (only available in browser builds via `@rolldown/browser`).
*
* @example
* ```typescript
* import { memfs } from 'rolldown/experimental';
*
* // Write files to virtual filesystem before bundling
* memfs?.volume.fromJSON({
* '/src/index.js': 'export const foo = 42;',
* '/package.json': '{"name": "my-app"}'
* });
*
* // Read files from the virtual filesystem
* const content = memfs?.fs.readFileSync('/src/index.js', 'utf8');
* ```
*
* @see {@link https://github.com/streamich/memfs} for more information on the memfs API.
*/
const memfs = void 0;
/** @deprecated Use from `rolldown/utils` instead. */
const parse = parse$1;
/** @deprecated Use from `rolldown/utils` instead. */
const parseSync = parseSync$1;
/** @deprecated Use from `rolldown/utils` instead. */
const minify = minify$1;
/** @deprecated Use from `rolldown/utils` instead. */
const minifySync = minifySync$1;
/** @deprecated Use from `rolldown/utils` instead. */
const transform = transform$1;
/** @deprecated Use from `rolldown/utils` instead. */
const transformSync = transformSync$1;
/** @deprecated Use from `rolldown/utils` instead. */
const TsconfigCache = TsconfigCache$1;
//#endregion
var BindingRebuildStrategy = import_binding.BindingRebuildStrategy;
var ResolverFactory = import_binding.ResolverFactory;
var isolatedDeclaration = import_binding.isolatedDeclaration;
var isolatedDeclarationSync = import_binding.isolatedDeclarationSync;
var moduleRunnerTransform = import_binding.moduleRunnerTransform;
export { BindingRebuildStrategy, DevEngine, ResolverFactory, TsconfigCache, bundleAnalyzerPlugin, defineParallelPlugin, dev, viteDynamicImportVarsPlugin as dynamicImportVarsPlugin, viteDynamicImportVarsPlugin, freeExternalMemory, viteImportGlobPlugin as importGlobPlugin, viteImportGlobPlugin, isolatedDeclaration, isolatedDeclarationPlugin, isolatedDeclarationSync, memfs, minify, minifySync, moduleRunnerTransform, oxcRuntimePlugin, parse, parseSync, resolveTsconfig, scan, transform, transformSync, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReactRefreshWrapperPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWebWorkerPostPlugin };

View File

@@ -0,0 +1,46 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
test("parse async test", async () => {
const schema1 = z.string().refine(async (_val) => false);
expect(() => schema1.parse("asdf")).toThrow();
const schema2 = z.string().refine((_val) => Promise.resolve(true));
return await expect(() => schema2.parse("asdf")).toThrow();
});
test("parseAsync async test", async () => {
const schema1 = z.string().refine(async (_val) => true);
await schema1.parseAsync("asdf");
const schema2 = z.string().refine(async (_val) => false);
return await expect(schema2.parseAsync("asdf")).rejects.toBeDefined();
// expect(async () => await schema2.parseAsync('asdf')).toThrow();
});
test("parseAsync async test", 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("parseAsync async with value", async () => {
const schema1 = z.string().refine(async (val) => {
return val.length > 5;
});
await expect(schema1.parseAsync("asdf")).rejects.toBeDefined();
const v = await schema1.parseAsync("asdf123");
return await expect(v).toEqual("asdf123");
});

View File

@@ -0,0 +1,159 @@
/**
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
* @module
*/
import { HashMD } from './_md.ts';
import { type CHash } from './utils.ts';
export declare class SHA256 extends HashMD<SHA256> {
protected A: number;
protected B: number;
protected C: number;
protected D: number;
protected E: number;
protected F: number;
protected G: number;
protected H: number;
constructor(outputLen?: number);
protected get(): [number, number, number, number, number, number, number, number];
protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
export declare class SHA224 extends SHA256 {
protected A: number;
protected B: number;
protected C: number;
protected D: number;
protected E: number;
protected F: number;
protected G: number;
protected H: number;
constructor();
}
export declare class SHA512 extends HashMD<SHA512> {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor(outputLen?: number);
protected get(): [
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number,
number
];
protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
export declare class SHA384 extends SHA512 {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
export declare class SHA512_224 extends SHA512 {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
export declare class SHA512_256 extends SHA512 {
protected Ah: number;
protected Al: number;
protected Bh: number;
protected Bl: number;
protected Ch: number;
protected Cl: number;
protected Dh: number;
protected Dl: number;
protected Eh: number;
protected El: number;
protected Fh: number;
protected Fl: number;
protected Gh: number;
protected Gl: number;
protected Hh: number;
protected Hl: number;
constructor();
}
/**
* SHA2-256 hash function from RFC 4634.
*
* It is the fastest JS hash, even faster than Blake3.
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
*/
export declare const sha256: CHash;
/** SHA2-224 hash function from RFC 4634 */
export declare const sha224: CHash;
/** SHA2-512 hash function from RFC 4634. */
export declare const sha512: CHash;
/** SHA2-384 hash function from RFC 4634. */
export declare const sha384: CHash;
/**
* SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
* See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
*/
export declare const sha512_256: CHash;
/**
* SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
* See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).
*/
export declare const sha512_224: CHash;
//# sourceMappingURL=sha2.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"modifierFlags.js","sourceRoot":"","sources":["../../src/enums/modifierFlags.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,309 @@
# Web Frameworks
Since HTTP logging is a primary use case, Pino has first-class support for the Node.js
web framework ecosystem.
- [Web Frameworks](#web-frameworks)
- [Pino with Fastify](#pino-with-fastify)
- [Pino with Express](#pino-with-express)
- [Pino with Hapi](#pino-with-hapi)
- [Pino with Restify](#pino-with-restify)
- [Pino with Koa](#pino-with-koa)
- [Pino with Node core `http`](#pino-with-node-core-http)
- [Pino with Nest](#pino-with-nest)
- [Pino with H3](#pino-with-h3)
- [Pino with Hono](#pino-with-hono)
<a id="fastify"></a>
## Pino with Fastify
The Fastify web framework comes bundled with Pino by default, simply set Fastify's
`logger` option to `true` and use `request.log` or `reply.log` for log messages that correspond
to each request:
```js
const fastify = require('fastify')({
logger: true
})
fastify.get('/', async (request, reply) => {
request.log.info('something')
return { hello: 'world' }
})
fastify.listen({ port: 3000 }, (err) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
```
The `logger` option can also be set to an object, which will be passed through directly
as the [`pino` options object](/docs/api.md#options-object).
See the [fastify documentation](https://www.fastify.io/docs/latest/Reference/Logging/) for more information.
<a id="express"></a>
## Pino with Express
```sh
npm install pino-http
```
```js
const app = require('express')()
const pino = require('pino-http')()
app.use(pino)
app.get('/', function (req, res) {
req.log.info('something')
res.send('hello world')
})
app.listen(3000)
```
See the [pino-http README](https://npm.im/pino-http) for more info.
<a id="hapi"></a>
## Pino with Hapi
```sh
npm install hapi-pino
```
```js
'use strict'
const Hapi = require('@hapi/hapi')
const Pino = require('hapi-pino');
async function start () {
// Create a server with a host and port
const server = Hapi.server({
host: 'localhost',
port: 3000
})
// Add the route
server.route({
method: 'GET',
path: '/',
handler: async function (request, h) {
// request.log is HAPI's standard way of logging
request.log(['a', 'b'], 'Request into hello world')
// a pino instance can also be used, which will be faster
request.logger.info('In handler %s', request.path)
return 'hello world'
}
})
await server.register(Pino)
// also as a decorated API
server.logger.info('another way for accessing it')
// and through Hapi standard logging system
server.log(['subsystem'], 'third way for accessing it')
await server.start()
return server
}
start().catch((err) => {
console.log(err)
process.exit(1)
})
```
See the [hapi-pino README](https://npm.im/hapi-pino) for more info.
<a id="restify"></a>
## Pino with Restify
```sh
npm install restify-pino-logger
```
```js
const server = require('restify').createServer({name: 'server'})
const pino = require('restify-pino-logger')()
server.use(pino)
server.get('/', function (req, res) {
req.log.info('something')
res.send('hello world')
})
server.listen(3000)
```
See the [restify-pino-logger README](https://npm.im/restify-pino-logger) for more info.
<a id="koa"></a>
## Pino with Koa
```sh
npm install koa-pino-logger
```
```js
const Koa = require('koa')
const app = new Koa()
const pino = require('koa-pino-logger')()
app.use(pino)
app.use((ctx) => {
ctx.log.info('something else')
ctx.body = 'hello world'
})
app.listen(3000)
```
See the [koa-pino-logger README](https://github.com/pinojs/koa-pino-logger) for more info.
<a id="http"></a>
## Pino with Node core `http`
```sh
npm install pino-http
```
```js
const http = require('http')
const server = http.createServer(handle)
const logger = require('pino-http')()
function handle (req, res) {
logger(req, res)
req.log.info('something else')
res.end('hello world')
}
server.listen(3000)
```
See the [pino-http README](https://npm.im/pino-http) for more info.
<a id="nest"></a>
## Pino with Nest
```sh
npm install nestjs-pino
```
```ts
import { NestFactory } from '@nestjs/core'
import { Controller, Get, Module } from '@nestjs/common'
import { LoggerModule, Logger } from 'nestjs-pino'
@Controller()
export class AppController {
constructor(private readonly logger: Logger) {}
@Get()
getHello() {
this.logger.log('something')
return `Hello world`
}
}
@Module({
controllers: [AppController],
imports: [LoggerModule.forRoot()]
})
class MyModule {}
async function bootstrap() {
const app = await NestFactory.create(MyModule)
await app.listen(3000)
}
bootstrap()
```
See the [nestjs-pino README](https://npm.im/nestjs-pino) for more info.
<a id="h3"></a>
## Pino with H3
```sh
npm install pino-http h3
```
Save as `server.mjs`:
```js
import { createApp, createRouter, eventHandler, fromNodeMiddleware } from "h3";
import pino from 'pino-http'
export const app = createApp();
const router = createRouter();
app.use(router);
app.use(fromNodeMiddleware(pino()))
app.use(eventHandler((event) => {
event.node.req.log.info('something')
return 'hello world'
}))
router.get(
"/",
eventHandler((event) => {
return { path: event.path, message: "Hello World!" };
}),
);
```
Execute `npx --yes listhen -w --open ./server.mjs`.
See the [pino-http README](https://npm.im/pino-http) for more info.
<a id="hono"></a>
## Pino with Hono
```sh
npm install pino pino-http hono
```
```js
import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { requestId } from 'hono/request-id';
import { pinoHttp } from 'pino-http';
const app = new Hono();
app.use(requestId());
app.use(async (c, next) => {
// pass hono's request-id to pino-http
c.env.incoming.id = c.var.requestId;
// map express style middleware to hono
await new Promise((resolve) => pinoHttp()(c.env.incoming, c.env.outgoing, () => resolve()));
c.set('logger', c.env.incoming.log);
await next();
});
app.get('/', (c) => {
c.var.logger.info('something');
return c.text('Hello Node.js!');
});
serve(app);
```
See the [pino-http README](https://npm.im/pino-http) for more info.

View File

@@ -0,0 +1,191 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}
{{
var $rule = this
, $definition = 'definition' + $lvl
, $rDef = $rule.definition
, $closingBraces = '';
var $validate = $rDef.validate;
var $compile, $inline, $macro, $ruleValidate, $validateCode;
}}
{{? $isData && $rDef.$data }}
{{
$validateCode = 'keywordValidate' + $lvl;
var $validateSchema = $rDef.validateSchema;
}}
var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition;
var {{=$validateCode}} = {{=$definition}}.validate;
{{??}}
{{
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
if (!$ruleValidate) return;
$schemaValue = 'validate.schema' + $schemaPath;
$validateCode = $ruleValidate.code;
$compile = $rDef.compile;
$inline = $rDef.inline;
$macro = $rDef.macro;
}}
{{?}}
{{
var $ruleErrs = $validateCode + '.errors'
, $i = 'i' + $lvl
, $ruleErr = 'ruleErr' + $lvl
, $asyncKeyword = $rDef.async;
if ($asyncKeyword && !it.async)
throw new Error('async keyword in sync schema');
}}
{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}}
var {{=$errs}} = errors;
var {{=$valid}};
{{## def.callRuleValidate:
{{=$validateCode}}.call(
{{? it.opts.passContext }}this{{??}}self{{?}}
{{? $compile || $rDef.schema === false }}
, {{=$data}}
{{??}}
, {{=$schemaValue}}
, {{=$data}}
, validate.schema{{=it.schemaPath}}
{{?}}
, {{# def.dataPath }}
{{# def.passParentData }}
, rootData
)
#}}
{{## def.extendErrors:_inline:
for (var {{=$i}}={{=$errs}}; {{=$i}}<errors; {{=$i}}++) {
var {{=$ruleErr}} = vErrors[{{=$i}}];
if ({{=$ruleErr}}.dataPath === undefined)
{{=$ruleErr}}.dataPath = (dataPath || '') + {{= it.errorPath }};
{{# _inline ? 'if (\{\{=$ruleErr\}\}.schemaPath === undefined) {' : '' }}
{{=$ruleErr}}.schemaPath = "{{=$errSchemaPath}}";
{{# _inline ? '}' : '' }}
{{? it.opts.verbose }}
{{=$ruleErr}}.schema = {{=$schemaValue}};
{{=$ruleErr}}.data = {{=$data}};
{{?}}
}
#}}
{{? $isData && $rDef.$data }}
{{ $closingBraces += '}'; }}
if ({{=$schemaValue}} === undefined) {
{{=$valid}} = true;
} else {
{{? $validateSchema }}
{{ $closingBraces += '}'; }}
{{=$valid}} = {{=$definition}}.validateSchema({{=$schemaValue}});
if ({{=$valid}}) {
{{?}}
{{?}}
{{? $inline }}
{{? $rDef.statements }}
{{= $ruleValidate.validate }}
{{??}}
{{=$valid}} = {{= $ruleValidate.validate }};
{{?}}
{{?? $macro }}
{{# def.setupNextLevel }}
{{
$it.schema = $ruleValidate.validate;
$it.schemaPath = '';
}}
{{# def.setCompositeRule }}
{{ var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); }}
{{# def.resetCompositeRule }}
{{= $code }}
{{??}}
{{# def.beginDefOut}}
{{# def.callRuleValidate }}
{{# def.storeDefOut:def_callRuleValidate }}
{{? $rDef.errors === false }}
{{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
{{??}}
{{? $asyncKeyword }}
{{ $ruleErrs = 'customErrors' + $lvl; }}
var {{=$ruleErrs}} = null;
try {
{{=$valid}} = await {{= def_callRuleValidate }};
} catch (e) {
{{=$valid}} = false;
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;
else throw e;
}
{{??}}
{{=$ruleErrs}} = null;
{{=$valid}} = {{= def_callRuleValidate }};
{{?}}
{{?}}
{{?}}
{{? $rDef.modifying }}
if ({{=$parentData}}) {{=$data}} = {{=$parentData}}[{{=$parentDataProperty}}];
{{?}}
{{= $closingBraces }}
{{## def.notValidationResult:
{{? $rDef.valid === undefined }}
!{{? $macro }}{{=$nextValid}}{{??}}{{=$valid}}{{?}}
{{??}}
{{= !$rDef.valid }}
{{?}}
#}}
{{? $rDef.valid }}
{{? $breakOnError }} if (true) { {{?}}
{{??}}
if ({{# def.notValidationResult }}) {
{{ $errorKeyword = $rule.keyword; }}
{{# def.beginDefOut}}
{{# def.error:'custom' }}
{{# def.storeDefOut:def_customError }}
{{? $inline }}
{{? $rDef.errors }}
{{? $rDef.errors != 'full' }}
{{# def.extendErrors:true }}
{{?}}
{{??}}
{{? $rDef.errors === false}}
{{= def_customError }}
{{??}}
if ({{=$errs}} == errors) {
{{= def_customError }}
} else {
{{# def.extendErrors:true }}
}
{{?}}
{{?}}
{{?? $macro }}
{{# def.extraError:'custom' }}
{{??}}
{{? $rDef.errors === false}}
{{= def_customError }}
{{??}}
if (Array.isArray({{=$ruleErrs}})) {
if (vErrors === null) vErrors = {{=$ruleErrs}};
else vErrors = vErrors.concat({{=$ruleErrs}});
errors = vErrors.length;
{{# def.extendErrors:false }}
} else {
{{= def_customError }}
}
{{?}}
{{?}}
} {{? $breakOnError }} else { {{?}}
{{?}}

View File

@@ -0,0 +1,26 @@
import { expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("ZodPreprocess<B> assignable to ZodPipe<$ZodTransform, B>", () => {
const pre = z.preprocess((v) => v, z.string().optional());
const _asPipe: z.ZodPipe<z.core.$ZodTransform, z.ZodOptional<z.ZodString>> = pre;
const _asCorePipe: z.core.$ZodPipe<z.core.$ZodTransform, z.ZodOptional<z.ZodString>> = pre;
expectTypeOf(_asPipe).toMatchTypeOf<z.ZodPipe>();
expectTypeOf(_asCorePipe).toMatchTypeOf<z.core.$ZodPipe>();
});
test("ZodPreprocess optin/optout defer to B", () => {
const optionalInside = z.preprocess((v) => v, z.string().optional());
expectTypeOf<(typeof optionalInside)["_zod"]["optin"]>().toEqualTypeOf<"optional">();
expectTypeOf<(typeof optionalInside)["_zod"]["optout"]>().toEqualTypeOf<"optional">();
const required = z.preprocess((v) => v, z.string());
expectTypeOf<(typeof required)["_zod"]["optin"]>().toEqualTypeOf<"optional" | undefined>();
expectTypeOf<(typeof required)["_zod"]["optout"]>().toEqualTypeOf<"optional" | undefined>();
});
test("ZodPreprocess input/output inference", () => {
const pre = z.preprocess((v) => v, z.number().optional());
expectTypeOf<z.output<typeof pre>>().toEqualTypeOf<number | undefined>();
expectTypeOf<z.input<typeof pre>>().toEqualTypeOf<unknown>();
});

View File

@@ -0,0 +1,33 @@
'use strict';
//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
'$ref': require('./ref'),
allOf: require('./allOf'),
anyOf: require('./anyOf'),
'$comment': require('./comment'),
const: require('./const'),
contains: require('./contains'),
dependencies: require('./dependencies'),
'enum': require('./enum'),
format: require('./format'),
'if': require('./if'),
items: require('./items'),
maximum: require('./_limit'),
minimum: require('./_limit'),
maxItems: require('./_limitItems'),
minItems: require('./_limitItems'),
maxLength: require('./_limitLength'),
minLength: require('./_limitLength'),
maxProperties: require('./_limitProperties'),
minProperties: require('./_limitProperties'),
multipleOf: require('./multipleOf'),
not: require('./not'),
oneOf: require('./oneOf'),
pattern: require('./pattern'),
properties: require('./properties'),
propertyNames: require('./propertyNames'),
required: require('./required'),
uniqueItems: require('./uniqueItems'),
validate: require('./validate')
};

View File

@@ -0,0 +1,17 @@
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./createProjectService"), exports);

View File

@@ -0,0 +1,14 @@
type LegacyAllowConstantLoopConditions = boolean;
type AllowConstantLoopConditions = 'always' | 'never' | 'only-allowed-literals';
export type Options = [
{
allowConstantLoopConditions?: AllowConstantLoopConditions | LegacyAllowConstantLoopConditions;
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
checkTypePredicates?: boolean;
}
];
export type MessageId = 'alwaysFalsy' | 'alwaysFalsyFunc' | 'alwaysNullish' | 'alwaysTruthy' | 'alwaysTruthyFunc' | 'comparisonBetweenLiteralTypes' | 'never' | 'neverNullish' | 'neverOptionalChain' | 'noOverlapBooleanExpression' | 'noStrictNullCheck' | 'suggestRemoveOptionalChain' | 'typeGuardAlreadyIsType';
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<MessageId, Options, import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
name: string;
};
export default _default;

View File

@@ -0,0 +1 @@
{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["../src/ed448.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,24 @@
"use strict";
/* @minVersion 7.22.0 */
function _using(stack, value, isAwait) {
if (value === null || value === void 0) return value;
if (Object(value) !== value) {
throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
}
// core-js-pure uses Symbol.for for polyfilling well-known symbols
if (isAwait) {
var dispose = value[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
}
if (dispose === null || dispose === void 0) {
dispose = value[Symbol.dispose || Symbol.for("Symbol.dispose")];
}
if (typeof dispose !== "function") {
throw new TypeError(`Property [Symbol.dispose] is not a function.`);
}
stack.push({ v: value, d: dispose, a: isAwait });
return value;
}
exports._ = _using;

View File

@@ -0,0 +1,88 @@
/**
* HKDF (RFC 5869): extract + expand in one step.
* See https://soatok.blog/2021/11/17/understanding-hkdf/.
* @module
*/
import { hmac } from './hmac.ts';
import { ahash, anumber, type CHash, clean, type Input, toBytes } from './utils.ts';
/**
* HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
* Arguments position differs from spec (IKM is first one, since it is not optional)
* @param hash - hash function that would be used (e.g. sha256)
* @param ikm - input keying material, the initial key
* @param salt - optional salt value (a non-secret random value)
*/
export function extract(hash: CHash, ikm: Input, salt?: Input): Uint8Array {
ahash(hash);
// NOTE: some libraries treat zero-length array as 'not provided';
// we don't, since we have undefined as 'not provided'
// https://github.com/RustCrypto/KDFs/issues/15
if (salt === undefined) salt = new Uint8Array(hash.outputLen);
return hmac(hash, toBytes(salt), toBytes(ikm));
}
const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
/**
* HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
* @param hash - hash function that would be used (e.g. sha256)
* @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
* @param info - optional context and application specific information (can be a zero-length string)
* @param length - length of output keying material in bytes
*/
export function expand(hash: CHash, prk: Input, info?: Input, length: number = 32): Uint8Array {
ahash(hash);
anumber(length);
const olen = hash.outputLen;
if (length > 255 * olen) throw new Error('Length should be <= 255*HashLen');
const blocks = Math.ceil(length / olen);
if (info === undefined) info = EMPTY_BUFFER;
// first L(ength) octets of T
const okm = new Uint8Array(blocks * olen);
// Re-use HMAC instance between blocks
const HMAC = hmac.create(hash, prk);
const HMACTmp = HMAC._cloneInto();
const T = new Uint8Array(HMAC.outputLen);
for (let counter = 0; counter < blocks; counter++) {
HKDF_COUNTER[0] = counter + 1;
// T(0) = empty string (zero length)
// T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
.update(info)
.update(HKDF_COUNTER)
.digestInto(T);
okm.set(T, olen * counter);
HMAC._cloneInto(HMACTmp);
}
HMAC.destroy();
HMACTmp.destroy();
clean(T, HKDF_COUNTER);
return okm.slice(0, length);
}
/**
* HKDF (RFC 5869): derive keys from an initial input.
* Combines hkdf_extract + hkdf_expand in one step
* @param hash - hash function that would be used (e.g. sha256)
* @param ikm - input keying material, the initial key
* @param salt - optional salt value (a non-secret random value)
* @param info - optional context and application specific information (can be a zero-length string)
* @param length - length of output keying material in bytes
* @example
* import { hkdf } from '@noble/hashes/hkdf';
* import { sha256 } from '@noble/hashes/sha2';
* import { randomBytes } from '@noble/hashes/utils';
* const inputKey = randomBytes(32);
* const salt = randomBytes(32);
* const info = 'application-key';
* const hk1 = hkdf(sha256, inputKey, salt, info, 32);
*/
export const hkdf = (
hash: CHash,
ikm: Input,
salt: Input | undefined,
info: Input | undefined,
length: number
): Uint8Array => expand(hash, extract(hash, ikm, salt), info, length);

View File

@@ -0,0 +1,3 @@
"use strict";var u=Object.defineProperty;var s=(e,r)=>u(e,"name",{value:r,configurable:!0});var c=require("node:repl"),l=require("./package-sd2gMcZx.cjs"),q=require("./index-6kqi0x0U.cjs");require("node:path"),require("node:url"),require("esbuild"),require("node:crypto"),require("./node-features-CEjg7cMX.cjs"),require("node:fs"),require("node:os"),require("./temporary-directory-B83uKxJF.cjs"),console.log(`Welcome to tsx v${l.version} (Node.js ${process.version}).
Type ".help" for more information.`);const i=c.start(),{eval:p}=i,v=s(async function(e,r,o,t){const a=await q.transform(e,o,{loader:"ts",tsconfigRaw:{compilerOptions:{preserveValueImports:!0}},define:{require:"global.require"}}).catch(n=>(console.log(n.message),{code:`
`}));return p.call(this,a.code,r,o,t)},"preEval");i.eval=v;

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt

View File

@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference lib="es2016" />
/// <reference lib="es2017.arraybuffer" />
/// <reference lib="es2017.date" />
/// <reference lib="es2017.intl" />
/// <reference lib="es2017.object" />
/// <reference lib="es2017.sharedmemory" />
/// <reference lib="es2017.string" />
/// <reference lib="es2017.typedarrays" />

View File

@@ -0,0 +1,25 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface String {
/**
* Returns a new String consisting of the single UTF-16 code unit located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): string | undefined;
}

View File

@@ -0,0 +1,255 @@
import type { ClassicConfig, FlatConfig, SharedConfig } from './Config';
import type { Parser } from './Parser';
import type { Processor as ProcessorType } from './Processor';
import type { AnyRuleCreateFunction, AnyRuleModule, RuleCreateFunction, RuleFix, RuleModule } from './Rule';
import type { SourceCode } from './SourceCode';
export type MinimalRuleModule<MessageIds extends string = string, Options extends readonly unknown[] = []> = Partial<Omit<RuleModule<MessageIds, Options>, 'create'>> & Pick<RuleModule<MessageIds, Options>, 'create'>;
declare class LinterBase {
/**
* The version from package.json.
*/
readonly version: string;
/**
* Initialize the Linter.
* @param config the config object
*/
constructor(config?: Linter.LinterOptions);
/**
* Define a new parser module
* @param parserId Name of the parser
* @param parserModule The parser object
*/
defineParser(parserId: string, parserModule: Parser.LooseParserModule): void;
/**
* Defines a new linting rule.
* @param ruleId A unique rule identifier
* @param ruleModule Function from context to object mapping AST node types to event handlers
*/
defineRule<MessageIds extends string, Options extends readonly unknown[]>(ruleId: string, ruleModule: MinimalRuleModule<MessageIds, Options> | RuleCreateFunction): void;
/**
* Defines many new linting rules.
* @param rulesToDefine map from unique rule identifier to rule
*/
defineRules<MessageIds extends string, Options extends readonly unknown[]>(rulesToDefine: Record<string, MinimalRuleModule<MessageIds, Options> | RuleCreateFunction<MessageIds, Options>>): void;
/**
* Gets an object with all loaded rules.
* @returns All loaded rules
*/
getRules(): Map<string, MinimalRuleModule<string, unknown[]>>;
/**
* Gets the `SourceCode` object representing the parsed source.
* @returns The `SourceCode` object.
*/
getSourceCode(): SourceCode;
/**
* Verifies the text against the rules specified by the second argument.
* @param textOrSourceCode The text to parse or a SourceCode object.
* @param config An ESLintConfig instance to configure everything.
* @param filenameOrOptions The optional filename of the file being checked.
* If this is not set, the filename will default to '<input>' in the rule context.
* If this is an object, then it has "filename", "allowInlineConfig", and some properties.
* @returns The results as an array of messages or an empty array if no messages.
*/
verify(textOrSourceCode: string | SourceCode, config: Linter.ConfigType, filenameOrOptions?: string | Linter.VerifyOptions): Linter.LintMessage[];
/**
* The version from package.json.
*/
static readonly version: string;
/**
* Performs multiple autofix passes over the text until as many fixes as possible have been applied.
* @param code The source text to apply fixes to.
* @param config The ESLint config object to use.
* @param options The ESLint options object to use.
* @returns The result of the fix operation as returned from the SourceCodeFixer.
*/
verifyAndFix(code: string, config: Linter.ConfigType, options: Linter.FixOptions): Linter.FixReport;
}
declare namespace Linter {
interface LinterOptions {
/**
* Which config format to use.
* @default 'flat'
*/
configType?: ConfigTypeSpecifier;
/**
* path to a directory that should be considered as the current working directory.
*/
cwd?: string;
}
type ConfigTypeSpecifier = 'eslintrc' | 'flat';
type EnvironmentConfig = SharedConfig.EnvironmentConfig;
type GlobalsConfig = SharedConfig.GlobalsConfig;
type GlobalVariableOption = SharedConfig.GlobalVariableOption;
type GlobalVariableOptionBase = SharedConfig.GlobalVariableOptionBase;
type ParserOptions = SharedConfig.ParserOptions;
type PluginMeta = SharedConfig.PluginMeta;
type RuleEntry = SharedConfig.RuleEntry;
type RuleLevel = SharedConfig.RuleLevel;
type RuleLevelAndOptions = SharedConfig.RuleLevelAndOptions;
type RulesRecord = SharedConfig.RulesRecord;
type Severity = SharedConfig.Severity;
type SeverityString = SharedConfig.SeverityString;
/** @deprecated use {@link Linter.ConfigType} instead */
type Config = ClassicConfig.Config;
type ConfigType = ClassicConfig.Config | FlatConfig.Config | FlatConfig.ConfigArray;
/** @deprecated use {@link ClassicConfig.ConfigOverride} instead */
type ConfigOverride = ClassicConfig.ConfigOverride;
interface VerifyOptions {
/**
* Allow/disallow inline comments' ability to change config once it is set. Defaults to true if not supplied.
* Useful if you want to validate JS without comments overriding rules.
*/
allowInlineConfig?: boolean;
/**
* if `true` then the linter doesn't make `fix` properties into the lint result.
*/
disableFixes?: boolean;
/**
* the filename of the source code.
*/
filename?: string;
/**
* the predicate function that selects adopt code blocks.
*/
filterCodeBlock?: (filename: string, text: string) => boolean;
/**
* postprocessor for report messages.
* If provided, this should accept an array of the message lists
* for each code block returned from the preprocessor, apply a mapping to
* the messages as appropriate, and return a one-dimensional array of
* messages.
*/
postprocess?: ProcessorType.PostProcess;
/**
* preprocessor for source text.
* If provided, this should accept a string of source text, and return an array of code blocks to lint.
*/
preprocess?: ProcessorType.PreProcess;
/**
* Adds reported errors for unused `eslint-disable` directives.
*/
reportUnusedDisableDirectives?: boolean | SeverityString;
}
interface FixOptions extends VerifyOptions {
/**
* Determines whether fixes should be applied.
*/
fix?: boolean;
}
interface LintSuggestion {
desc: string;
fix: RuleFix;
messageId?: string;
}
interface LintMessage {
/**
* The 1-based column number.
*/
column: number;
/**
* The 1-based column number of the end location.
*/
endColumn?: number;
/**
* The 1-based line number of the end location.
*/
endLine?: number;
/**
* If `true` then this is a fatal error.
*/
fatal?: true;
/**
* Information for autofix.
*/
fix?: RuleFix;
/**
* The 1-based line number.
*/
line: number;
/**
* The error message.
*/
message: string;
messageId?: string;
/**
* @deprecated `nodeType` is deprecated and will be removed in the next major version.
*/
nodeType?: string;
/**
* The ID of the rule which makes this message.
*/
ruleId: string | null;
/**
* The severity of this message.
*/
severity: Severity;
source: string | null;
/**
* Information for suggestions
*/
suggestions?: LintSuggestion[];
}
interface FixReport {
/**
* True, if the code was fixed
*/
fixed: boolean;
/**
* Collection of all messages for the given code
*/
messages: LintMessage[];
/**
* Fixed code text (might be the same as input if no fixes were applied).
*/
output: string;
}
/** @deprecated use {@link Parser.ParserModule} */
type ParserModule = Parser.LooseParserModule;
/** @deprecated use {@link Parser.ParseResult} */
type ESLintParseResult = Parser.ParseResult;
/** @deprecated use {@link ProcessorType.ProcessorModule} */
type Processor = ProcessorType.ProcessorModule;
interface Environment {
/**
* The definition of global variables.
*/
globals?: GlobalsConfig;
/**
* The parser options that will be enabled under this environment.
*/
parserOptions?: ParserOptions;
}
type LegacyPluginRules = Record<string, AnyRuleCreateFunction | AnyRuleModule>;
type PluginRules = Record<string, AnyRuleModule>;
interface Plugin {
/**
* The definition of plugin configs.
*/
configs?: Record<string, ClassicConfig.Config>;
/**
* The definition of plugin environments.
*/
environments?: Record<string, Environment>;
/**
* Metadata about your plugin for easier debugging and more effective caching of plugins.
*/
meta?: PluginMeta;
/**
* The definition of plugin processors.
*/
processors?: Record<string, ProcessorType.ProcessorModule>;
/**
* The definition of plugin rules.
*/
rules?: LegacyPluginRules;
}
}
declare const Linter_base: typeof LinterBase;
/**
* The Linter object does the actual evaluation of the JavaScript code. It doesn't do any filesystem operations, it
* simply parses and reports on the code. In particular, the Linter object does not process configuration objects
* or files.
*/
declare class Linter extends Linter_base {
}
export { Linter };

View File

@@ -0,0 +1,13 @@
'use strict'
const { test } = require('node:test')
const stringifySafe = require('fast-safe-stringify')
const prettifyError = require('./prettify-error')
test('prettifies error', t => {
const error = Error('Bad error!')
const lines = stringifySafe(error, Object.getOwnPropertyNames(error), 2)
const prettyError = prettifyError({ keyName: 'errorKey', lines, ident: ' ', eol: '\n' })
t.assert.match(prettyError, /\s*errorKey: {\n\s*"stack":[\s\S]*"message": "Bad error!"/)
})