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,17 @@
// Code generated by Herebyfile.mjs generate:enums from internal/checker/types.go. DO NOT EDIT.
export var SignatureFlags;
(function (SignatureFlags) {
SignatureFlags[SignatureFlags["None"] = 0] = "None";
SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
SignatureFlags[SignatureFlags["Construct"] = 4] = "Construct";
SignatureFlags[SignatureFlags["Abstract"] = 8] = "Abstract";
SignatureFlags[SignatureFlags["IsInnerCallChain"] = 16] = "IsInnerCallChain";
SignatureFlags[SignatureFlags["IsOuterCallChain"] = 32] = "IsOuterCallChain";
SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 64] = "IsUntypedSignatureInJSFile";
SignatureFlags[SignatureFlags["IsNonInferrable"] = 128] = "IsNonInferrable";
SignatureFlags[SignatureFlags["IsSignatureCandidateForOverloadFailure"] = 256] = "IsSignatureCandidateForOverloadFailure";
SignatureFlags[SignatureFlags["PropagatingFlags"] = 335] = "PropagatingFlags";
SignatureFlags[SignatureFlags["CallChainFlags"] = 48] = "CallChainFlags";
})(SignatureFlags || (SignatureFlags = {}));
//# sourceMappingURL=signatureFlags.enum.js.map

View File

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

View File

@@ -0,0 +1,22 @@
'use strict'
const SonicBoom = require('..')
const out = new SonicBoom({ fd: process.stdout.fd })
const str = Buffer.alloc(1000).fill('a').toString()
let i = 0
function write () {
if (i++ === 10) {
return
}
if (out.write(str)) {
write()
} else {
out.once('drain', write)
}
}
write()

View File

@@ -0,0 +1,8 @@
import validate from './validate.js';
function version(uuid) {
if (!validate(uuid)) {
throw TypeError('Invalid UUID');
}
return parseInt(uuid.slice(14, 15), 16);
}
export default version;

View File

@@ -0,0 +1,313 @@
// @ts-ignore TS6133
import { expect, test } from "vitest";
import * as z from "zod/v3";
import { ZodIssueCode } from "../ZodError.js";
import { util } from "../helpers/util.js";
test("refinement", () => {
const obj1 = z.object({
first: z.string(),
second: z.string(),
});
const obj2 = obj1.partial().strict();
const obj3 = obj2.refine((data) => data.first || data.second, "Either first or second should be filled in.");
expect(obj1 === (obj2 as any)).toEqual(false);
expect(obj2 === (obj3 as any)).toEqual(false);
expect(() => obj1.parse({})).toThrow();
expect(() => obj2.parse({ third: "adsf" })).toThrow();
expect(() => obj3.parse({})).toThrow();
obj3.parse({ first: "a" });
obj3.parse({ second: "a" });
obj3.parse({ first: "a", second: "a" });
});
test("refinement 2", () => {
const validationSchema = z
.object({
email: z.string().email(),
password: z.string(),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, "Both password and confirmation must match");
expect(() =>
validationSchema.parse({
email: "aaaa@gmail.com",
password: "aaaaaaaa",
confirmPassword: "bbbbbbbb",
})
).toThrow();
});
test("refinement type guard", () => {
const validationSchema = z.object({
a: z.string().refine((s): s is "a" => s === "a"),
});
type Input = z.input<typeof validationSchema>;
type Schema = z.infer<typeof validationSchema>;
util.assertEqual<"a", Input["a"]>(false);
util.assertEqual<string, Input["a"]>(true);
util.assertEqual<"a", Schema["a"]>(true);
util.assertEqual<string, Schema["a"]>(false);
});
test("refinement Promise", async () => {
const validationSchema = z
.object({
email: z.string().email(),
password: z.string(),
confirmPassword: z.string(),
})
.refine(
(data) => Promise.resolve().then(() => data.password === data.confirmPassword),
"Both password and confirmation must match"
);
await validationSchema.parseAsync({
email: "aaaa@gmail.com",
password: "password",
confirmPassword: "password",
});
});
test("custom path", async () => {
const result = await z
.object({
password: z.string(),
confirm: z.string(),
})
.refine((data) => data.confirm === data.password, { path: ["confirm"] })
.spa({ password: "asdf", confirm: "qewr" });
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues[0].path).toEqual(["confirm"]);
}
});
test("use path in refinement context", async () => {
const noNested = z.string()._refinement((_val, ctx) => {
if (ctx.path.length > 0) {
ctx.addIssue({
code: ZodIssueCode.custom,
message: `schema cannot be nested. path: ${ctx.path.join(".")}`,
});
return false;
} else {
return true;
}
});
const data = z.object({
foo: noNested,
});
const t1 = await noNested.spa("asdf");
const t2 = await data.spa({ foo: "asdf" });
expect(t1.success).toBe(true);
expect(t2.success).toBe(false);
if (t2.success === false) {
expect(t2.error.issues[0].message).toEqual("schema cannot be nested. path: foo");
}
});
test("superRefine", () => {
const Strings = z.array(z.string()).superRefine((val, ctx) => {
if (val.length > 3) {
ctx.addIssue({
code: z.ZodIssueCode.too_big,
maximum: 3,
type: "array",
inclusive: true,
exact: true,
message: "Too many items 😡",
});
}
if (val.length !== new Set(val).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `No duplicates allowed.`,
});
}
});
const result = Strings.safeParse(["asfd", "asfd", "asfd", "asfd"]);
expect(result.success).toEqual(false);
if (!result.success) expect(result.error.issues.length).toEqual(2);
Strings.parse(["asfd", "qwer"]);
});
test("superRefine async", async () => {
const Strings = z.array(z.string()).superRefine(async (val, ctx) => {
if (val.length > 3) {
ctx.addIssue({
code: z.ZodIssueCode.too_big,
maximum: 3,
type: "array",
inclusive: true,
exact: true,
message: "Too many items 😡",
});
}
if (val.length !== new Set(val).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `No duplicates allowed.`,
});
}
});
const result = await Strings.safeParseAsync(["asfd", "asfd", "asfd", "asfd"]);
expect(result.success).toEqual(false);
if (!result.success) expect(result.error.issues.length).toEqual(2);
Strings.parseAsync(["asfd", "qwer"]);
});
test("superRefine - type narrowing", () => {
type NarrowType = { type: string; age: number };
const schema = z
.object({
type: z.string(),
age: z.number(),
})
.nullable()
.superRefine((arg, ctx): arg is NarrowType => {
if (!arg) {
// still need to make a call to ctx.addIssue
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "cannot be null",
fatal: true,
});
return false;
}
return true;
});
util.assertEqual<z.infer<typeof schema>, NarrowType>(true);
expect(schema.safeParse({ type: "test", age: 0 }).success).toEqual(true);
expect(schema.safeParse(null).success).toEqual(false);
});
test("chained mixed refining types", () => {
type firstRefinement = { first: string; second: number; third: true };
type secondRefinement = { first: "bob"; second: number; third: true };
type thirdRefinement = { first: "bob"; second: 33; third: true };
const schema = z
.object({
first: z.string(),
second: z.number(),
third: z.boolean(),
})
.nullable()
.refine((arg): arg is firstRefinement => !!arg?.third)
.superRefine((arg, ctx): arg is secondRefinement => {
util.assertEqual<typeof arg, firstRefinement>(true);
if (arg.first !== "bob") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "`first` property must be `bob`",
});
return false;
}
return true;
})
.refine((arg): arg is thirdRefinement => {
util.assertEqual<typeof arg, secondRefinement>(true);
return arg.second === 33;
});
util.assertEqual<z.infer<typeof schema>, thirdRefinement>(true);
});
test("get inner type", () => {
z.string()
.refine(() => true)
.innerType()
.parse("asdf");
});
test("chained refinements", () => {
const objectSchema = z
.object({
length: z.number(),
size: z.number(),
})
.refine(({ length }) => length > 5, {
path: ["length"],
message: "length greater than 5",
})
.refine(({ size }) => size > 7, {
path: ["size"],
message: "size greater than 7",
});
const r1 = objectSchema.safeParse({
length: 4,
size: 9,
});
expect(r1.success).toEqual(false);
if (!r1.success) expect(r1.error.issues.length).toEqual(1);
const r2 = objectSchema.safeParse({
length: 4,
size: 3,
});
expect(r2.success).toEqual(false);
if (!r2.success) expect(r2.error.issues.length).toEqual(2);
});
test("fatal superRefine", () => {
const Strings = z
.string()
.superRefine((val, ctx) => {
if (val === "") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "foo",
fatal: true,
});
}
})
.superRefine((val, ctx) => {
if (val !== " ") {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "bar",
});
}
});
const result = Strings.safeParse("");
expect(result.success).toEqual(false);
if (!result.success) expect(result.error.issues.length).toEqual(1);
});
test("superRefine after skipped transform", () => {
const schema = z
.string()
.regex(/^\d+$/)
.transform((val) => Number(val))
.superRefine((val) => {
if (typeof val !== "number") {
throw new Error("Called without transform");
}
});
const result = schema.safeParse("");
expect(result.success).toEqual(false);
});

View File

@@ -0,0 +1,95 @@
// Karma configuration
// Generated on Sun Sep 03 2017 04:55:32 GMT+0200 (CEST)
module.exports = function(config) {
// in seconds
var TIMEOUT = 360;
var customLaunchers = {
// desktop evergreen
sl_chrome: { base: 'SauceLabs', browserName: 'chrome', version: '60', idleTimeout: TIMEOUT },
sl_firefox: { base: 'SauceLabs', browserName: 'firefox', version: '54', idleTimeout: TIMEOUT },
sl_safari: { base: "SauceLabs", browserName: "safari", version: '10', platform: 'macOS 10.12', idleTimeout: TIMEOUT },
sl_edge: { base: "SauceLabs", browserName: "microsoftedge", version: '14', platform: 'Windows 10', idleTimeout: TIMEOUT },
//sl_opera: { base: "SauceLabs", browsername: "opera", version: '12', platform: 'Windows 7', idleTimeout: TIMEOUT },
// desktop legacy
sl_ie_9: { base: 'SauceLabs', browserName: 'internet explorer', version: '9', idleTimeout: TIMEOUT },
sl_ie_10: { base: 'SauceLabs', browserName: 'internet explorer', version: '10', idleTimeout: TIMEOUT },
sl_ie_11: { base: 'SauceLabs', browserName: 'internet explorer', version: '11', idleTimeout: TIMEOUT },
// mobile
sl_iphone: { base: 'SauceLabs', browserName: 'iphone', version: '10.3', idleTimeout: TIMEOUT },
sl_android: { base: 'SauceLabs', browserName: 'android', version: '6.0', idleTimeout: TIMEOUT },
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['benchmark'],
// list of files / patterns to load in the browser
files: [
'test/travis.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/travis.js': ['webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['benchmark'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: false,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
//browsers: ['Chrome', 'Firefox'],
browserNoActivityTimeout: TIMEOUT * 1000,
captureTimeout: TIMEOUT * 1000,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 5
})
};

View File

@@ -0,0 +1,52 @@
/**
* @fileoverview Rule to flag use of arguments.callee and arguments.caller.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Disallow the use of `arguments.caller` or `arguments.callee`",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-caller",
},
schema: [],
messages: {
unexpected: "Avoid arguments.{{prop}}.",
},
},
create(context) {
return {
MemberExpression(node) {
const objectName = node.object.name,
propertyName = node.property.name;
if (
objectName === "arguments" &&
!node.computed &&
propertyName &&
propertyName.match(/^calle[er]$/u)
) {
context.report({
node,
messageId: "unexpected",
data: { prop: propertyName },
});
}
},
};
},
};

View File

@@ -0,0 +1,409 @@
import { expect, expectTypeOf, test } from "vitest";
import { z } from "zod/v4";
test("basic defaults", () => {
expect(z.string().default("default").parse(undefined)).toBe("default");
});
test("default with optional", () => {
const schema = z.string().optional().default("default");
expect(schema.parse(undefined)).toBe("default");
expect(schema.unwrap().parse(undefined)).toBe(undefined);
});
test("default with transform", () => {
const stringWithDefault = z
.string()
.transform((val) => val.toUpperCase())
.default("default");
expect(stringWithDefault.parse(undefined)).toBe("default");
expect(stringWithDefault).toBeInstanceOf(z.ZodDefault);
expect(stringWithDefault.unwrap()).toBeInstanceOf(z.ZodPipe);
expect(stringWithDefault.unwrap().in).toBeInstanceOf(z.ZodString);
expect(stringWithDefault.unwrap().out).toBeInstanceOf(z.ZodTransform);
type inp = z.input<typeof stringWithDefault>;
expectTypeOf<inp>().toEqualTypeOf<string | undefined>();
type out = z.output<typeof stringWithDefault>;
expectTypeOf<out>().toEqualTypeOf<string>();
});
test("default on existing optional", () => {
const stringWithDefault = z.string().optional().default("asdf");
expect(stringWithDefault.parse(undefined)).toBe("asdf");
expect(stringWithDefault).toBeInstanceOf(z.ZodDefault);
expect(stringWithDefault.unwrap()).toBeInstanceOf(z.ZodOptional);
expect(stringWithDefault.unwrap().unwrap()).toBeInstanceOf(z.ZodString);
type inp = z.input<typeof stringWithDefault>;
expectTypeOf<inp>().toEqualTypeOf<string | undefined>();
type out = z.output<typeof stringWithDefault>;
expectTypeOf<out>().toEqualTypeOf<string>();
});
test("optional on default", () => {
const stringWithDefault = z.string().default("asdf").optional();
type inp = z.input<typeof stringWithDefault>;
expectTypeOf<inp>().toEqualTypeOf<string | undefined>();
type out = z.output<typeof stringWithDefault>;
expectTypeOf<out>().toEqualTypeOf<string | undefined>();
expect(stringWithDefault.parse(undefined)).toBe("asdf");
});
// test("complex chain example", () => {
// const complex = z
// .string()
// .default("asdf")
// .transform((val) => val.toUpperCase())
// .default("qwer")
// .unwrap()
// .optional()
// .default("asdfasdf");
// expect(complex.parse(undefined)).toBe("asdfasdf");
// });
test("removeDefault", () => {
const stringWithRemovedDefault = z.string().default("asdf").removeDefault();
type out = z.output<typeof stringWithRemovedDefault>;
expectTypeOf<out>().toEqualTypeOf<string>();
});
test("apply default at output", () => {
const schema = z
.string()
.transform((_) => (Math.random() > 0 ? undefined : _))
.default("asdf");
expect(schema.parse("")).toEqual("asdf");
});
test("nested", () => {
const inner = z.string().default("asdf");
const outer = z.object({ inner }).default({
inner: "qwer",
});
type input = z.input<typeof outer>;
expectTypeOf<input>().toEqualTypeOf<{ inner?: string | undefined } | undefined>();
type out = z.output<typeof outer>;
expectTypeOf<out>().toEqualTypeOf<{ inner: string }>();
expect(outer.parse(undefined)).toEqual({ inner: "qwer" });
expect(outer.parse({})).toEqual({ inner: "asdf" });
expect(outer.parse({ inner: undefined })).toEqual({ inner: "asdf" });
});
test("chained defaults", () => {
const stringWithDefault = z.string().default("inner").default("outer");
const result = stringWithDefault.parse(undefined);
expect(result).toEqual("outer");
});
test("object optionality", () => {
const schema = z.object({
hi: z.string().default("hi"),
});
type schemaInput = z.input<typeof schema>;
type schemaOutput = z.output<typeof schema>;
expectTypeOf<schemaInput>().toEqualTypeOf<{ hi?: string | undefined }>();
expectTypeOf<schemaOutput>().toEqualTypeOf<{ hi: string }>();
expect(schema.parse({})).toEqual({
hi: "hi",
});
});
test("nested prefault/default", () => {
const a = z
.string()
.default("a")
.refine((val) => val.startsWith("a"));
const b = z
.string()
.refine((val) => val.startsWith("b"))
.default("b");
const c = z
.string()
.prefault("c")
.refine((val) => val.startsWith("c"));
const d = z
.string()
.refine((val) => val.startsWith("d"))
.prefault("d");
const obj = z.object({
a,
b,
c,
d,
});
expect(obj.safeParse({ a: "a1", b: "b1", c: "c1", d: "d1" })).toMatchInlineSnapshot(`
{
"data": {
"a": "a1",
"b": "b1",
"c": "c1",
"d": "d1",
},
"success": true,
}
`);
expect(obj.safeParse({ a: "f", b: "f", c: "f", d: "f" })).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"code": "custom",
"path": [
"a"
],
"message": "Invalid input"
},
{
"code": "custom",
"path": [
"b"
],
"message": "Invalid input"
},
{
"code": "custom",
"path": [
"c"
],
"message": "Invalid input"
},
{
"code": "custom",
"path": [
"d"
],
"message": "Invalid input"
}
]],
"success": false,
}
`);
expect(obj.safeParse({})).toMatchInlineSnapshot(`
{
"data": {
"a": "a",
"b": "b",
"c": "c",
"d": "d",
},
"success": true,
}
`);
expect(obj.safeParse({ a: undefined, b: undefined, c: undefined, d: undefined })).toMatchInlineSnapshot(`
{
"data": {
"a": "a",
"b": "b",
"c": "c",
"d": "d",
},
"success": true,
}
`);
const obj2 = z.object({
a: a.optional(),
b: b.optional(),
c: c.optional(),
d: d.optional(),
});
expect(obj2.safeParse({ a: undefined, b: undefined, c: undefined, d: undefined })).toMatchInlineSnapshot(`
{
"data": {
"a": "a",
"b": "b",
"c": "c",
"d": "d",
},
"success": true,
}
`);
expect(a.parse(undefined)).toBe("a");
expect(b.parse(undefined)).toBe("b");
expect(c.parse(undefined)).toBe("c");
expect(d.parse(undefined)).toBe("d");
});
test("failing default", () => {
const a = z
.string()
.default("z")
.refine((val) => val.startsWith("a"));
const b = z
.string()
.refine((val) => val.startsWith("b"))
.default("z");
const c = z
.string()
.prefault("z")
.refine((val) => val.startsWith("c"));
const d = z
.string()
.refine((val) => val.startsWith("d"))
.prefault("z");
const obj = z.object({
a,
b,
c,
d,
});
expect(
obj.safeParse({
a: undefined,
b: undefined,
c: undefined,
d: undefined,
}).error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "custom",
"message": "Invalid input",
"path": [
"a",
],
},
{
"code": "custom",
"message": "Invalid input",
"path": [
"c",
],
},
{
"code": "custom",
"message": "Invalid input",
"path": [
"d",
],
},
]
`);
});
test("partial should not clobber defaults", () => {
const objWithDefaults = z.object({
a: z.string().default("defaultA"),
b: z.string().default("defaultB"),
c: z.string().default("defaultC"),
});
const objPartialWithOneRequired = objWithDefaults.partial(); //.required({ a: true });
const test = objPartialWithOneRequired.parse({});
expect(test).toMatchInlineSnapshot(`
{
"a": "defaultA",
"b": "defaultB",
"c": "defaultC",
}
`);
});
test("defaulted object schema returns shallow clone", () => {
const schema = z
.object({
a: z.string(),
})
.default({ a: "x" });
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
test("defaulted array schema returns shallow clone", () => {
const schema = z.array(z.string()).default(["x"]);
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
test("defaulted Map schema returns shallow clone", () => {
const schema = z.map(z.string(), z.number()).default(new Map([["a", 1]]));
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
test("defaulted Set schema returns shallow clone", () => {
const schema = z.set(z.string()).default(new Set(["x"]));
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
test("mutations on defaulted Map do not affect subsequent parses", () => {
const schema = z.map(z.string(), z.number()).default(new Map());
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
result1.set("key1", 1);
result2.set("key2", 2);
expect(result1.size).toBe(1);
expect(result1.get("key1")).toBe(1);
expect(result1.has("key2")).toBe(false);
expect(result2.size).toBe(1);
expect(result2.get("key2")).toBe(2);
expect(result2.has("key1")).toBe(false);
});
test("mutations on defaulted Set do not affect subsequent parses", () => {
const schema = z.set(z.string()).default(new Set());
const result1 = schema.parse(undefined);
const result2 = schema.parse(undefined);
result1.add("item1");
result2.add("item2");
expect(result1.size).toBe(1);
expect(result1.has("item1")).toBe(true);
expect(result1.has("item2")).toBe(false);
expect(result2.size).toBe(1);
expect(result2.has("item2")).toBe(true);
expect(result2.has("item1")).toBe(false);
});
test("direction-aware defaults", () => {
const schema = z.string().default("hello");
// Forward direction (regular parse): defaults should be applied
expect(schema.parse(undefined)).toBe("hello");
expect(schema.parse("hello")).toBe("hello");
// Reverse direction (encode): defaults should NOT be applied, undefined should fail validation
expect(() => z.encode(schema, undefined as any)).toThrow();
// But valid values should still work in reverse
expect(z.safeEncode(schema, "world")).toMatchInlineSnapshot(`
{
"data": "world",
"success": true,
}
`);
expect(z.safeEncode(schema, undefined as any)).toMatchInlineSnapshot(`
{
"error": [ZodError: [
{
"expected": "string",
"code": "invalid_type",
"path": [],
"message": "Invalid input: expected string, received undefined"
}
]],
"success": false,
}
`);
});

View File

@@ -0,0 +1,196 @@
# levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" />
__Light ECMAScript (JavaScript) Value Notation__
Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments).
Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1.
__How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose.
npm install levn
For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev).
## Quick Examples
```js
var parse = require('levn').parse;
parse('Number', '2'); // 2
parse('String', '2'); // '2'
parse('String', 'levn'); // 'levn'
parse('String', 'a b'); // 'a b'
parse('Boolean', 'true'); // true
parse('Date', '#2011-11-11#'); // (Date object)
parse('Date', '2011-11-11'); // (Date object)
parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi
parse('RegExp', 're'); // /re/
parse('Int', '2'); // 2
parse('Number | String', 'str'); // 'str'
parse('Number | String', '2'); // 2
parse('[Number]', '[1,2,3]'); // [1,2,3]
parse('(String, Boolean)', '(hi, false)'); // ['hi', false]
parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2}
// at the top level, you can ommit surrounding delimiters
parse('[Number]', '1,2,3'); // [1,2,3]
parse('(String, Boolean)', 'hi, false'); // ['hi', false]
parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2}
// wildcard - auto choose type
parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}]
```
## Usage
`require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions.
```js
// parse(type, input, options);
parse('[Number]', '1,2,3'); // [1, 2, 3]
// parsedTypeParse(parsedType, input, options);
var parsedType = require('type-check').parseType('[Number]');
parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3]
```
### parse(type, input, options)
`parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value.
##### arguments
* type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against
* input - `String` - the value written in the [levn format](#levn-format)
* options - `Maybe Object` - an optional parameter specifying additional [options](#options)
##### returns
`*` - the resulting JavaScript value
##### example
```js
parse('[Number]', '1,2,3'); // [1, 2, 3]
```
### parsedTypeParse(parsedType, input, options)
`parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function.
##### arguments
* type - `Object` - the type in the parsed type format which to check against
* input - `String` - the value written in the [levn format](#levn-format)
* options - `Maybe Object` - an optional parameter specifying additional [options](#options)
##### returns
`*` - the resulting JavaScript value
##### example
```js
var parsedType = require('type-check').parseType('[Number]');
parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3]
```
## Levn Format
Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`.
If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options).
* `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"`
* `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')`
* `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi`
* `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents
* `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`.
* `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`).
* `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`.
* Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`.
If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information:
* If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`.
* If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`.
* If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`.
* If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`.
* If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`).
* If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`.
If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list.
Whitespace between special characters and elements is inconsequential.
## Options
Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions.
### Explicit
A `Boolean`. By default it is `false`.
__Example:__
```js
parse('RegExp', 're', {explicit: false}); // /re/
parse('RegExp', 're', {explicit: true}); // Error: ... does not type check...
parse('RegExp | String', 're', {explicit: true}); // 're'
```
`explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section.
### customTypes
An `Object`. Empty `{}` by default.
__Example:__
```js
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function (x) {
return x % 2 === 0;
},
cast: function (x) {
return {type: 'Just', value: parseInt(x)};
}
}
}
}
parse('Even', '2', options); // 2
parse('Even', '3', options); // Error: Value: "3" does not type check...
```
__Another Example:__
```js
function Person(name, age){
this.name = name;
this.age = age;
}
var options = {
customTypes: {
Person: {
typeOf: 'Object',
validate: function (x) {
x instanceof Person;
},
cast: function (value, options, typesCast) {
var name, age;
if ({}.toString.call(value).slice(8, -1) !== 'Object') {
return {type: 'Nothing'};
}
name = typesCast(value.name, [{type: 'String'}], options);
age = typesCast(value.age, [{type: 'Numger'}], options);
return {type: 'Just', value: new Person(name, age)};
}
}
}
parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25}
```
`customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check.
`cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly.
## Technical About
`levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library.

View File

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

View File

@@ -0,0 +1,668 @@
/**
* @fileoverview Utility to load config files
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("node:path");
const fs = require("node:fs/promises");
const findUp = require("find-up");
const { pathToFileURL } = require("node:url");
const debug = require("debug")("eslint:config-loader");
const { FlatConfigArray } = require("./flat-config-array");
const { WarningService } = require("../services/warning-service");
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("../types").Linter.Config} Config */
/**
* @typedef {Object} ConfigLoaderOptions
* @property {string|false|undefined} configFile The path to the config file to use.
* @property {string} cwd The current working directory.
* @property {boolean} ignoreEnabled Indicates if ignore patterns should be honored.
* @property {Config|Array<Config>} [baseConfig] The base config to use.
* @property {Array<Config>} [defaultConfigs] The default configs to use.
* @property {Array<string>} [ignorePatterns] The ignore patterns to use.
* @property {Config|Array<Config>} [overrideConfig] The override config to use.
* @property {boolean} [hasUnstableNativeNodeJsTSConfigFlag] The flag to indicate whether the `unstable_native_nodejs_ts_config` flag is enabled.
* @property {WarningService} [warningService] The warning service to use.
*/
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const FLAT_CONFIG_FILENAMES = [
"eslint.config.js",
"eslint.config.mjs",
"eslint.config.cjs",
"eslint.config.ts",
"eslint.config.mts",
"eslint.config.cts",
];
const importedConfigFileModificationTime = new Map();
/**
* Asserts that the given file path is valid.
* @param {string} filePath The file path to check.
* @returns {void}
* @throws {Error} If `filePath` is not a non-empty string.
*/
function assertValidFilePath(filePath) {
if (!filePath || typeof filePath !== "string") {
throw new Error("'filePath' must be a non-empty string");
}
}
/**
* Asserts that a configuration exists. A configuration exists if any
* of the following are true:
* - `configFilePath` is defined.
* - `useConfigFile` is `false`.
* @param {string|undefined} configFilePath The path to the config file.
* @param {ConfigLoaderOptions} loaderOptions The options to use when loading configuration files.
* @returns {void}
* @throws {Error} If no configuration exists.
*/
function assertConfigurationExists(configFilePath, loaderOptions) {
const { configFile: useConfigFile } = loaderOptions;
if (!configFilePath && useConfigFile !== false) {
const error = new Error("Could not find config file.");
error.messageTemplate = "config-file-missing";
throw error;
}
}
/**
* Check if the file is a TypeScript file.
* @param {string} filePath The file path to check.
* @returns {boolean} `true` if the file is a TypeScript file, `false` if it's not.
*/
function isFileTS(filePath) {
const fileExtension = path.extname(filePath);
return /^\.[mc]?ts$/u.test(fileExtension);
}
/**
* Check if ESLint is running in Bun.
* @returns {boolean} `true` if the ESLint is running Bun, `false` if it's not.
*/
function isRunningInBun() {
return !!globalThis.Bun;
}
/**
* Check if ESLint is running in Deno.
* @returns {boolean} `true` if the ESLint is running in Deno, `false` if it's not.
*/
function isRunningInDeno() {
return !!globalThis.Deno;
}
/**
* Checks if native TypeScript support is
* enabled in the current Node.js process.
*
* This function determines if the
* {@linkcode NodeJS.ProcessFeatures.typescript | typescript}
* feature is present in the
* {@linkcode process.features} object
* and if its value is either "strip" or "transform".
* @returns {boolean} `true` if native TypeScript support is enabled, otherwise `false`.
* @since 9.24.0
*/
function isNativeTypeScriptSupportEnabled() {
return (
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- it's still an experimental feature.
["strip", "transform"].includes(process.features.typescript)
);
}
/**
* Load the TypeScript configuration file.
* @param {string} filePath The absolute file path to load.
* @param {URL} fileURL The file URL to load.
* @param {number} mtime The last modified timestamp of the file.
* @returns {Promise<any>} The configuration loaded from the file.
* @since 9.24.0
*/
async function loadTypeScriptConfigFileWithJiti(filePath, fileURL, mtime) {
const { createJiti, version: jitiVersion } =
// eslint-disable-next-line no-use-before-define -- `ConfigLoader.loadJiti` can be overwritten for testing
await ConfigLoader.loadJiti().catch(() => {
throw new Error(
"The 'jiti' library is required for loading TypeScript configuration files. Make sure to install it.",
);
});
// Ensure the version is at least 2.2.0.
const [jitiMajor, jitiMinor] = jitiVersion
.split(".")
.map(versionPart => Number(versionPart));
if (jitiMajor < 2 || (jitiMajor === 2 && jitiMinor < 2)) {
throw new Error(
"You are using an outdated version of the 'jiti' library. Please update to the latest version of 'jiti' to ensure compatibility and access to the latest features.",
);
}
/*
* Disabling `moduleCache` allows us to reload a
* config file when the last modified timestamp changes.
*/
const jitiOptions = {
moduleCache: false,
};
const jiti = createJiti(__filename, jitiOptions);
const config = await jiti.import(fileURL.href);
importedConfigFileModificationTime.set(filePath, mtime);
return config?.default ?? config;
}
/**
* Dynamically imports a module from the given file path.
* @param {string} filePath The absolute file path of the module to import.
* @param {URL} fileURL The file URL to load.
* @param {number} mtime The last modified timestamp of the file.
* @returns {Promise<any>} - A {@linkcode Promise | promise} that resolves to the imported ESLint config.
* @since 9.24.0
*/
async function dynamicImportConfig(filePath, fileURL, mtime) {
const module = await import(fileURL.href);
importedConfigFileModificationTime.set(filePath, mtime);
return module.default;
}
/**
* Load the config array from the given filename.
* @param {string} filePath The filename to load from.
* @param {boolean} hasUnstableNativeNodeJsTSConfigFlag The flag to indicate whether the `unstable_native_nodejs_ts_config` flag is enabled.
* @returns {Promise<any>} The config loaded from the config file.
*/
async function loadConfigFile(filePath, hasUnstableNativeNodeJsTSConfigFlag) {
debug(`Loading config from ${filePath}`);
const fileURL = pathToFileURL(filePath);
debug(`Config file URL is ${fileURL}`);
const mtime = (await fs.stat(filePath)).mtime.getTime();
/*
* Append a query with the config file's modification time (`mtime`) in order
* to import the current version of the config file. Without the query, `import()` would
* cache the config file module by the pathname only, and then always return
* the same version (the one that was actual when the module was imported for the first time).
*
* This ensures that the config file module is loaded and executed again
* if it has been changed since the last time it was imported.
* If it hasn't been changed, `import()` will just return the cached version.
*
* Note that we should not overuse queries (e.g., by appending the current time
* to always reload the config file module) as that could cause memory leaks
* because entries are never removed from the import cache.
*/
fileURL.searchParams.append("mtime", mtime);
/*
* With queries, we can bypass the import cache. However, when import-ing a CJS module,
* Node.js uses the require infrastructure under the hood. That includes the require cache,
* which caches the config file module by its file path (queries have no effect).
* Therefore, we also need to clear the require cache before importing the config file module.
* In order to get the same behavior with ESM and CJS config files, in particular - to reload
* the config file only if it has been changed, we track file modification times and clear
* the require cache only if the file has been changed.
*/
if (importedConfigFileModificationTime.get(filePath) !== mtime) {
delete require.cache?.[filePath];
}
const isTS = isFileTS(filePath);
const isBun = isRunningInBun();
const isDeno = isRunningInDeno();
/*
* If we are dealing with a TypeScript file, then we need to use `jiti` to load it
* in Node.js. Deno and Bun both allow native importing of TypeScript files.
*
* When Node.js supports native TypeScript imports, we can remove this check.
*/
if (isTS) {
if (hasUnstableNativeNodeJsTSConfigFlag) {
if (isNativeTypeScriptSupportEnabled()) {
return await dynamicImportConfig(filePath, fileURL, mtime);
}
if (!("typescript" in process.features)) {
throw new Error(
"The unstable_native_nodejs_ts_config flag is not supported in older versions of Node.js.",
);
}
throw new Error(
"The unstable_native_nodejs_ts_config flag is enabled, but native TypeScript support is not enabled in the current Node.js process. You need to either enable native TypeScript support by passing --experimental-strip-types or remove the unstable_native_nodejs_ts_config flag.",
);
}
if (!isDeno && !isBun) {
return await loadTypeScriptConfigFileWithJiti(
filePath,
fileURL,
mtime,
);
}
}
// fallback to normal runtime behavior
return await dynamicImportConfig(filePath, fileURL, mtime);
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Encapsulates the loading and caching of configuration files when looking up
* from the file being linted.
*/
class ConfigLoader {
/**
* Map of config file paths to the config arrays for those directories.
* @type {Map<string, FlatConfigArray|Promise<FlatConfigArray>>}
*/
#configArrays = new Map();
/**
* Map of absolute directory names to the config file paths for those directories.
* @type {Map<string, {configFilePath:string,basePath:string}|Promise<{configFilePath:string,basePath:string}>>}
*/
#configFilePaths = new Map();
/**
* The options to use when loading configuration files.
* @type {ConfigLoaderOptions}
*/
#options;
/**
* Creates a new instance.
* @param {ConfigLoaderOptions} options The options to use when loading configuration files.
*/
constructor(options) {
this.#options = options.warningService
? options
: { ...options, warningService: new WarningService() };
}
/**
* Determines which config file to use. This is determined by seeing if an
* override config file was specified, and if so, using it; otherwise, as long
* as override config file is not explicitly set to `false`, it will search
* upwards from `fromDirectory` for a file named `eslint.config.js`.
* @param {string} fromDirectory The directory from which to start searching.
* @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for
* the config file.
*/
async #locateConfigFileToUse(fromDirectory) {
// check cache first
if (this.#configFilePaths.has(fromDirectory)) {
return this.#configFilePaths.get(fromDirectory);
}
const resultPromise = ConfigLoader.locateConfigFileToUse({
useConfigFile: this.#options.configFile,
cwd: this.#options.cwd,
fromDirectory,
});
// ensure `ConfigLoader.locateConfigFileToUse` is called only once for `fromDirectory`
this.#configFilePaths.set(fromDirectory, resultPromise);
// Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method.
const result = await resultPromise;
this.#configFilePaths.set(fromDirectory, result);
return result;
}
/**
* Calculates the config array for this run based on inputs.
* @param {string} configFilePath The absolute path to the config file to use if not overridden.
* @param {string} basePath The base path to use for relative paths in the config file.
* @returns {Promise<FlatConfigArray>} The config array for `eslint`.
*/
async #calculateConfigArray(configFilePath, basePath) {
// check for cached version first
if (this.#configArrays.has(configFilePath)) {
return this.#configArrays.get(configFilePath);
}
const configsPromise = ConfigLoader.calculateConfigArray(
configFilePath,
basePath,
this.#options,
);
// ensure `ConfigLoader.calculateConfigArray` is called only once for `configFilePath`
this.#configArrays.set(configFilePath, configsPromise);
// Unwrap the promise. This is primarily for the sync `getCachedConfigArrayForPath` method.
const configs = await configsPromise;
this.#configArrays.set(configFilePath, configs);
return configs;
}
/**
* Returns the config file path for the given directory or file. This will either use
* the override config file that was specified in the constructor options or
* search for a config file from the directory.
* @param {string} fileOrDirPath The file or directory path to get the config file path for.
* @returns {Promise<string|undefined>} The config file path or `undefined` if not found.
* @throws {Error} If `fileOrDirPath` is not a non-empty string.
* @throws {Error} If `fileOrDirPath` is not an absolute path.
*/
async findConfigFileForPath(fileOrDirPath) {
assertValidFilePath(fileOrDirPath);
const absoluteDirPath = path.resolve(
this.#options.cwd,
path.dirname(fileOrDirPath),
);
const { configFilePath } =
await this.#locateConfigFileToUse(absoluteDirPath);
return configFilePath;
}
/**
* Returns a configuration object for the given file based on the CLI options.
* This is the same logic used by the ESLint CLI executable to determine
* configuration for each file it processes.
* @param {string} filePath The path of the file or directory to retrieve config for.
* @returns {Promise<FlatConfigArray>} A configuration object for the file.
* @throws {Error} If no configuration for `filePath` exists.
*/
async loadConfigArrayForFile(filePath) {
assertValidFilePath(filePath);
debug(`Calculating config for file ${filePath}`);
const configFilePath = await this.findConfigFileForPath(filePath);
assertConfigurationExists(configFilePath, this.#options);
return this.loadConfigArrayForDirectory(filePath);
}
/**
* Returns a configuration object for the given directory based on the CLI options.
* This is the same logic used by the ESLint CLI executable to determine
* configuration for each file it processes.
* @param {string} dirPath The path of the directory to retrieve config for.
* @returns {Promise<FlatConfigArray>} A configuration object for the directory.
*/
async loadConfigArrayForDirectory(dirPath) {
assertValidFilePath(dirPath);
debug(`Calculating config for directory ${dirPath}`);
const absoluteDirPath = path.resolve(
this.#options.cwd,
path.dirname(dirPath),
);
const { configFilePath, basePath } =
await this.#locateConfigFileToUse(absoluteDirPath);
debug(`Using config file ${configFilePath} and base path ${basePath}`);
return this.#calculateConfigArray(configFilePath, basePath);
}
/**
* Returns a configuration array for the given file based on the CLI options.
* This is a synchronous operation and does not read any files from disk. It's
* intended to be used in locations where we know the config file has already
* been loaded and we just need to get the configuration for a file.
* @param {string} filePath The path of the file to retrieve a config object for.
* @returns {FlatConfigArray} A configuration object for the file.
* @throws {Error} If `filePath` is not a non-empty string.
* @throws {Error} If `filePath` is not an absolute path.
* @throws {Error} If the config file was not already loaded.
*/
getCachedConfigArrayForFile(filePath) {
assertValidFilePath(filePath);
debug(`Looking up cached config for ${filePath}`);
return this.getCachedConfigArrayForPath(path.dirname(filePath));
}
/**
* Returns a configuration array for the given directory based on the CLI options.
* This is a synchronous operation and does not read any files from disk. It's
* intended to be used in locations where we know the config file has already
* been loaded and we just need to get the configuration for a file.
* @param {string} fileOrDirPath The path of the directory to retrieve a config object for.
* @returns {FlatConfigArray} A configuration object for the directory.
* @throws {Error} If `dirPath` is not a non-empty string.
* @throws {Error} If `dirPath` is not an absolute path.
* @throws {Error} If the config file was not already loaded.
*/
getCachedConfigArrayForPath(fileOrDirPath) {
assertValidFilePath(fileOrDirPath);
debug(`Looking up cached config for ${fileOrDirPath}`);
const absoluteDirPath = path.resolve(this.#options.cwd, fileOrDirPath);
if (!this.#configFilePaths.has(absoluteDirPath)) {
throw new Error(`Could not find config file for ${fileOrDirPath}`);
}
const configFilePathInfo = this.#configFilePaths.get(absoluteDirPath);
if (typeof configFilePathInfo.then === "function") {
throw new Error(
`Config file path for ${fileOrDirPath} has not yet been calculated or an error occurred during the calculation`,
);
}
const { configFilePath } = configFilePathInfo;
const configArray = this.#configArrays.get(configFilePath);
if (!configArray || typeof configArray.then === "function") {
throw new Error(
`Config array for ${fileOrDirPath} has not yet been calculated or an error occurred during the calculation`,
);
}
return configArray;
}
/**
* Used to import the jiti dependency. This method is exposed internally for testing purposes.
* @returns {Promise<{createJiti: Function|undefined, version: string;}>} A promise that fulfills with an object containing the jiti module's createJiti function and version.
*/
static async loadJiti() {
const { createJiti } = await import("jiti");
const version = require("jiti/package.json").version;
return { createJiti, version };
}
/**
* Determines which config file to use. This is determined by seeing if an
* override config file was specified, and if so, using it; otherwise, as long
* as override config file is not explicitly set to `false`, it will search
* upwards from `fromDirectory` for a file named `eslint.config.js`.
* This method is exposed internally for testing purposes.
* @param {Object} [options] the options object
* @param {string|false|undefined} options.useConfigFile The path to the config file to use.
* @param {string} options.cwd Path to a directory that should be considered as the current working directory.
* @param {string} [options.fromDirectory] The directory from which to start searching. Defaults to `cwd`.
* @returns {Promise<{configFilePath:string|undefined,basePath:string}>} Location information for
* the config file.
*/
static async locateConfigFileToUse({
useConfigFile,
cwd,
fromDirectory = cwd,
}) {
// determine where to load config file from
let configFilePath;
let basePath = cwd;
if (typeof useConfigFile === "string") {
debug(`Override config file path is ${useConfigFile}`);
configFilePath = path.resolve(cwd, useConfigFile);
basePath = cwd;
} else if (useConfigFile !== false) {
debug("Searching for eslint.config.js");
configFilePath = await findUp(FLAT_CONFIG_FILENAMES, {
cwd: fromDirectory,
});
if (configFilePath) {
basePath = path.dirname(configFilePath);
}
}
return {
configFilePath,
basePath,
};
}
/**
* Calculates the config array for this run based on inputs.
* This method is exposed internally for testing purposes.
* @param {string} configFilePath The absolute path to the config file to use if not overridden.
* @param {string} basePath The base path to use for relative paths in the config file.
* @param {ConfigLoaderOptions} options The options to use when loading configuration files.
* @returns {Promise<FlatConfigArray>} The config array for `eslint`.
*/
static async calculateConfigArray(configFilePath, basePath, options) {
const {
cwd,
baseConfig,
ignoreEnabled,
ignorePatterns,
overrideConfig,
hasUnstableNativeNodeJsTSConfigFlag = false,
defaultConfigs = [],
warningService,
} = options;
debug(
`Calculating config array from config file ${configFilePath} and base path ${basePath}`,
);
const configs = new FlatConfigArray(baseConfig || [], {
basePath,
shouldIgnore: ignoreEnabled,
});
// load config file
if (configFilePath) {
debug(`Loading config file ${configFilePath}`);
const fileConfig = await loadConfigFile(
configFilePath,
hasUnstableNativeNodeJsTSConfigFlag,
);
/*
* It's possible that a config file could be empty or else
* have an empty object or array. In this case, we want to
* warn the user that they have an empty config.
*
* An empty CommonJS file exports an empty object while
* an empty ESM file exports undefined.
*/
let emptyConfig = typeof fileConfig === "undefined";
debug(
`Config file ${configFilePath} is ${emptyConfig ? "empty" : "not empty"}`,
);
if (!emptyConfig) {
if (Array.isArray(fileConfig)) {
if (fileConfig.length === 0) {
debug(
`Config file ${configFilePath} is an empty array`,
);
emptyConfig = true;
} else {
configs.push(...fileConfig);
}
} else {
if (
typeof fileConfig === "object" &&
fileConfig !== null &&
Object.keys(fileConfig).length === 0
) {
debug(
`Config file ${configFilePath} is an empty object`,
);
emptyConfig = true;
} else {
configs.push(fileConfig);
}
}
}
if (emptyConfig) {
warningService.emitEmptyConfigWarning(configFilePath);
}
}
// add in any configured defaults
configs.push(...defaultConfigs);
// append command line ignore patterns
if (ignorePatterns && ignorePatterns.length > 0) {
/*
* Ignore patterns are added to the end of the config array
* so they can override default ignores.
*/
configs.push({
basePath: cwd,
ignores: ignorePatterns,
});
}
if (overrideConfig) {
if (Array.isArray(overrideConfig)) {
configs.push(...overrideConfig);
} else {
configs.push(overrideConfig);
}
}
await configs.normalize();
return configs;
}
}
module.exports = { ConfigLoader };

View File

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

View File

@@ -0,0 +1,6 @@
require('./libs');
//require('./escape-short');
//require('./escape-long');
//require('./itar-short');
//require('./itar-long');
//require('./iter');

View File

@@ -0,0 +1,8 @@
export type ParseClassResult = [
src: string,
uFlag: boolean,
consumed: number,
hasMagic: boolean
];
export declare const parseClass: (glob: string, position: number) => ParseClassResult;
//# sourceMappingURL=brace-expressions.d.ts.map

View File

@@ -0,0 +1,68 @@
import Agent from './agent'
import Dispatcher from './dispatcher'
import { Interceptable, MockInterceptor } from './mock-interceptor'
import MockDispatch = MockInterceptor.MockDispatch
import { MockCallHistory } from './mock-call-history'
export default MockAgent
interface PendingInterceptor extends MockDispatch {
origin: string;
}
/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */
declare class MockAgent<TMockAgentOptions extends MockAgent.Options = MockAgent.Options> extends Dispatcher {
constructor (options?: TMockAgentOptions)
/** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */
get<TInterceptable extends Interceptable>(origin: string): TInterceptable
get<TInterceptable extends Interceptable>(origin: RegExp): TInterceptable
get<TInterceptable extends Interceptable>(origin: ((origin: string) => boolean)): TInterceptable
/** Dispatches a mocked request. */
dispatch (options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean
/** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */
close (): Promise<void>
/** Disables mocking in MockAgent. */
deactivate (): void
/** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */
activate (): void
/** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */
enableNetConnect (): void
enableNetConnect (host: string): void
enableNetConnect (host: RegExp): void
enableNetConnect (host: ((host: string) => boolean)): void
/** Causes all requests to throw when requests are not matched in a MockAgent intercept. */
disableNetConnect (): void
/** get call history. returns the MockAgent call history or undefined if the option is not enabled. */
getCallHistory (): MockCallHistory | undefined
/** clear every call history. Any MockCallHistoryLog will be deleted on the MockCallHistory instance */
clearCallHistory (): void
/** Enable call history. Any subsequence calls will then be registered. */
enableCallHistory (): this
/** Disable call history. Any subsequence calls will then not be registered. */
disableCallHistory (): this
pendingInterceptors (): PendingInterceptor[]
assertNoPendingInterceptors (options?: {
pendingInterceptorsFormatter?: PendingInterceptorsFormatter;
}): void
}
interface PendingInterceptorsFormatter {
format(pendingInterceptors: readonly PendingInterceptor[]): string;
}
declare namespace MockAgent {
/** MockAgent options. */
export interface Options extends Agent.Options {
/** A custom agent to be encapsulated by the MockAgent. */
agent?: Dispatcher;
/** Ignore trailing slashes in the path */
ignoreTrailingSlash?: boolean;
/** Accept URLs with search parameters using non standard syntaxes. default false */
acceptNonStandardSearchParameters?: boolean;
/** Enable call history. you can either call MockAgent.enableCallHistory(). default false */
enableCallHistory?: boolean
}
}

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SwitchScope = void 0;
const ScopeBase_1 = require("./ScopeBase");
const ScopeType_1 = require("./ScopeType");
class SwitchScope extends ScopeBase_1.ScopeBase {
constructor(scopeManager, upperScope, block) {
super(scopeManager, ScopeType_1.ScopeType.switch, upperScope, block, false);
}
}
exports.SwitchScope = SwitchScope;

View File

@@ -0,0 +1,319 @@
/**
* @fileoverview Rule to enforce sorted `import` declarations within modules
* @author Christian Schuller
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
{
allowSeparatedGroups: false,
ignoreCase: false,
ignoreDeclarationSort: false,
ignoreMemberSort: false,
memberSyntaxSortOrder: ["none", "all", "multiple", "single"],
},
],
docs: {
description: "Enforce sorted `import` declarations within modules",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/sort-imports",
},
schema: [
{
type: "object",
properties: {
ignoreCase: {
type: "boolean",
},
memberSyntaxSortOrder: {
type: "array",
items: {
enum: ["none", "all", "multiple", "single"],
},
uniqueItems: true,
minItems: 4,
maxItems: 4,
},
ignoreDeclarationSort: {
type: "boolean",
},
ignoreMemberSort: {
type: "boolean",
},
allowSeparatedGroups: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
sortImportsAlphabetically:
"Imports should be sorted alphabetically.",
sortMembersAlphabetically:
"Member '{{memberName}}' of the import declaration should be sorted alphabetically.",
unexpectedSyntaxOrder:
"Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax.",
},
},
create(context) {
const [
{
ignoreCase,
ignoreDeclarationSort,
ignoreMemberSort,
memberSyntaxSortOrder,
allowSeparatedGroups,
},
] = context.options;
const sourceCode = context.sourceCode;
let previousDeclaration = null;
/**
* Gets the used member syntax style.
*
* import "my-module.js" --> none
* import * as myModule from "my-module.js" --> all
* import {myMember} from "my-module.js" --> single
* import {foo, bar} from "my-module.js" --> multiple
* @param {ASTNode} node the ImportDeclaration node.
* @returns {string} used member parameter style, ["all", "multiple", "single"]
*/
function usedMemberSyntax(node) {
if (node.specifiers.length === 0) {
return "none";
}
if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
return "all";
}
if (node.specifiers.length === 1) {
return "single";
}
return "multiple";
}
/**
* Gets the group by member parameter index for given declaration.
* @param {ASTNode} node the ImportDeclaration node.
* @returns {number} the declaration group by member index.
*/
function getMemberParameterGroupIndex(node) {
return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node));
}
/**
* Gets the local name of the first imported module.
* @param {ASTNode} node the ImportDeclaration node.
* @returns {?string} the local name of the first imported module.
*/
function getFirstLocalMemberName(node) {
if (node.specifiers[0]) {
return node.specifiers[0].local.name;
}
return null;
}
/**
* Calculates number of lines between two nodes. It is assumed that the given `left` node appears before
* the given `right` node in the source code. Lines are counted from the end of the `left` node till the
* start of the `right` node. If the given nodes are on the same line, it returns `0`, same as if they were
* on two consecutive lines.
* @param {ASTNode} left node that appears before the given `right` node.
* @param {ASTNode} right node that appears after the given `left` node.
* @returns {number} number of lines between nodes.
*/
function getNumberOfLinesBetween(left, right) {
return Math.max(right.loc.start.line - left.loc.end.line - 1, 0);
}
return {
ImportDeclaration(node) {
if (!ignoreDeclarationSort) {
if (
previousDeclaration &&
allowSeparatedGroups &&
getNumberOfLinesBetween(previousDeclaration, node) > 0
) {
// reset declaration sort
previousDeclaration = null;
}
if (previousDeclaration) {
const currentMemberSyntaxGroupIndex =
getMemberParameterGroupIndex(node),
previousMemberSyntaxGroupIndex =
getMemberParameterGroupIndex(
previousDeclaration,
);
let currentLocalMemberName =
getFirstLocalMemberName(node),
previousLocalMemberName =
getFirstLocalMemberName(previousDeclaration);
if (ignoreCase) {
previousLocalMemberName =
previousLocalMemberName &&
previousLocalMemberName.toLowerCase();
currentLocalMemberName =
currentLocalMemberName &&
currentLocalMemberName.toLowerCase();
}
/*
* When the current declaration uses a different member syntax,
* then check if the ordering is correct.
* Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name.
*/
if (
currentMemberSyntaxGroupIndex !==
previousMemberSyntaxGroupIndex
) {
if (
currentMemberSyntaxGroupIndex <
previousMemberSyntaxGroupIndex
) {
context.report({
node,
messageId: "unexpectedSyntaxOrder",
data: {
syntaxA:
memberSyntaxSortOrder[
currentMemberSyntaxGroupIndex
],
syntaxB:
memberSyntaxSortOrder[
previousMemberSyntaxGroupIndex
],
},
});
}
} else {
if (
previousLocalMemberName &&
currentLocalMemberName &&
currentLocalMemberName < previousLocalMemberName
) {
context.report({
node,
messageId: "sortImportsAlphabetically",
});
}
}
}
previousDeclaration = node;
}
if (!ignoreMemberSort) {
const importSpecifiers = node.specifiers.filter(
specifier => specifier.type === "ImportSpecifier",
);
const getSortableName = ignoreCase
? specifier => specifier.local.name.toLowerCase()
: specifier => specifier.local.name;
const firstUnsortedIndex = importSpecifiers
.map(getSortableName)
.findIndex(
(name, index, array) => array[index - 1] > name,
);
if (firstUnsortedIndex !== -1) {
context.report({
node: importSpecifiers[firstUnsortedIndex],
messageId: "sortMembersAlphabetically",
data: {
memberName:
importSpecifiers[firstUnsortedIndex].local
.name,
},
fix(fixer) {
if (
importSpecifiers.some(
specifier =>
sourceCode.getCommentsBefore(
specifier,
).length ||
sourceCode.getCommentsAfter(
specifier,
).length,
)
) {
// If there are comments in the ImportSpecifier list, don't rearrange the specifiers.
return null;
}
return fixer.replaceTextRange(
[
importSpecifiers[0].range[0],
importSpecifiers.at(-1).range[1],
],
importSpecifiers
// Clone the importSpecifiers array to avoid mutating it
.slice()
// Sort the array into the desired order
.sort((specifierA, specifierB) => {
const aName =
getSortableName(specifierA);
const bName =
getSortableName(specifierB);
return aName > bName ? 1 : -1;
})
// Build a string out of the sorted list of import specifiers and the text between the originals
.reduce(
(sourceText, specifier, index) => {
const textAfterSpecifier =
index ===
importSpecifiers.length - 1
? ""
: sourceCode
.getText()
.slice(
importSpecifiers[
index
].range[1],
importSpecifiers[
index +
1
].range[0],
);
return (
sourceText +
sourceCode.getText(
specifier,
) +
textAfterSpecifier
);
},
"",
),
);
},
});
}
}
},
};
},
};

View File

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

View File

@@ -0,0 +1,7 @@
import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js";
import classPrivateFieldGet2 from "./classPrivateFieldGet2.js";
function _classPrivateFieldDestructureSet(e, t) {
var r = classPrivateFieldGet2(t, e);
return classApplyDescriptorDestructureSet(e, r);
}
export { _classPrivateFieldDestructureSet as default };

View File

@@ -0,0 +1,171 @@
/**
* @fileoverview Ensures that the results of typeof are compared against a valid string
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
defaultOptions: [
{
requireStringLiterals: false,
},
],
docs: {
description:
"Enforce comparing `typeof` expressions against valid strings",
recommended: true,
url: "https://eslint.org/docs/latest/rules/valid-typeof",
},
hasSuggestions: true,
schema: [
{
type: "object",
properties: {
requireStringLiterals: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
invalidValue: "Invalid typeof comparison value.",
notString: "Typeof comparisons should be to string literals.",
suggestString: 'Use `"{{type}}"` instead of `{{type}}`.',
},
},
create(context) {
const VALID_TYPES = new Set([
"symbol",
"undefined",
"object",
"boolean",
"number",
"string",
"function",
"bigint",
]),
OPERATORS = new Set(["==", "===", "!=", "!=="]);
const sourceCode = context.sourceCode;
const [{ requireStringLiterals }] = context.options;
let globalScope;
/**
* Checks whether the given node represents a reference to a global variable that is not declared in the source code.
* These identifiers will be allowed, as it is assumed that user has no control over the names of external global variables.
* @param {ASTNode} node `Identifier` node to check.
* @returns {boolean} `true` if the node is a reference to a global variable.
*/
function isReferenceToGlobalVariable(node) {
const variable = globalScope.set.get(node.name);
return (
variable &&
variable.defs.length === 0 &&
variable.references.some(ref => ref.identifier === node)
);
}
/**
* Determines whether a node is a typeof expression.
* @param {ASTNode} node The node
* @returns {boolean} `true` if the node is a typeof expression
*/
function isTypeofExpression(node) {
return (
node.type === "UnaryExpression" && node.operator === "typeof"
);
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
Program(node) {
globalScope = sourceCode.getScope(node);
},
UnaryExpression(node) {
if (isTypeofExpression(node)) {
const { parent } = node;
if (
parent.type === "BinaryExpression" &&
OPERATORS.has(parent.operator)
) {
const sibling =
parent.left === node ? parent.right : parent.left;
if (
sibling.type === "Literal" ||
astUtils.isStaticTemplateLiteral(sibling)
) {
const value =
sibling.type === "Literal"
? sibling.value
: sibling.quasis[0].value.cooked;
if (!VALID_TYPES.has(value)) {
context.report({
node: sibling,
messageId: "invalidValue",
});
}
} else if (
sibling.type === "Identifier" &&
sibling.name === "undefined" &&
isReferenceToGlobalVariable(sibling)
) {
context.report({
node: sibling,
messageId: requireStringLiterals
? "notString"
: "invalidValue",
suggest: [
{
messageId: "suggestString",
data: { type: "undefined" },
fix(fixer) {
return fixer.replaceText(
sibling,
'"undefined"',
);
},
},
],
});
} else if (
requireStringLiterals &&
!isTypeofExpression(sibling)
) {
context.report({
node: sibling,
messageId: "notString",
});
}
}
}
},
};
},
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"timing.d.ts","sourceRoot":"","sources":["../../src/api/timing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,kEAAkE;AAClE,eAAO,MAAM,uBAAuB,IAAI,CAAC;AAEzC,8DAA8D;AAC9D,MAAM,WAAW,aAAa;IAC1B,uCAAuC;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,WAAW,EAAE,MAAM,CAAC;IACpB,0DAA0D;IAC1D,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,aAAa,EAAE,MAAM,CAAC;IACtB,mFAAmF;IACnF,SAAS,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED,gEAAgE;AAChE,MAAM,WAAW,kBAAkB;IAC/B,mCAAmC;IACnC,YAAY,EAAE,MAAM,CAAC;IACrB,oDAAoD;IACpD,WAAW,EAAE,MAAM,CAAC;IACpB,yCAAyC;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,aAAa,EAAE,MAAM,CAAC;IACtB,2DAA2D;IAC3D,YAAY,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,mBAAmB,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAC1B;;;OAGG;IACH,kBAAkB,EAAE,MAAM,CAAC;IAC3B;;;;;;OAMG;IACH,YAAY,EAAE,MAAM,CAAC;CACxB;AAED,gEAAgE;AAChE,MAAM,WAAW,UAAU;IACvB,kEAAkE;IAClE,OAAO,EAAE,OAAO,CAAC;IACjB,oDAAoD;IACpD,MAAM,EAAE,kBAAkB,CAAC;IAC3B;;;OAGG;IACH,cAAc,EAAE,aAAa,EAAE,CAAC;CACnC;AAED,kEAAkE;AAClE,MAAM,WAAW,YAAY;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAChC,uCAAuC;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,oDAAoD;IACpD,gBAAgB,EAAE,MAAM,CAAC;IACzB,0EAA0E;IAC1E,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,6EAA6E;AAC7E,MAAM,WAAW,kBAAkB;IAC/B,wCAAwC;IACxC,YAAY,EAAE,MAAM,CAAC;IACrB,2DAA2D;IAC3D,qBAAqB,EAAE,MAAM,CAAC;CACjC;AAED;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC7B,wDAAwD;IACxD,OAAO,EAAE,OAAO,CAAC;IACjB,8DAA8D;IAC9D,MAAM,EAAE,kBAAkB,CAAC;IAC3B;;;OAGG;IACH,cAAc,EAAE,mBAAmB,EAAE,CAAC;CACzC;AAgBD,kFAAkF;AAClF,wBAAgB,kBAAkB,IAAI,UAAU,CAM/C;AAED,8EAA8E;AAC9E,wBAAgB,wBAAwB,IAAI,gBAAgB,CAM3D;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,gBAAgB,GAAG,UAAU,CA6B1F;AAED;;;GAGG;AACH,qBAAa,eAAe;IACxB,OAAO,CAAC,MAAM,CAA2C;IAGzD,OAAO,CAAC,IAAI,CAAuB;IACnC,OAAO,CAAC,IAAI,CAAK;IAEjB,+CAA+C;IAC/C,MAAM,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI;IAuBlC;;;;OAIG;IACH,qBAAqB,IAAI,IAAI;IAI7B;;;;OAIG;IACH,uBAAuB,CAAC,uBAAuB,EAAE,MAAM,GAAG,IAAI;IAK9D,8DAA8D;IAC9D,OAAO,IAAI,UAAU;IAYrB,gEAAgE;IAChE,KAAK,IAAI,IAAI;CAKhB"}

View File

@@ -0,0 +1,22 @@
Copyright (c) 2012, 2013 Thorsten Lorenz <thlorenz@gmx.de>
Copyright (c) 2012 James Halliday <mail@substack.net>
Copyright (c) 2009 Thomas Robinson <280north.com>
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,71 @@
/**
SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions.
Don't use them in a new protocol. What "weak" means:
- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
- No practical pre-image attacks (only theoretical, 2^123.4)
- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151
* @module
*/
import { HashMD } from './_md.ts';
import { type CHash } from './utils.ts';
/** SHA1 legacy hash class. */
export declare class SHA1 extends HashMD<SHA1> {
private A;
private B;
private C;
private D;
private E;
constructor();
protected get(): [number, number, number, number, number];
protected set(A: number, B: number, C: number, D: number, E: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
/** SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */
export declare const sha1: CHash;
/** MD5 legacy hash class. */
export declare class MD5 extends HashMD<MD5> {
private A;
private B;
private C;
private D;
constructor();
protected get(): [number, number, number, number];
protected set(A: number, B: number, C: number, D: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
/**
* MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
* MD5 architecture is similar to SHA1, with some differences:
* - Reduced output length: 16 bytes (128 bit) instead of 20
* - 64 rounds, instead of 80
* - Little-endian: could be faster, but will require more code
* - Non-linear index selection: huge speed-up for unroll
* - Per round constants: more memory accesses, additional speed-up for unroll
*/
export declare const md5: CHash;
export declare class RIPEMD160 extends HashMD<RIPEMD160> {
private h0;
private h1;
private h2;
private h3;
private h4;
constructor();
protected get(): [number, number, number, number, number];
protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void;
protected process(view: DataView, offset: number): void;
protected roundClean(): void;
destroy(): void;
}
/**
* RIPEMD-160 - a legacy hash function from 1990s.
* * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
* * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
*/
export declare const ripemd160: CHash;
//# sourceMappingURL=legacy.d.ts.map