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,18 @@
"use strict";
function _is_native_reflect_construct() {
// Since Reflect.construct can't be properly polyfilled, some
// implementations (e.g. core-js@2) don't set the correct internal slots.
// Those polyfills don't allow us to subclass built-ins, so we need to
// use our fallback implementation.
try {
// If the internal slots aren't set, this throws an error similar to
// TypeError: this is not a Boolean object.
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
} catch (_) {}
return (exports._ = _is_native_reflect_construct = function() {
return !!result;
})();
}
exports._ = _is_native_reflect_construct;

View File

@@ -0,0 +1,13 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
test("type inference", () => {
const schema = z.string().array();
expectTypeOf<z.infer<typeof schema>>().toEqualTypeOf<string[]>();
});
test("url regex", () => {
expect((z.url({ hostname: /^example\.com$/ }).safeParse("http://example.org/").error?.issues[0] as any).pattern).toBe(
"^example\\.com$"
);
});

View File

@@ -0,0 +1,111 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "문자", verb: "to have" },
file: { unit: "바이트", verb: "to have" },
array: { unit: "개", verb: "to have" },
set: { unit: "개", verb: "to have" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "입력",
email: "이메일 주소",
url: "URL",
emoji: "이모지",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO 날짜시간",
date: "ISO 날짜",
time: "ISO 시간",
duration: "ISO 기간",
ipv4: "IPv4 주소",
ipv6: "IPv6 주소",
cidrv4: "IPv4 범위",
cidrv6: "IPv6 범위",
base64: "base64 인코딩 문자열",
base64url: "base64url 인코딩 문자열",
json_string: "JSON 문자열",
e164: "E.164 번호",
jwt: "JWT",
template_literal: "입력",
};
const TypeDictionary = {
nan: "NaN",
};
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 `잘못된 입력: 예상 타입은 instanceof ${issue.expected}, 받은 타입은 ${received}입니다`;
}
return `잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`;
}
case "invalid_value":
if (issue.values.length === 1)
return `잘못된 입력: 값은 ${util.stringifyPrimitive(issue.values[0])} 이어야 합니다`;
return `잘못된 옵션: ${util.joinValues(issue.values, "또는 ")} 중 하나여야 합니다`;
case "too_big": {
const adj = issue.inclusive ? "이하" : "미만";
const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다";
const sizing = getSizing(issue.origin);
const unit = sizing?.unit ?? "요소";
if (sizing)
return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`;
return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`;
}
case "too_small": {
const adj = issue.inclusive ? "이상" : "초과";
const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다";
const sizing = getSizing(issue.origin);
const unit = sizing?.unit ?? "요소";
if (sizing) {
return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`;
}
return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") {
return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;
}
if (_issue.format === "ends_with")
return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;
if (_issue.format === "includes")
return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;
if (_issue.format === "regex")
return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;
return `잘못된 ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`;
case "unrecognized_keys":
return `인식할 수 없는 키: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `잘못된 키: ${issue.origin}`;
case "invalid_union":
return `잘못된 입력`;
case "invalid_element":
return `잘못된 값: ${issue.origin}`;
default:
return `잘못된 입력`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,21 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 15
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- "discussion"
- "feature request"
- "bug"
- "help wanted"
- "plugin suggestion"
- "good first issue"
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@@ -0,0 +1,8 @@
import { createWriteStream } from 'node:fs'
import { once } from 'node:events'
export default async function run (opts) {
const stream = createWriteStream(opts.destination)
await once(stream, 'open')
return stream
}

View File

@@ -0,0 +1,110 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@typescript-eslint/utils");
const util_1 = require("../util");
exports.default = (0, util_1.createRule)({
name: 'triple-slash-reference',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow certain triple slash directives in favor of ES6-style import declarations',
recommended: 'recommended',
},
messages: {
tripleSlashReference: 'Do not use a triple slash reference for {{module}}, use `import` style instead.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
lib: {
type: 'string',
description: 'What to enforce for `/// <reference lib="..." />` references.',
enum: ['always', 'never'],
},
path: {
type: 'string',
description: 'What to enforce for `/// <reference path="..." />` references.',
enum: ['always', 'never'],
},
types: {
type: 'string',
description: 'What to enforce for `/// <reference types="..." />` references.',
enum: ['always', 'never', 'prefer-import'],
},
},
},
],
},
defaultOptions: [
{
lib: 'always',
path: 'never',
types: 'prefer-import',
},
],
create(context, [{ lib, path, types }]) {
let programNode;
const references = [];
function hasMatchingReference(source) {
references.forEach(reference => {
if (reference.importName === source.value) {
context.report({
node: reference.comment,
messageId: 'tripleSlashReference',
data: {
module: reference.importName,
},
});
}
});
}
return {
ImportDeclaration(node) {
if (programNode) {
hasMatchingReference(node.source);
}
},
Program(node) {
if (lib === 'always' && path === 'always' && types === 'always') {
return;
}
programNode = node;
const referenceRegExp = /^\/\s*<reference\s*(types|path|lib)\s*=\s*["|'](.*)["|']/;
const commentsBefore = context.sourceCode.getCommentsBefore(programNode);
commentsBefore.forEach(comment => {
if (comment.type !== utils_1.AST_TOKEN_TYPES.Line) {
return;
}
const referenceResult = referenceRegExp.exec(comment.value);
if (referenceResult) {
if ((referenceResult[1] === 'types' && types === 'never') ||
(referenceResult[1] === 'path' && path === 'never') ||
(referenceResult[1] === 'lib' && lib === 'never')) {
context.report({
node: comment,
messageId: 'tripleSlashReference',
data: {
module: referenceResult[2],
},
});
return;
}
if (referenceResult[1] === 'types' && types === 'prefer-import') {
references.push({ comment, importName: referenceResult[2] });
}
}
});
},
TSImportEqualsDeclaration(node) {
if (programNode) {
const reference = node.moduleReference;
if (reference.type === utils_1.AST_NODE_TYPES.TSExternalModuleReference) {
hasMatchingReference(reference.expression);
}
}
},
};
},
});

View File

@@ -0,0 +1,9 @@
// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT.
export var ModuleDetectionKind;
(function (ModuleDetectionKind) {
ModuleDetectionKind[ModuleDetectionKind["None"] = 0] = "None";
ModuleDetectionKind[ModuleDetectionKind["Auto"] = 1] = "Auto";
ModuleDetectionKind[ModuleDetectionKind["Legacy"] = 2] = "Legacy";
ModuleDetectionKind[ModuleDetectionKind["Force"] = 3] = "Force";
})(ModuleDetectionKind || (ModuleDetectionKind = {}));
//# sourceMappingURL=moduleDetectionKind.js.map

View File

@@ -0,0 +1,60 @@
interface AfterSuiteRunMeta {
coverage?: unknown;
testFiles: string[];
environment: string;
projectName?: string;
}
interface UserConsoleLog {
content: string;
origin?: string;
browser?: boolean;
type: "stdout" | "stderr";
taskId?: string;
time: number;
size: number;
}
interface ModuleGraphData {
graph: Record<string, string[]>;
externalized: string[];
inlined: string[];
}
interface ProvidedContext {}
interface ResolveFunctionResult {
id: string;
file: string;
url: string;
}
interface FetchCachedFileSystemResult {
cached: true;
tmp: string;
id: string;
file: string | null;
url: string;
invalidate: boolean;
}
type LabelColor = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white";
interface AsyncLeak {
filename: string;
projectName: string;
stack: string;
type: string;
}
interface OTELCarrier {
traceparent?: string;
tracestate?: string;
}
interface TracesOptions {
enabled: boolean;
watchMode?: boolean;
sdkPath?: string;
tracerName?: string;
}
declare class Traces {
#private;
constructor(options: TracesOptions);
isEnabled(): boolean;
}
export { Traces as T };
export type { AsyncLeak as A, FetchCachedFileSystemResult as F, LabelColor as L, ModuleGraphData as M, OTELCarrier as O, ProvidedContext as P, ResolveFunctionResult as R, UserConsoleLog as U, AfterSuiteRunMeta as a };

View File

@@ -0,0 +1 @@
{"version":3,"file":"blake1.d.ts","sourceRoot":"","sources":["src/blake1.ts"],"names":[],"mappings":"AA4BA,OAAO,EAGO,IAAI,EAChB,KAAK,MAAM,EAAE,KAAK,KAAK,EACxB,MAAM,YAAY,CAAC;AAEpB,4CAA4C;AAC5C,MAAM,MAAM,SAAS,GAAG;IACtB,IAAI,CAAC,EAAE,UAAU,CAAC;CACnB,CAAC;AAKF,uBAAe,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IACxD,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,S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;AAC/B,eAAO,MAAM,QAAQ,EAAE,MAEtB,CAAC;AACF,+BAA+B;AAC/B,eAAO,MAAM,QAAQ,EAAE,MAEtB,CAAC"}

View File

@@ -0,0 +1,699 @@
/**
* @fileoverview The main file for the humanfs package.
* @author Nicholas C. Zakas
*/
/* global URL, TextDecoder, TextEncoder */
//-----------------------------------------------------------------------------
// Types
//-----------------------------------------------------------------------------
/** @typedef {import("@humanfs/types").HfsImpl} HfsImpl */
/** @typedef {import("@humanfs/types").HfsDirectoryEntry} HfsDirectoryEntry */
/** @typedef {import("@humanfs/types").HfsWalkEntry} HfsWalkEntry */
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const decoder = new TextDecoder();
const encoder = new TextEncoder();
/**
* Error to represent when a method is missing on an impl.
*/
export class NoSuchMethodError extends Error {
/**
* Creates a new instance.
* @param {string} methodName The name of the method that was missing.
*/
constructor(methodName) {
super(`Method "${methodName}" does not exist on impl.`);
}
}
/**
* Error to represent when a method is not supported on an impl. This happens
* when a method on `Hfs` is called with one name and the corresponding method
* on the impl has a different name. (Example: `text()` and `bytes()`.)
*/
export class MethodNotSupportedError extends Error {
/**
* Creates a new instance.
* @param {string} methodName The name of the method that was missing.
*/
constructor(methodName) {
super(`Method "${methodName}" is not supported on this impl.`);
}
}
/**
* Error to represent when an impl is already set.
*/
export class ImplAlreadySetError extends Error {
/**
* Creates a new instance.
*/
constructor() {
super(`Implementation already set.`);
}
}
/**
* Asserts that the given path is a valid file path.
* @param {any} fileOrDirPath The path to check.
* @returns {void}
* @throws {TypeError} When the path is not a non-empty string.
*/
function assertValidFileOrDirPath(fileOrDirPath) {
if (
!fileOrDirPath ||
(!(fileOrDirPath instanceof URL) && typeof fileOrDirPath !== "string")
) {
throw new TypeError("Path must be a non-empty string or URL.");
}
}
/**
* Asserts that the given file contents are valid.
* @param {any} contents The contents to check.
* @returns {void}
* @throws {TypeError} When the contents are not a string or ArrayBuffer.
*/
function assertValidFileContents(contents) {
if (
typeof contents !== "string" &&
!(contents instanceof ArrayBuffer) &&
!ArrayBuffer.isView(contents)
) {
throw new TypeError(
"File contents must be a string, ArrayBuffer, or ArrayBuffer view.",
);
}
}
/**
* Converts the given contents to Uint8Array.
* @param {any} contents The data to convert.
* @returns {Uint8Array} The converted Uint8Array.
* @throws {TypeError} When the contents are not a string or ArrayBuffer.
*/
function toUint8Array(contents) {
if (contents instanceof Uint8Array) {
return contents;
}
if (typeof contents === "string") {
return encoder.encode(contents);
}
if (contents instanceof ArrayBuffer) {
return new Uint8Array(contents);
}
if (ArrayBuffer.isView(contents)) {
const bytes = contents.buffer.slice(
contents.byteOffset,
contents.byteOffset + contents.byteLength,
);
return new Uint8Array(bytes);
}
throw new TypeError(
"Invalid contents type. Expected string or ArrayBuffer.",
);
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A class representing a log entry.
*/
export class LogEntry {
/**
* The type of log entry.
* @type {string}
*/
type;
/**
* The data associated with the log entry.
* @type {any}
*/
data;
/**
* The time at which the log entry was created.
* @type {number}
*/
timestamp = Date.now();
/**
* Creates a new instance.
* @param {string} type The type of log entry.
* @param {any} [data] The data associated with the log entry.
*/
constructor(type, data) {
this.type = type;
this.data = data;
}
}
/**
* A class representing a file system utility library.
* @implements {HfsImpl}
*/
export class Hfs {
/**
* The base implementation for this instance.
* @type {HfsImpl}
*/
#baseImpl;
/**
* The current implementation for this instance.
* @type {HfsImpl}
*/
#impl;
/**
* A map of log names to their corresponding entries.
* @type {Map<string,Array<LogEntry>>}
*/
#logs = new Map();
/**
* Creates a new instance.
* @param {object} options The options for the instance.
* @param {HfsImpl} options.impl The implementation to use.
*/
constructor({ impl }) {
this.#baseImpl = impl;
this.#impl = impl;
}
/**
* Logs an entry onto all currently open logs.
* @param {string} methodName The name of the method being called.
* @param {...*} args The arguments to the method.
* @returns {void}
*/
#log(methodName, ...args) {
for (const logs of this.#logs.values()) {
logs.push(new LogEntry("call", { methodName, args }));
}
}
/**
* Starts a new log with the given name.
* @param {string} name The name of the log to start;
* @returns {void}
* @throws {Error} When the log already exists.
* @throws {TypeError} When the name is not a non-empty string.
*/
logStart(name) {
if (!name || typeof name !== "string") {
throw new TypeError("Log name must be a non-empty string.");
}
if (this.#logs.has(name)) {
throw new Error(`Log "${name}" already exists.`);
}
this.#logs.set(name, []);
}
/**
* Ends a log with the given name and returns the entries.
* @param {string} name The name of the log to end.
* @returns {Array<LogEntry>} The entries in the log.
* @throws {Error} When the log does not exist.
*/
logEnd(name) {
if (this.#logs.has(name)) {
const logs = this.#logs.get(name);
this.#logs.delete(name);
return logs;
}
throw new Error(`Log "${name}" does not exist.`);
}
/**
* Determines if the current implementation is the base implementation.
* @returns {boolean} True if the current implementation is the base implementation.
*/
isBaseImpl() {
return this.#impl === this.#baseImpl;
}
/**
* Sets the implementation for this instance.
* @param {object} impl The implementation to use.
* @returns {void}
*/
setImpl(impl) {
this.#log("implSet", impl);
if (this.#impl !== this.#baseImpl) {
throw new ImplAlreadySetError();
}
this.#impl = impl;
}
/**
* Resets the implementation for this instance back to its original.
* @returns {void}
*/
resetImpl() {
this.#log("implReset");
this.#impl = this.#baseImpl;
}
/**
* Asserts that the given method exists on the current implementation.
* @param {string} methodName The name of the method to check.
* @returns {void}
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
*/
#assertImplMethod(methodName) {
if (typeof this.#impl[methodName] !== "function") {
throw new NoSuchMethodError(methodName);
}
}
/**
* Asserts that the given method exists on the current implementation, and if not,
* throws an error with a different method name.
* @param {string} methodName The name of the method to check.
* @param {string} targetMethodName The name of the method that should be reported
* as an error when methodName does not exist.
* @returns {void}
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
*/
#assertImplMethodAlt(methodName, targetMethodName) {
if (typeof this.#impl[methodName] !== "function") {
throw new MethodNotSupportedError(targetMethodName);
}
}
/**
* Calls the given method on the current implementation.
* @param {string} methodName The name of the method to call.
* @param {...any} args The arguments to the method.
* @returns {any} The return value from the method.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
*/
#callImplMethod(methodName, ...args) {
this.#log(methodName, ...args);
this.#assertImplMethod(methodName);
return this.#impl[methodName](...args);
}
/**
* Calls the given method on the current implementation and doesn't log the call.
* @param {string} methodName The name of the method to call.
* @param {...any} args The arguments to the method.
* @returns {any} The return value from the method.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
*/
#callImplMethodWithoutLog(methodName, ...args) {
this.#assertImplMethod(methodName);
return this.#impl[methodName](...args);
}
/**
* Calls the given method on the current implementation but logs a different method name.
* @param {string} methodName The name of the method to call.
* @param {string} targetMethodName The name of the method to log.
* @param {...any} args The arguments to the method.
* @returns {any} The return value from the method.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
*/
#callImplMethodAlt(methodName, targetMethodName, ...args) {
this.#log(targetMethodName, ...args);
this.#assertImplMethodAlt(methodName, targetMethodName);
return this.#impl[methodName](...args);
}
/**
* Reads the given file and returns the contents as text. Assumes UTF-8 encoding.
* @param {string|URL} filePath The file to read.
* @returns {Promise<string|undefined>} The contents of the file.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
async text(filePath) {
assertValidFileOrDirPath(filePath);
const result = await this.#callImplMethodAlt("bytes", "text", filePath);
return result ? decoder.decode(result) : undefined;
}
/**
* Reads the given file and returns the contents as JSON. Assumes UTF-8 encoding.
* @param {string|URL} filePath The file to read.
* @returns {Promise<any|undefined>} The contents of the file as JSON.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {SyntaxError} When the file contents are not valid JSON.
* @throws {TypeError} When the file path is not a non-empty string.
*/
async json(filePath) {
assertValidFileOrDirPath(filePath);
const result = await this.#callImplMethodAlt("bytes", "json", filePath);
return result ? JSON.parse(decoder.decode(result)) : undefined;
}
/**
* Reads the given file and returns the contents as an ArrayBuffer.
* @param {string|URL} filePath The file to read.
* @returns {Promise<ArrayBuffer|undefined>} The contents of the file as an ArrayBuffer.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
* @deprecated Use bytes() instead.
*/
async arrayBuffer(filePath) {
assertValidFileOrDirPath(filePath);
const result = await this.#callImplMethodAlt(
"bytes",
"arrayBuffer",
filePath,
);
return result?.buffer;
}
/**
* Reads the given file and returns the contents as an Uint8Array.
* @param {string|URL} filePath The file to read.
* @returns {Promise<Uint8Array|undefined>} The contents of the file as an Uint8Array.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
async bytes(filePath) {
assertValidFileOrDirPath(filePath);
return this.#callImplMethod("bytes", filePath);
}
/**
* Writes the given data to the given file. Creates any necessary directories along the way.
* If the data is a string, UTF-8 encoding is used.
* @param {string|URL} filePath The file to write.
* @param {string|ArrayBuffer|ArrayBufferView} contents The data to write.
* @returns {Promise<void>} A promise that resolves when the file is written.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
async write(filePath, contents) {
assertValidFileOrDirPath(filePath);
assertValidFileContents(contents);
this.#log("write", filePath, contents);
let value = toUint8Array(contents);
return this.#callImplMethodWithoutLog("write", filePath, value);
}
/**
* Appends the given data to the given file. Creates any necessary directories along the way.
* If the data is a string, UTF-8 encoding is used.
* @param {string|URL} filePath The file to append to.
* @param {string|ArrayBuffer|ArrayBufferView} contents The data to append.
* @returns {Promise<void>} A promise that resolves when the file is appended to.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
* @throws {TypeError} When the file contents are not a string or ArrayBuffer.
* @throws {Error} When the file cannot be appended to.
*/
async append(filePath, contents) {
assertValidFileOrDirPath(filePath);
assertValidFileContents(contents);
this.#log("append", filePath, contents);
let value = toUint8Array(contents);
return this.#callImplMethodWithoutLog("append", filePath, value);
}
/**
* Determines if the given file exists.
* @param {string|URL} filePath The file to check.
* @returns {Promise<boolean>} True if the file exists.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
async isFile(filePath) {
assertValidFileOrDirPath(filePath);
return this.#callImplMethod("isFile", filePath);
}
/**
* Determines if the given directory exists.
* @param {string|URL} dirPath The directory to check.
* @returns {Promise<boolean>} True if the directory exists.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the directory path is not a non-empty string.
*/
async isDirectory(dirPath) {
assertValidFileOrDirPath(dirPath);
return this.#callImplMethod("isDirectory", dirPath);
}
/**
* Creates the given directory.
* @param {string|URL} dirPath The directory to create.
* @returns {Promise<void>} A promise that resolves when the directory is created.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the directory path is not a non-empty string.
*/
async createDirectory(dirPath) {
assertValidFileOrDirPath(dirPath);
return this.#callImplMethod("createDirectory", dirPath);
}
/**
* Deletes the given file or empty directory.
* @param {string|URL} filePath The file to delete.
* @returns {Promise<boolean>} A promise that resolves when the file or
* directory is deleted, true if the file or directory is deleted, false
* if the file or directory does not exist.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the file path is not a non-empty string.
*/
async delete(filePath) {
assertValidFileOrDirPath(filePath);
return this.#callImplMethod("delete", filePath);
}
/**
* Deletes the given file or directory recursively.
* @param {string|URL} dirPath The directory to delete.
* @returns {Promise<boolean>} A promise that resolves when the file or
* directory is deleted, true if the file or directory is deleted, false
* if the file or directory does not exist.
* @throws {NoSuchMethodError} When the method does not exist on the current implementation.
* @throws {TypeError} When the directory path is not a non-empty string.
*/
async deleteAll(dirPath) {
assertValidFileOrDirPath(dirPath);
return this.#callImplMethod("deleteAll", dirPath);
}
/**
* Returns a list of directory entries for the given path.
* @param {string|URL} dirPath The path to the directory to read.
* @returns {AsyncIterable<HfsDirectoryEntry>} A promise that resolves with the
* directory entries.
* @throws {TypeError} If the directory path is not a string or URL.
* @throws {Error} If the directory cannot be read.
*/
async *list(dirPath) {
assertValidFileOrDirPath(dirPath);
yield* await this.#callImplMethod("list", dirPath);
}
/**
* Walks a directory using a depth-first traversal and returns the entries
* from the traversal.
* @param {string|URL} dirPath The path to the directory to walk.
* @param {Object} [options] The options for the walk.
* @param {(entry:HfsWalkEntry) => Promise<boolean>|boolean} [options.directoryFilter] A filter function to determine
* if a directory's entries should be included in the walk.
* @param {(entry:HfsWalkEntry) => Promise<boolean>|boolean} [options.entryFilter] A filter function to determine if
* an entry should be included in the walk.
* @returns {AsyncIterable<HfsWalkEntry>} A promise that resolves with the
* directory entries.
* @throws {TypeError} If the directory path is not a string or URL.
* @throws {Error} If the directory cannot be read.
*/
async *walk(
dirPath,
{ directoryFilter = () => true, entryFilter = () => true } = {},
) {
assertValidFileOrDirPath(dirPath);
this.#log("walk", dirPath, { directoryFilter, entryFilter });
// inner function for recursion without additional logging
const walk = async function* (
dirPath,
{ directoryFilter, entryFilter, parentPath = "", depth = 1 },
) {
let dirEntries;
try {
dirEntries = await this.#callImplMethodWithoutLog(
"list",
dirPath,
);
} catch (error) {
// if the directory does not exist then return an empty array
if (error.code === "ENOENT") {
return;
}
// otherwise, rethrow the error
throw error;
}
for await (const listEntry of dirEntries) {
const walkEntry = {
path: listEntry.name,
depth,
...listEntry,
};
if (parentPath) {
walkEntry.path = `${parentPath}/${walkEntry.path}`;
}
// first emit the entry but only if the entry filter returns true
let shouldEmitEntry = entryFilter(walkEntry);
if (shouldEmitEntry.then) {
shouldEmitEntry = await shouldEmitEntry;
}
if (shouldEmitEntry) {
yield walkEntry;
}
// if it's a directory then yield the entry and walk the directory
if (listEntry.isDirectory) {
// if the directory filter returns false, skip the directory
let shouldWalkDirectory = directoryFilter(walkEntry);
if (shouldWalkDirectory.then) {
shouldWalkDirectory = await shouldWalkDirectory;
}
if (!shouldWalkDirectory) {
continue;
}
// make sure there's a trailing slash on the directory path before appending
const directoryPath =
dirPath instanceof URL
? new URL(
listEntry.name,
dirPath.href.endsWith("/")
? dirPath.href
: `${dirPath.href}/`,
)
: `${dirPath.endsWith("/") ? dirPath : `${dirPath}/`}${listEntry.name}`;
yield* walk(directoryPath, {
directoryFilter,
entryFilter,
parentPath: walkEntry.path,
depth: depth + 1,
});
}
}
}.bind(this);
yield* walk(dirPath, { directoryFilter, entryFilter });
}
/**
* Returns the size of the given file.
* @param {string|URL} filePath The path to the file to read.
* @returns {Promise<number>} A promise that resolves with the size of the file.
* @throws {TypeError} If the file path is not a string or URL.
* @throws {Error} If the file cannot be read.
*/
async size(filePath) {
assertValidFileOrDirPath(filePath);
return this.#callImplMethod("size", filePath);
}
/**
* Returns the last modified timestamp of the given file or directory.
* @param {string|URL} fileOrDirPath The path to the file or directory.
* @returns {Promise<Date|undefined>} A promise that resolves with the last modified date
* or undefined if the file or directory does not exist.
* @throws {TypeError} If the path is not a string or URL.
*/
async lastModified(fileOrDirPath) {
assertValidFileOrDirPath(fileOrDirPath);
return this.#callImplMethod("lastModified", fileOrDirPath);
}
/**
* Copys a file from one location to another.
* @param {string|URL} source The path to the file to copy.
* @param {string|URL} destination The path to the new file.
* @returns {Promise<void>} A promise that resolves when the file is copied.
* @throws {TypeError} If the file path is not a string or URL.
* @throws {Error} If the file cannot be copied.
*/
async copy(source, destination) {
assertValidFileOrDirPath(source);
assertValidFileOrDirPath(destination);
return this.#callImplMethod("copy", source, destination);
}
/**
* Copies a file or directory from one location to another.
* @param {string|URL} source The path to the file or directory to copy.
* @param {string|URL} destination The path to copy the file or directory to.
* @returns {Promise<void>} A promise that resolves when the file or directory is
* copied.
* @throws {TypeError} If the directory path is not a string or URL.
* @throws {Error} If the directory cannot be copied.
*/
async copyAll(source, destination) {
assertValidFileOrDirPath(source);
assertValidFileOrDirPath(destination);
return this.#callImplMethod("copyAll", source, destination);
}
/**
* Moves a file from the source path to the destination path.
* @param {string|URL} source The location of the file to move.
* @param {string|URL} destination The destination of the file to move.
* @returns {Promise<void>} A promise that resolves when the move is complete.
* @throws {TypeError} If the file or directory paths are not strings.
* @throws {Error} If the file or directory cannot be moved.
*/
async move(source, destination) {
assertValidFileOrDirPath(source);
assertValidFileOrDirPath(destination);
return this.#callImplMethod("move", source, destination);
}
/**
* Moves a file or directory from one location to another.
* @param {string|URL} source The path to the file or directory to move.
* @param {string|URL} destination The path to move the file or directory to.
* @returns {Promise<void>} A promise that resolves when the file or directory is
* moved.
* @throws {TypeError} If the source is not a string or URL.
* @throws {TypeError} If the destination is not a string or URL.
* @throws {Error} If the file or directory cannot be moved.
*/
async moveAll(source, destination) {
assertValidFileOrDirPath(source);
assertValidFileOrDirPath(destination);
return this.#callImplMethod("moveAll", source, destination);
}
}

View File

@@ -0,0 +1,743 @@
<h1 align="center">Picomatch</h1>
<p align="center">
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/v/picomatch.svg" alt="version">
</a>
<a href="https://github.com/micromatch/picomatch/actions/workflows/test.yml">
<img src="https://github.com/micromatch/picomatch/actions/workflows/test.yml/badge.svg?branch=master" alt="test status">
</a>
<a href="https://coveralls.io/github/micromatch/picomatch">
<img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status">
</a>
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/dm/picomatch" alt="downloads">
</a>
</p>
<br>
<br>
<p align="center">
<strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br>
<em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em>
</p>
<br>
<br>
## Why picomatch?
* **Lightweight** - No dependencies
* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps)
* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files)
* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes.
* **Well tested** - Thousands of unit tests
See the [library comparison](#library-comparisons) to other libraries.
<br>
<br>
## Table of Contents
<details><summary> Click to expand </summary>
- [Install](#install)
- [Usage](#usage)
- [API](#api)
* [picomatch](#picomatch)
* [.test](#test)
* [.matchBase](#matchbase)
* [.isMatch](#ismatch)
* [.parse](#parse)
* [.scan](#scan)
* [.compileRe](#compilere)
* [.makeRe](#makere)
* [.toRegex](#toregex)
- [Options](#options)
* [Picomatch options](#picomatch-options)
* [Scan Options](#scan-options)
* [Options Examples](#options-examples)
- [Globbing features](#globbing-features)
* [Basic globbing](#basic-globbing)
* [Advanced globbing](#advanced-globbing)
* [Braces](#braces)
* [Matching special characters as literals](#matching-special-characters-as-literals)
- [Library Comparisons](#library-comparisons)
- [Benchmarks](#benchmarks)
- [Philosophies](#philosophies)
- [About](#about)
* [Author](#author)
* [License](#license)
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
</details>
<br>
<br>
## Install
Install with [npm](https://www.npmjs.com/):
```sh
npm install --save picomatch
```
<br>
## Usage
The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
```js
const pm = require('picomatch');
const isMatch = pm('*.js');
console.log(isMatch('abcd')); //=> false
console.log(isMatch('a.js')); //=> true
console.log(isMatch('a.md')); //=> false
console.log(isMatch('a/b.js')); //=> false
```
<br>
## API
### [picomatch](lib/picomatch.js#L43)
Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information.
**Params**
* `globs` **{String|Array}**: One or more glob patterns.
* `options` **{Object=}**
* `returns` **{Function=}**: Returns a matcher function.
**Example**
```js
const picomatch = require('picomatch');
// picomatch(glob[, options]);
const isMatch = picomatch('*.!(*a)');
console.log(isMatch('a.a')); //=> false
console.log(isMatch('a.b')); //=> true
// For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection.
const picomatch = require('picomatch/posix');
// the same API, defaulting to posix paths
const isMatch = picomatch('a/*');
console.log(isMatch('a\\b')); //=> false
console.log(isMatch('a/b')); //=> true
// you can still configure the matcher function to accept windows paths
const isMatch = picomatch('a/*', { options: windows });
console.log(isMatch('a\\b')); //=> true
console.log(isMatch('a/b')); //=> true
```
### [.test](lib/picomatch.js#L128)
Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string.
**Params**
* `input` **{String}**: String to test.
* `regex` **{RegExp}**
* `returns` **{Object}**: Returns an object with matching info.
**Example**
```js
const picomatch = require('picomatch');
// picomatch.test(input, regex[, options]);
console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
```
### [.matchBase](lib/picomatch.js#L172)
Match the basename of a filepath.
**Params**
* `input` **{String}**: String to test.
* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe).
* `returns` **{Boolean}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.matchBase(input, glob[, options]);
console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
```
### [.isMatch](lib/picomatch.js#L194)
Returns true if **any** of the given glob `patterns` match the specified `string`.
**Params**
* **{String|Array}**: str The string to test.
* **{String|Array}**: patterns One or more glob patterns to use for matching.
* **{Object}**: See available [options](#options).
* `returns` **{Boolean}**: Returns true if any patterns match `str`
**Example**
```js
const picomatch = require('picomatch');
// picomatch.isMatch(string, patterns[, options]);
console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
```
### [.parse](lib/picomatch.js#L210)
Parse a glob pattern to create the source string for a regular expression.
**Params**
* `pattern` **{String}**
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string.
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.parse(pattern[, options]);
```
### [.scan](lib/picomatch.js#L242)
Scan a glob pattern to separate the pattern into segments.
**Params**
* `input` **{String}**: Glob pattern to scan.
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with
**Example**
```js
const picomatch = require('picomatch');
// picomatch.scan(input[, options]);
const result = picomatch.scan('!./foo/*.js');
console.log(result);
{ prefix: '!./',
input: '!./foo/*.js',
start: 3,
base: 'foo',
glob: '*.js',
isBrace: false,
isBracket: false,
isGlob: true,
isExtglob: false,
isGlobstar: false,
negated: true }
```
### [.compileRe](lib/picomatch.js#L264)
Compile a regular expression from the `state` object returned by the [parse()](#parse) method.
**Params**
* `state` **{Object}**
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser.
* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* `returns` **{RegExp}**
**Example**
```js
const picomatch = require('picomatch');
const state = picomatch.parse('*.js');
// picomatch.compileRe(state[, options]);
console.log(picomatch.compileRe(state));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
### [.makeRe](lib/picomatch.js#L305)
Create a regular expression from a parsed glob pattern.
**Params**
* `state` **{String}**: The object returned from the `.parse` method.
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* `returns` **{RegExp}**: Returns a regex created from the given pattern.
**Example**
```js
const picomatch = require('picomatch');
// picomatch.makeRe(state[, options]);
const result = picomatch.makeRe('*.js');
console.log(result);
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
### [.toRegex](lib/picomatch.js#L340)
Create a regular expression from the given regex source string.
**Params**
* `source` **{String}**: Regular expression source string.
* `options` **{Object}**
* `returns` **{RegExp}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.toRegex(source[, options]);
const { output } = picomatch.parse('*.js');
console.log(picomatch.toRegex(output));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
<br>
## Options
### Picomatch options
The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. |
| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true |
| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. |
| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
| `matchBase` | `boolean` | `false` | Alias for `basename` |
| `maxLength` | `number` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
| `maxExtglobRecursion` | `number\|boolean` | `0` | Limit nested quantified extglobs and other risky repeated extglob forms. When the limit is exceeded, the extglob is treated as a literal string instead of being compiled to regex. Set to `false` to disable this safeguard. |
| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. |
| `noext` | `boolean` | `false` | Alias for `noextglob` |
| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) |
| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). |
| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. |
| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
| `windows` | `boolean` | `false` | Also accept backslashes as the path separator. |
### Scan Options
In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true |
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.scan('!./foo/*.js', { tokens: true });
console.log(result);
// {
// prefix: '!./',
// input: '!./foo/*.js',
// start: 3,
// base: 'foo',
// glob: '*.js',
// isBrace: false,
// isBracket: false,
// isGlob: true,
// isExtglob: false,
// isGlobstar: false,
// negated: true,
// maxDepth: 2,
// tokens: [
// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
// { value: 'foo', depth: 1, isGlob: false },
// { value: '*.js', depth: 1, isGlob: true }
// ],
// slashes: [ 2, 6 ],
// parts: [ 'foo', '*.js' ]
// }
```
<br>
### Options Examples
#### options.expandRange
**Type**: `function`
**Default**: `undefined`
Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
**Example**
The following example shows how to create a glob that matches a folder
```js
const fill = require('fill-range');
const regex = pm.makeRe('foo/{01..25}/bar', {
expandRange(a, b) {
return `(${fill(a, b, { toRegex: true })})`;
}
});
console.log(regex);
//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
console.log(regex.test('foo/00/bar')) // false
console.log(regex.test('foo/01/bar')) // true
console.log(regex.test('foo/10/bar')) // true
console.log(regex.test('foo/22/bar')) // true
console.log(regex.test('foo/25/bar')) // true
console.log(regex.test('foo/26/bar')) // false
```
#### options.format
**Type**: `function`
**Default**: `undefined`
Custom function for formatting strings before they're matched.
**Example**
```js
// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')); //=> true
```
#### options.onMatch
```js
const onMatch = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onMatch });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onIgnore
```js
const onIgnore = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onResult
```js
const onResult = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
<br>
<br>
## Globbing features
* [Basic globbing](#basic-globbing) (Wildcard matching)
* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching)
### Basic globbing
| **Character** | **Description** |
| --- | --- |
| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. |
| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` with the `windows` option) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. |
| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. |
| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. |
#### Matching behavior vs. Bash
Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`.
* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`.
<br>
### Advanced globbing
* [extglobs](#extglobs)
* [POSIX brackets](#posix-brackets)
* [Braces](#brace-expansion)
#### Extglobs
| **Pattern** | **Description** |
| --- | --- |
| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` |
| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` |
| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` |
| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` |
| `!(pattern)` | Match _anything but_ `pattern` |
**Examples**
```js
const pm = require('picomatch');
// *(pattern) matches ZERO or more of "pattern"
console.log(pm.isMatch('a', 'a*(z)')); // true
console.log(pm.isMatch('az', 'a*(z)')); // true
console.log(pm.isMatch('azzz', 'a*(z)')); // true
// +(pattern) matches ONE or more of "pattern"
console.log(pm.isMatch('a', 'a+(z)')); // false
console.log(pm.isMatch('az', 'a+(z)')); // true
console.log(pm.isMatch('azzz', 'a+(z)')); // true
// supports multiple extglobs
console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
// supports nested extglobs
console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
// risky quantified extglobs are treated literally by default
console.log(pm.makeRe('+(a|aa)'));
//=> /^(?:\+\(a\|aa\))$/
// increase the limit to allow a small amount of nested quantified extglobs
console.log(pm.isMatch('aaa', '+(+(a))', { maxExtglobRecursion: 1 })); // true
```
#### POSIX brackets
POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true.
**Enable POSIX bracket support**
```js
console.log(pm.makeRe('[[:word:]]+', { posix: true }));
//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
```
**Supported POSIX classes**
The following named POSIX bracket expressions are supported:
* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]`
* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`.
* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`.
* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`.
* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`.
* `[:digit:]` - Numerical digits, equivalent to `[0-9]`.
* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`.
* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`.
* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`.
* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`.
* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`.
* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`.
* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`.
See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information.
### Braces
Picomatch only does [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) of comma-delimited lists (e.g. `a/{b,c}/d`). For advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch), which supports advanced syntax such as ranges (e.g. `{01..03}`) and increments (e.g. `{2..10..2}`).
### Matching special characters as literals
If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
**Special Characters**
Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
To match any of the following characters as literals: `$^*+?()[]
Examples:
```js
console.log(pm.makeRe('foo/bar \\(1\\)'));
console.log(pm.makeRe('foo/bar \\(1\\)'));
```
<br>
<br>
## Library Comparisons
The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets).
| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - |
| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - |
| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - |
| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
| File system operations | - | - | - | - | - | - | - |
<br>
<br>
## Benchmarks
Performance comparison of picomatch and minimatch.
```
# .makeRe star (*)
picomatch x 3,251,247 ops/sec ±0.25% (95 runs sampled)
minimatch x 497,224 ops/sec ±0.11% (100 runs sampled)
# .makeRe star; dot=true (*)
picomatch x 2,624,035 ops/sec ±0.16% (98 runs sampled)
minimatch x 446,244 ops/sec ±0.63% (99 runs sampled)
# .makeRe globstar (**)
picomatch x 2,524,465 ops/sec ±0.13% (99 runs sampled)
minimatch x 1,396,257 ops/sec ±0.58% (96 runs sampled)
# .makeRe globstars (**/**/**)
picomatch x 2,545,674 ops/sec ±0.10% (99 runs sampled)
minimatch x 1,196,835 ops/sec ±0.63% (98 runs sampled)
# .makeRe with leading star (*.txt)
picomatch x 2,537,708 ops/sec ±0.11% (100 runs sampled)
minimatch x 345,284 ops/sec ±0.64% (96 runs sampled)
# .makeRe - basic braces ({a,b,c}*.txt)
picomatch x 505,430 ops/sec ±1.04% (94 runs sampled)
minimatch x 107,991 ops/sec ±0.54% (99 runs sampled)
# .makeRe - short ranges ({a..z}*.txt)
picomatch x 371,179 ops/sec ±2.91% (77 runs sampled)
minimatch x 14,104 ops/sec ±0.61% (99 runs sampled)
# .makeRe - medium ranges ({1..100000}*.txt)
picomatch x 384,958 ops/sec ±1.70% (82 runs sampled)
minimatch x 2.55 ops/sec ±3.22% (11 runs sampled)
# .makeRe - long ranges ({1..10000000}*.txt)
picomatch x 382,552 ops/sec ±1.52% (71 runs sampled)
minimatch x 0.83 ops/sec ±5.67% (7 runs sampled))
```
<br>
<br>
## Philosophies
The goal of this library is to be blazing fast, without compromising on accuracy.
**Accuracy**
The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`.
Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
**Performance**
Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
<br>
<br>
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).

View File

@@ -0,0 +1 @@
{"version":3,"file":"typePredicateKind.enum.js","sourceRoot":"","sources":["../../src/enums/typePredicateKind.enum.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAE/F,MAAM,CAAN,IAAY,iBAKX;AALD,WAAY,iBAAiB;IACzB,yDAAQ,CAAA;IACR,qEAAc,CAAA;IACd,uEAAe,CAAA;IACf,mFAAqB,CAAA;AACzB,CAAC,EALW,iBAAiB,KAAjB,iBAAiB,QAK5B"}

View File

@@ -0,0 +1,9 @@
import get from "./get.js";
import getPrototypeOf from "./getPrototypeOf.js";
function _superPropGet(t, o, e, r) {
var p = get(getPrototypeOf(1 & r ? t.prototype : t), o, e);
return 2 & r && "function" == typeof p ? function (t) {
return p.apply(e, t);
} : p;
}
export { _superPropGet as default };

View File

@@ -0,0 +1,13 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
/**
* Check whether a given character is a regional indicator symbol.
* @param {number} code The character code to check.
* @returns {boolean} `true` if the character is a regional indicator symbol.
*/
module.exports = function isRegionalIndicatorSymbol(code) {
return code >= 0x1f1e6 && code <= 0x1f1ff;
};

View File

@@ -0,0 +1,112 @@
import * as util from "../core/util.js";
const error = () => {
const Sizable = {
string: { unit: "merkkiä", subject: "merkkijonon" },
file: { unit: "tavua", subject: "tiedoston" },
array: { unit: "alkiota", subject: "listan" },
set: { unit: "alkiota", subject: "joukon" },
number: { unit: "", subject: "luvun" },
bigint: { unit: "", subject: "suuren kokonaisluvun" },
int: { unit: "", subject: "kokonaisluvun" },
date: { unit: "", subject: "päivämäärän" },
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "säännöllinen lauseke",
email: "sähköpostiosoite",
url: "URL-osoite",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO-aikaleima",
date: "ISO-päivämäärä",
time: "ISO-aika",
duration: "ISO-kesto",
ipv4: "IPv4-osoite",
ipv6: "IPv6-osoite",
cidrv4: "IPv4-alue",
cidrv6: "IPv6-alue",
base64: "base64-koodattu merkkijono",
base64url: "base64url-koodattu merkkijono",
json_string: "JSON-merkkijono",
e164: "E.164-luku",
jwt: "JWT",
template_literal: "templaattimerkkijono",
};
const TypeDictionary = {
nan: "NaN",
};
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 `Virheellinen tyyppi: odotettiin instanceof ${issue.expected}, oli ${received}`;
}
return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
}
case "invalid_value":
if (issue.values.length === 1)
return `Virheellinen syöte: täytyy olla ${util.stringifyPrimitive(issue.values[0])}`;
return `Virheellinen valinta: täytyy olla yksi seuraavista: ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim();
}
return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim();
}
return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with")
return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;
if (_issue.format === "ends_with")
return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;
if (_issue.format === "includes")
return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;
if (_issue.format === "regex") {
return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;
}
return `Virheellinen ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`;
case "unrecognized_keys":
return `${issue.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return "Virheellinen avain tietueessa";
case "invalid_union":
return "Virheellinen unioni";
case "invalid_element":
return "Virheellinen arvo joukossa";
default:
return `Virheellinen syöte`;
}
};
};
export default function () {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1,18 @@
import { FixedSizeDecoder, FixedSizeEncoder } from '@solana/codecs-core';
import { NumberCodecConfig } from './common';
type NumberFactorySharedInput<TSize extends number> = {
config?: NumberCodecConfig;
name: string;
size: TSize;
};
type NumberFactoryEncoderInput<TFrom, TSize extends number> = NumberFactorySharedInput<TSize> & {
range?: [bigint | number, bigint | number];
set: (view: DataView, value: TFrom, littleEndian?: boolean) => void;
};
type NumberFactoryDecoderInput<TTo, TSize extends number> = NumberFactorySharedInput<TSize> & {
get: (view: DataView, littleEndian?: boolean) => TTo;
};
export declare function numberEncoderFactory<TFrom extends bigint | number, TSize extends number>(input: NumberFactoryEncoderInput<TFrom, TSize>): FixedSizeEncoder<TFrom, TSize>;
export declare function numberDecoderFactory<TTo extends bigint | number, TSize extends number>(input: NumberFactoryDecoderInput<TTo, TSize>): FixedSizeDecoder<TTo, TSize>;
export {};
//# sourceMappingURL=utils.d.ts.map

View File

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

View File

@@ -0,0 +1,74 @@
{
"name": "ws",
"version": "8.21.3",
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"keywords": [
"HyBi",
"Push",
"RFC-6455",
"WebSocket",
"WebSockets",
"real-time"
],
"homepage": "https://github.com/websockets/ws",
"bugs": "https://github.com/websockets/ws/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/websockets/ws.git"
},
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"license": "MIT",
"main": "index.js",
"exports": {
".": {
"browser": "./browser.js",
"import": "./wrapper.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"browser": "browser.js",
"engines": {
"node": ">=10.0.0"
},
"files": [
"browser.js",
"index.js",
"lib/*.js",
"wrapper.mjs"
],
"scripts": {
"test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
"integration": "mocha --throw-deprecation test/*.integration.js",
"lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"benchmark": "^2.1.4",
"bufferutil": "^4.0.1",
"eslint": "^10.0.1",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.0.0",
"globals": "^17.0.0",
"mocha": "^8.4.0",
"nyc": "^15.0.0",
"prettier": "^3.0.0",
"utf-8-validate": "^6.0.0"
},
"allowScripts": {
"bufferutil": true,
"utf-8-validate": true
}
}

View File

@@ -0,0 +1,87 @@
'use strict'
const test = require('tape')
const pino = require('../browser')
test('set browser opts disabled to true', ({ end, same }) => {
const instance = pino({
browser: {
disabled: true,
write (actual) {
checkLogObjects(same, actual, [])
}
}
})
instance.info('hello world')
instance.error('this is an error')
instance.fatal('this is fatal')
end()
})
test('set browser opts disabled to false', ({ end, same }) => {
const expected = [
{
level: 30,
msg: 'hello world'
},
{
level: 50,
msg: 'this is an error'
},
{
level: 60,
msg: 'this is fatal'
}
]
const instance = pino({
browser: {
disabled: false,
write (actual) {
checkLogObjects(same, actual, expected.shift())
}
}
})
instance.info('hello world')
instance.error('this is an error')
instance.fatal('this is fatal')
end()
})
test('disabled is not set in browser opts', ({ end, same }) => {
const expected = [
{
level: 30,
msg: 'hello world'
},
{
level: 50,
msg: 'this is an error'
},
{
level: 60,
msg: 'this is fatal'
}
]
const instance = pino({
browser: {
write (actual) {
checkLogObjects(same, actual, expected.shift())
}
}
})
instance.info('hello world')
instance.error('this is an error')
instance.fatal('this is fatal')
end()
})
function checkLogObjects (same, actual, expected, is) {
const actualCopy = Object.assign({}, actual)
const expectedCopy = Object.assign({}, expected)
delete actualCopy.time
delete expectedCopy.time
same(actualCopy, expectedCopy)
}

View File

@@ -0,0 +1,15 @@
export { default as MAX } from './max.js';
export { default as NIL } from './nil.js';
export { default as parse } from './parse.js';
export { default as stringify } from './stringify.js';
export type * from './types.js';
export { default as v1 } from './v1.js';
export { default as v1ToV6 } from './v1ToV6.js';
export { default as v3 } from './v3.js';
export { default as v4 } from './v4.js';
export { default as v5 } from './v5.js';
export { default as v6 } from './v6.js';
export { default as v6ToV1 } from './v6ToV1.js';
export { default as v7 } from './v7.js';
export { default as validate } from './validate.js';
export { default as version } from './version.js';

View File

@@ -0,0 +1,61 @@
{
"name": "tinyexec",
"version": "1.3.0",
"type": "module",
"description": "A minimal library for executing processes in Node",
"main": "./dist/main.mjs",
"engines": {
"node": ">=18"
},
"files": [
"dist",
"THIRD-PARTY-LICENSES.txt"
],
"scripts": {
"build": "tsdown",
"dev": "tsdown --watch",
"format": "prettier --write src",
"format:check": "prettier --check src",
"lint": "tsc --noEmit && eslint src && publint",
"prepare": "npm run build",
"test": "npm run build && npm run test:unit",
"test:unit": "vitest run"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tinylibs/tinyexec.git"
},
"keywords": [
"execa",
"exec",
"tiny",
"child_process",
"spawn"
],
"author": "James Garbutt (https://github.com/43081j)",
"license": "MIT",
"bugs": {
"url": "https://github.com/tinylibs/tinyexec/issues"
},
"homepage": "https://github.com/tinylibs/tinyexec#readme",
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/node": "^26.1.2",
"@vitest/coverage-v8": "^4.1.10",
"eslint": "^10.8.0",
"prettier": "^3.9.6",
"publint": "^0.3.22",
"tsdown": "^0.22.14",
"typescript": "^6.0.3",
"typescript-eslint": "^8.65.0",
"vitest": "^4.0.7"
},
"exports": {
".": {
"types": "./dist/main.d.mts",
"default": "./dist/main.mjs"
},
"./package.json": "./package.json"
},
"types": "./dist/main.d.mts"
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,MAAM,CAAC;AACrB,cAAc,aAAa,CAAC;AAC5B,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,OAAO,CAAC;AACtB,cAAc,MAAM,CAAC"}

View File

@@ -0,0 +1,89 @@
'use strict';
var traverse = module.exports = function (schema, opts, cb) {
// Legacy support for v0.3.1 and earlier.
if (typeof opts == 'function') {
cb = opts;
opts = {};
}
cb = opts.cb || cb;
var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
var post = cb.post || function() {};
_traverse(opts, pre, post, schema, '', schema);
};
traverse.keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true
};
traverse.arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true
};
traverse.propsKeywords = {
definitions: true,
properties: true,
patternProperties: true,
dependencies: true
};
traverse.skipKeywords = {
default: true,
enum: true,
const: true,
required: true,
maximum: true,
minimum: true,
exclusiveMaximum: true,
exclusiveMinimum: true,
multipleOf: true,
maxLength: true,
minLength: true,
pattern: true,
format: true,
maxItems: true,
minItems: true,
uniqueItems: true,
maxProperties: true,
minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
for (var key in schema) {
var sch = schema[key];
if (Array.isArray(sch)) {
if (key in traverse.arrayKeywords) {
for (var i=0; i<sch.length; i++)
_traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
}
} else if (key in traverse.propsKeywords) {
if (sch && typeof sch == 'object') {
for (var prop in sch)
_traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
}
} else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
_traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
}
}
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
}
}
function escapeJsonPtr(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2013 Andrey Sitnik <andrey@sitnik.es>
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,46 @@
// Type definitions for the es-module-lexer minimal build (es-module-lexer/minimal).
// Auto-generated by build/gen-min-dts.mjs — do not edit.
import { ImportType, ImportSpecifier, ParseError } from './lexer.js';
export { ImportType, ImportSpecifier, ParseError };
/**
* Export specifier — minimal build.
*
* Identical to the full ExportSpecifier except that the export statement start
* (`ss`) is not tracked in the minimal build.
*/
export interface ExportSpecifier {
/** Exported name */
readonly n: string;
/** Local name, or undefined */
readonly ln: string | undefined;
/** Start of exported name */
readonly s: number;
/** End of exported name */
readonly e: number;
/** Start of local name, or -1 */
readonly ls: number;
/** End of local name, or -1 */
readonly le: number;
}
/**
* Outputs the lexical analysis of the source — minimal build.
*
* Returns a 2-tuple of imports and exports. Unlike the full build, the minimal
* build does not emit the facade / hasModuleSyntax flags, and ImportSpecifier
* `at` is always null (read assertions via `source.slice(a, se - 1)`).
*
* @param source Source code to parse
* @param name Optional sourcename
*/
export declare function parse(source: string, name?: string): readonly [
imports: ReadonlyArray<ImportSpecifier>,
exports: ReadonlyArray<ExportSpecifier>
];
/**
* Wait for init to resolve before calling `parse`.
*/
export declare const init: Promise<void>;
export declare const initSync: () => void;

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,MAAM,EACN,OAAO,EACP,UAAU,EACV,WAAW,EACX,WAAW,EACX,UAAU,EACV,OAAO,EACP,WAAW,EACX,WAAW,GACZ,MAAM,wBAAwB,CAAC;AAGhC,MAAM,MAAM,GAAG,GAAG,UAAU,GAAG,MAAM,CAAC;AACtC,MAAM,MAAM,OAAO,GAAG,GAAG,GAAG,MAAM,CAAC;AACnC,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,GAAG,CAAC;CACxC,CAAC;AACF,MAAM,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,UAAU,GAAG,MAAM,KAAK,UAAU,CAAC;AAEjE,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEzD;AAGD,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,GAAE,MAAW,GAAG,OA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;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,SAAS;CAAE,CAAC;AAG5E,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC1D,MAAM,EAAE,CAAC,EACT,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,EACrB,aAAa,GAAE,MAAM,CAAC,CAAC,CAAM,GAC5B,CAAC,CAgBH;AAUD,wBAAgB,MAAM,CAAC,GAAG,EAAE,KAAK,GAAG,OAAO,CAE1C;AACD,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC3B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC9B,SAAS,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,GACrC,IAAI,CAYN;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,QAAO,KAEjC,CAAC;AAEF;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,SAAS,GAAG,EAAE,EAC3D,EAAE,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,GAC5B,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,KAAK,CAAC,CAS3B"}

View File

@@ -0,0 +1,41 @@
/**
* @fileoverview Rule to flag use of a debugger statement
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow the use of `debugger`",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-debugger",
},
fixable: null,
schema: [],
messages: {
unexpected: "Unexpected 'debugger' statement.",
},
},
create(context) {
return {
DebuggerStatement(node) {
context.report({
node,
messageId: "unexpected",
});
},
};
},
};