docs: 仓库链接指向本镜像仓库
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run

This commit is contained in:
TanTan committed 2026-11-13 09:27:07 +08:00
1 parent fa9c73363d
commit 2a69b23b47
18210 files changed
+5101211 -16

No files matched your search

@@ -0,0 +1 @@
{"version":3,"file":"minus-square.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Mic = createLucideIcon("Mic", [
["path", { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z", key: "131961" }],
["path", { d: "M19 10v2a7 7 0 0 1-14 0v-2", key: "1vc78b" }],
["line", { x1: "12", x2: "12", y1: "19", y2: "22", key: "x3vr5v" }]
]);
export { Mic as default };
//# sourceMappingURL=mic.js.map
@@ -0,0 +1,411 @@
import { ResolveOptions as ResolveOptions$1 } from 'mlly';
import { CompilerOptions, TypeAcquisition } from 'typescript';
interface FindFileOptions {
/**
* The starting directory for the search.
* @default . (same as `process.cwd()`)
*/
startingFrom?: string;
/**
* A pattern to match a path segment above which you don't want to ascend
* @default /^node_modules$/
*/
rootPattern?: RegExp;
/**
* If true, search starts from root level descending into subdirectories
*/
reverse?: boolean;
/**
* A matcher that can evaluate whether the given path is a valid file (for example,
* by testing whether the file path exists.
*
* @default fs.statSync(path).isFile()
*/
test?: (filePath: string) => boolean | undefined | Promise<boolean | undefined>;
}
/** @deprecated */
type FindNearestFileOptions = FindFileOptions;
/**
* Asynchronously finds a file by name, starting from the specified directory and traversing up (or down if reverse).
* @param filename - The name of the file to find.
* @param _options - Options to customise the search behaviour.
* @returns a promise that resolves to the path of the file found.
* @throws Will throw an error if the file cannot be found.
*/
declare function findFile(filename: string | string[], _options?: FindFileOptions): Promise<string>;
/**
* Asynchronously finds the next file with the given name, starting in the given directory and moving up.
* Alias for findFile without reversing the search.
* @param filename - The name of the file to find.
* @param _options - Options to customise the search behaviour.
* @returns A promise that resolves to the path of the next file found.
*/
declare function findNearestFile(filename: string | string[], _options?: FindFileOptions): Promise<string>;
/**
* Asynchronously finds the furthest file with the given name, starting from the root directory and moving downwards.
* This is essentially the reverse of `findNearestFile'.
* @param filename - The name of the file to find.
* @param _options - Options to customise the search behaviour, with reverse set to true.
* @returns A promise that resolves to the path of the farthest file found.
*/
declare function findFarthestFile(filename: string, _options?: FindFileOptions): Promise<string>;
type StripEnums<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends boolean ? T[K] : T[K] extends string ? T[K] : T[K] extends object ? T[K] : T[K] extends Array<any> ? T[K] : T[K] extends undefined ? undefined : any;
};
interface TSConfig {
compilerOptions?: StripEnums<CompilerOptions>;
exclude?: string[];
compileOnSave?: boolean;
extends?: string | string[];
files?: string[];
include?: string[];
typeAcquisition?: TypeAcquisition;
references?: {
path: string;
}[];
}
interface PackageJson {
/**
* The name is what your thing is called.
* Some rules:
* - The name must be less than or equal to 214 characters. This includes the scope for scoped packages.
* - The name can’t start with a dot or an underscore.
* - New packages must not have uppercase letters in the name.
* - The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can’t contain any non-URL-safe characters.
*/
name?: string;
/**
* Version must be parseable by `node-semver`, which is bundled with npm as a dependency. (`npm install semver` to use it yourself.)
*/
version?: string;
/**
* Put a description in it. It’s a string. This helps people discover your package, as it’s listed in `npm search`.
*/
description?: string;
/**
* Put keywords in it. It’s an array of strings. This helps people discover your package as it’s listed in `npm search`.
*/
keywords?: string[];
/**
* The url to the project homepage.
*/
homepage?: string;
/**
* The url to your project’s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.
*/
bugs?: string | {
url?: string;
email?: string;
};
/**
* You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you’re placing on it.
*/
license?: string;
/**
* Specify the place where your code lives. This is helpful for people who want to contribute. If the git repo is on GitHub, then the `npm docs` command will be able to find you.
* For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same shortcut syntax you use for npm install:
*/
repository?: string | {
type: string;
url: string;
/**
* If the `package.json` for your package is not in the root directory (for example if it is part of a monorepo), you can specify the directory in which it lives:
*/
directory?: string;
};
/**
* The `scripts` field is a dictionary containing script commands that are run at various times in the lifecycle of your package.
*/
scripts?: Record<string, string>;
/**
* If you set `"private": true` in your package.json, then npm will refuse to publish it.
*/
private?: boolean;
/**
* The “author” is one person.
*/
author?: PackageJsonPerson;
/**
* “contributors” is an array of people.
*/
contributors?: PackageJsonPerson[];
/**
* The optional `files` field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. File patterns follow a similar syntax to `.gitignore`, but reversed: including a file, directory, or glob pattern (`*`, `**\/*`, and such) will make it so that file is included in the tarball when it’s packed. Omitting the field will make it default to `["*"]`, which means it will include all files.
*/
files?: string[];
/**
* The main field is a module ID that is the primary entry point to your program. That is, if your package is named `foo`, and a user installs it, and then does `require("foo")`, then your main module’s exports object will be returned.
* This should be a module ID relative to the root of your package folder.
* For most modules, it makes the most sense to have a main script and often not much else.
*/
main?: string;
/**
* If your module is meant to be used client-side the browser field should be used instead of the main field. This is helpful to hint users that it might rely on primitives that aren’t available in Node.js modules. (e.g. window)
*/
browser?: string | Record<string, string | false>;
/**
* The `unpkg` field is used to specify the URL to a UMD module for your package. This is used by default in the unpkg.com CDN service.
*/
unpkg?: string;
/**
* A map of command name to local file name. On install, npm will symlink that file into `prefix/bin` for global installs, or `./node_modules/.bin/` for local installs.
*/
bin?: string | Record<string, string>;
/**
* Specify either a single file or an array of filenames to put in place for the `man` program to find.
*/
man?: string | string[];
/**
* Dependencies are specified in a simple object that maps a package name to a version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.
*/
dependencies?: Record<string, string>;
/**
* If someone is planning on downloading and using your module in their program, then they probably don’t want or need to download and build the external test or documentation framework that you use.
* In this case, it’s best to map these additional items in a `devDependencies` object.
*/
devDependencies?: Record<string, string>;
/**
* If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the `optionalDependencies` object. This is a map of package name to version or url, just like the `dependencies` object. The difference is that build failures do not cause installation to fail.
*/
optionalDependencies?: Record<string, string>;
/**
* In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a `require` of this host. This is usually referred to as a plugin. Notably, your module may be exposing a specific interface, expected and specified by the host documentation.
*/
peerDependencies?: Record<string, string>;
/**
* TypeScript typings, typically ending by `.d.ts`.
*/
types?: string;
/**
* This field is synonymous with `types`.
*/
typings?: string;
/**
* Non-Standard Node.js alternate entry-point to main.
* An initial implementation for supporting CJS packages (from main), and use module for ESM modules.
*/
module?: string;
/**
* Make main entry-point be loaded as an ESM module, support "export" syntax instead of "require"
*
* Docs:
* - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_package_json_type_field
*
* @default 'commonjs'
* @since Node.js v14
*/
type?: "module" | "commonjs";
/**
* Alternate and extensible alternative to "main" entry point.
*
* When using `{type: "module"}`, any ESM module file MUST end with `.mjs` extension.
*
* Docs:
* - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_exports_sugar
*
* @since Node.js v12.7
*/
exports?: PackageJsonExports;
/**
* Docs:
* - https://nodejs.org/api/packages.html#imports
*/
imports?: Record<string, string | Record<string, string>>;
/**
* The field is used to define a set of sub-packages (or workspaces) within a monorepo.
*
* This field is an array of glob patterns or an object with specific configurations for managing
* multiple packages in a single repository.
*/
workspaces?: string[];
/**
* The field is is used to specify different TypeScript declaration files for
* different versions of TypeScript, allowing for version-specific type definitions.
*/
typesVersions?: Record<string, Record<string, string[]>>;
/**
* You can specify which operating systems your module will run on:
* ```json
* {
* "os": ["darwin", "linux"]
* }
* ```
* You can also block instead of allowing operating systems, just prepend the blocked os with a '!':
* ```json
* {
* "os": ["!win32"]
* }
* ```
* The host operating system is determined by `process.platform`
* It is allowed to both block and allow an item, although there isn't any good reason to do this.
*/
os?: string[];
/**
* If your code only runs on certain cpu architectures, you can specify which ones.
* ```json
* {
* "cpu": ["x64", "ia32"]
* }
* ```
* Like the `os` option, you can also block architectures:
* ```json
* {
* "cpu": ["!arm", "!mips"]
* }
* ```
* The host architecture is determined by `process.arch`
*/
cpu?: string[];
/**
* This is a set of config values that will be used at publish-time.
*/
publishConfig?: {
/**
* The registry that will be used if the package is published.
*/
registry?: string;
/**
* The tag that will be used if the package is published.
*/
tag?: string;
/**
* The access level that will be used if the package is published.
*/
access?: "public" | "restricted";
/**
* **pnpm-only**
*
* By default, for portability reasons, no files except those listed in
* the bin field will be marked as executable in the resulting package
* archive. The executableFiles field lets you declare additional fields
* that must have the executable flag (+x) set even if
* they aren't directly accessible through the bin field.
*/
executableFiles?: string[];
/**
* **pnpm-only**
*
* You also can use the field `publishConfig.directory` to customize
* the published subdirectory relative to the current `package.json`.
*
* It is expected to have a modified version of the current package in
* the specified directory (usually using third party build tools).
*/
directory?: string;
/**
* **pnpm-only**
*
* When set to `true`, the project will be symlinked from the
* `publishConfig.directory` location during local development.
* @default true
*/
linkDirectory?: boolean;
} & Pick<PackageJson, "bin" | "main" | "exports" | "types" | "typings" | "module" | "browser" | "unpkg" | "typesVersions" | "os" | "cpu">;
/**
* See: https://nodejs.org/api/packages.html#packagemanager
* This field defines which package manager is expected to be used when working on the current project.
* Should be of the format: `<name>@<version>[#hash]`
*/
packageManager?: string;
[key: string]: any;
}
/**
* A “person” is an object with a “name” field and optionally “url” and “email”. Or you can shorten that all into a single string, and npm will parse it for you.
*/
type PackageJsonPerson = string | {
name: string;
email?: string;
url?: string;
};
type PackageJsonExportKey = "." | "import" | "require" | "types" | "node" | "browser" | "default" | (string & {});
type PackageJsonExportsObject = {
[P in PackageJsonExportKey]?: string | PackageJsonExportsObject | Array<string | PackageJsonExportsObject>;
};
type PackageJsonExports = string | PackageJsonExportsObject | Array<string | PackageJsonExportsObject>;
/**
* Represents the options for resolving paths with additional file finding capabilities.
*/
type ResolveOptions = ResolveOptions$1 & FindFileOptions;
/**
* Options for reading files with optional caching.
*/
type ReadOptions = {
/**
* Specifies whether the read results should be cached.
* Can be a boolean or a map to hold the cached data.
*/
cache?: boolean | Map<string, Record<string, any>>;
};
/**
* Defines a PackageJson structure.
* @param package_ - The `package.json` content as an object. See {@link PackageJson}.
* @returns the same `package.json` object.
*/
declare function definePackageJSON(package_: PackageJson): PackageJson;
/**
* Defines a TSConfig structure.
* @param tsconfig - The contents of `tsconfig.json` as an object. See {@link TSConfig}.
* @returns the same `tsconfig.json` object.
*/
declare function defineTSConfig(tsconfig: TSConfig): TSConfig;
/**
* Asynchronously reads a `package.json` file.
* @param id - The path identifier for the package.json, defaults to the current working directory.
* @param options - The options for resolving and reading the file. See {@link ResolveOptions}.
* @returns a promise resolving to the parsed `package.json` object.
*/
declare function readPackageJSON(id?: string, options?: ResolveOptions & ReadOptions): Promise<PackageJson>;
/**
* Asynchronously writes data to a `package.json` file.
* @param path - The path to the file where the `package.json` is written.
* @param package_ - The `package.json` object to write. See {@link PackageJson}.
*/
declare function writePackageJSON(path: string, package_: PackageJson): Promise<void>;
/**
* Asynchronously reads a `tsconfig.json` file.
* @param id - The path to the `tsconfig.json` file, defaults to the current working directory.
* @param options - The options for resolving and reading the file. See {@link ResolveOptions}.
* @returns a promise resolving to the parsed `tsconfig.json` object.
*/
declare function readTSConfig(id?: string, options?: ResolveOptions & ReadOptions): Promise<TSConfig>;
/**
* Asynchronously writes data to a `tsconfig.json` file.
* @param path - The path to the file where the `tsconfig.json` is written.
* @param tsconfig - The `tsconfig.json` object to write. See {@link TSConfig}.
*/
declare function writeTSConfig(path: string, tsconfig: TSConfig): Promise<void>;
/**
* Resolves the path to the nearest `package.json` file from a given directory.
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest `package.json` file.
*/
declare function resolvePackageJSON(id?: string, options?: ResolveOptions): Promise<string>;
/**
* Resolves the path to the nearest `tsconfig.json` file from a given directory.
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest `tsconfig.json` file.
*/
declare function resolveTSConfig(id?: string, options?: ResolveOptions): Promise<string>;
/**
* Resolves the path to the nearest lockfile from a given directory.
* @param id - The base path for the search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns A promise resolving to the path of the nearest lockfile.
*/
declare function resolveLockfile(id?: string, options?: ResolveOptions): Promise<string>;
/**
* Detects the workspace directory based on common project markers (`.git`, lockfiles, `package.json`).
* Throws an error if the workspace root cannot be detected.
* @param id - The base path to search, defaults to the current working directory.
* @param options - Options to modify the search behaviour. See {@link ResolveOptions}.
* @returns a promise resolving to the path of the detected workspace directory.
*/
declare function findWorkspaceDir(id?: string, options?: ResolveOptions): Promise<string>;
export { type FindFileOptions, type FindNearestFileOptions, type PackageJson, type PackageJsonExports, type PackageJsonPerson, type ReadOptions, type ResolveOptions, type StripEnums, type TSConfig, definePackageJSON, defineTSConfig, findFarthestFile, findFile, findNearestFile, findWorkspaceDir, readPackageJSON, readTSConfig, resolveLockfile, resolvePackageJSON, resolveTSConfig, writePackageJSON, writeTSConfig };
@@ -0,0 +1,22 @@
/**
* Assigns a value for a given ref, no matter of the ref format
* @param {RefObject} ref - a callback function or ref object
* @param value - a new value
*
* @see https://github.com/theKashey/use-callback-ref#assignref
* @example
* const refObject = useRef();
* const refFn = (ref) => {....}
*
* assignRef(refObject, "refValue");
* assignRef(refFn, "refValue");
*/
export function assignRef(ref, value) {
if (typeof ref === 'function') {
ref(value);
}
else if (ref) {
ref.current = value;
}
return ref;
}
@@ -0,0 +1 @@
{"version":3,"names":["_inherit","require","inheritTrailingComments","child","parent","inherit"],"sources":["../../src/comments/inheritTrailingComments.ts"],"sourcesContent":["import inherit from \"../utils/inherit.ts\";\nimport type * as t from \"../index.ts\";\n\nexport default function inheritTrailingComments(\n child: t.Node,\n parent: t.Node,\n): void {\n inherit(\"trailingComments\", child, parent);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,QAAA,GAAAC,OAAA;AAGe,SAASC,uBAAuBA,CAC7CC,KAAa,EACbC,MAAc,EACR;EACN,IAAAC,gBAAO,EAAC,kBAAkB,EAAEF,KAAK,EAAEC,MAAM,CAAC;AAC5C","ignoreList":[]}
@@ -0,0 +1,890 @@
// @ts-self-types="./index.d.ts"
import levn from 'levn';
/**
* @fileoverview Config Comment Parser
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
/** @import * as $eslintcore from "@eslint/core"; */
/** @typedef {$eslintcore.RuleConfig} RuleConfig */
/** @typedef {$eslintcore.RulesConfig} RulesConfig */
/** @import * as $typests from "./types.ts"; */
/** @typedef {$typests.StringConfig} StringConfig */
/** @typedef {$typests.BooleanConfig} BooleanConfig */
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const directivesPattern = /^([a-z]+(?:-[a-z]+)*)(?:\s|$)/u;
const validSeverities = new Set([0, 1, 2, "off", "warn", "error"]);
/**
* Determines if the severity in the rule configuration is valid.
* @param {RuleConfig} ruleConfig A rule's configuration.
* @returns {boolean} `true` if the severity is valid, otherwise `false`.
*/
function isSeverityValid(ruleConfig) {
const severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
return validSeverities.has(severity);
}
/**
* Determines if all severities in the rules configuration are valid.
* @param {RulesConfig} rulesConfig The rules configuration to check.
* @returns {boolean} `true` if all severities are valid, otherwise `false`.
*/
function isEverySeverityValid(rulesConfig) {
return Object.values(rulesConfig).every(isSeverityValid);
}
/**
* Represents a directive comment.
*/
class DirectiveComment {
/**
* The label of the directive, such as "eslint", "eslint-disable", etc.
* @type {string}
*/
label = "";
/**
* The value of the directive (the string after the label).
* @type {string}
*/
value = "";
/**
* The justification of the directive (the string after the --).
* @type {string}
*/
justification = "";
/**
* Creates a new directive comment.
* @param {string} label The label of the directive.
* @param {string} value The value of the directive.
* @param {string} justification The justification of the directive.
*/
constructor(label, value, justification) {
this.label = label;
this.value = value;
this.justification = justification;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Object to parse ESLint configuration comments.
*/
class ConfigCommentParser {
/**
* Parses a list of "name:string_value" or/and "name" options divided by comma or
* whitespace. Used for "global" comments.
* @param {string} string The string to parse.
* @returns {StringConfig} Result map object of names and string values, or null values if no value was provided.
*/
parseStringConfig(string) {
const items = /** @type {StringConfig} */ ({});
// Collapse whitespace around `:` and `,` to make parsing easier
const trimmedString = string
.trim()
.replace(/(?<!\s)\s*([:,])\s*/gu, "$1");
trimmedString.split(/\s|,+/u).forEach(name => {
if (!name) {
return;
}
// value defaults to null (if not provided), e.g: "foo" => ["foo", null]
const [key, value = null] = name.split(":");
items[key] = value;
});
return items;
}
/**
* Parses a JSON-like config.
* @param {string} string The string to parse.
* @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object
*/
parseJSONLikeConfig(string) {
// Parses a JSON-like comment by the same way as parsing CLI option.
try {
const items =
/** @type {RulesConfig} */ (levn.parse("Object", string)) || {};
/*
* When the configuration has any invalid severities, it should be completely
* ignored. This is because the configuration is not valid and should not be
* applied.
*
* For example, the following configuration is invalid:
*
* "no-alert: 2 no-console: 2"
*
* This results in a configuration of { "no-alert": "2 no-console: 2" }, which is
* not valid. In this case, the configuration should be ignored.
*/
if (isEverySeverityValid(items)) {
return {
ok: true,
config: items,
};
}
} catch {
// levn parsing error: ignore to parse the string by a fallback.
}
/*
* Optionator cannot parse commaless notations.
* But we are supporting that. So this is a fallback for that.
*/
const normalizedString = string
.replace(/(?<![-a-zA-Z0-9/])([-a-zA-Z0-9/]+):/gu, '"$1":')
.replace(/([\]0-9])\s+(?=")/u, "$1,");
try {
const items = JSON.parse(`{${normalizedString}}`);
return {
ok: true,
config: items,
};
} catch (ex) {
const errorMessage = ex instanceof Error ? ex.message : String(ex);
return {
ok: false,
error: {
message: `Failed to parse JSON from '${normalizedString}': ${errorMessage}`,
},
};
}
}
/**
* Parses a config of values separated by comma.
* @param {string} string The string to parse.
* @returns {BooleanConfig} Result map of values and true values
*/
parseListConfig(string) {
const items = /** @type {BooleanConfig} */ ({});
string.split(",").forEach(name => {
const trimmedName = name
.trim()
.replace(
/^(?<quote>['"]?)(?<ruleId>.*)\k<quote>$/su,
"$<ruleId>",
);
if (trimmedName) {
items[trimmedName] = true;
}
});
return items;
}
/**
* Extract the directive and the justification from a given directive comment and trim them.
* @param {string} value The comment text to extract.
* @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification.
*/
#extractDirectiveComment(value) {
const match = /\s-{2,}\s/u.exec(value);
if (!match) {
return { directivePart: value.trim(), justificationPart: "" };
}
const directive = value.slice(0, match.index).trim();
const justification = value.slice(match.index + match[0].length).trim();
return { directivePart: directive, justificationPart: justification };
}
/**
* Parses a directive comment into directive text and value.
* @param {string} string The string with the directive to be parsed.
* @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid.
*/
parseDirective(string) {
const { directivePart, justificationPart } =
this.#extractDirectiveComment(string);
const match = directivesPattern.exec(directivePart);
if (!match) {
return undefined;
}
const directiveText = match[1];
const directiveValue = directivePart.slice(
match.index + directiveText.length,
);
return new DirectiveComment(
directiveText,
directiveValue.trim(),
justificationPart,
);
}
}
/**
* @fileoverview A collection of helper classes for implementing `SourceCode`.
* @author Nicholas C. Zakas
*/
/* eslint class-methods-use-this: off -- Required to complete interface. */
//-----------------------------------------------------------------------------
// Type Definitions
//-----------------------------------------------------------------------------
/** @typedef {$eslintcore.VisitTraversalStep} VisitTraversalStep */
/** @typedef {$eslintcore.CallTraversalStep} CallTraversalStep */
/** @typedef {$eslintcore.TraversalStep} TraversalStep */
/** @typedef {$eslintcore.SourceLocation} SourceLocation */
/** @typedef {$eslintcore.SourceLocationWithOffset} SourceLocationWithOffset */
/** @typedef {$eslintcore.SourceRange} SourceRange */
/** @typedef {$eslintcore.Directive} IDirective */
/** @typedef {$eslintcore.DirectiveType} DirectiveType */
/** @typedef {$eslintcore.SourceCodeBaseTypeOptions} SourceCodeBaseTypeOptions */
/**
* @typedef {import("@eslint/core").TextSourceCode<Options>} TextSourceCode
* @template {SourceCodeBaseTypeOptions} [Options=SourceCodeBaseTypeOptions]
*/
/** @typedef {$eslintcore.RuleVisitor} RuleVisitor */
/**
* @typedef {import("./types.ts").CustomRuleVisitorWithExit<RuleVisitorType>} CustomRuleVisitorWithExit
* @template {RuleVisitor} RuleVisitorType
*/
/** @typedef {$typests.CustomRuleTypeDefinitions} CustomRuleTypeDefinitions */
/**
* @typedef {import("./types.ts").CustomRuleDefinitionType<LanguageSpecificOptions, Options>} CustomRuleDefinitionType
* @template {Omit<import("@eslint/core").RuleDefinitionTypeOptions, keyof CustomRuleTypeDefinitions>} LanguageSpecificOptions
* @template {Partial<CustomRuleTypeDefinitions>} Options
*/
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/**
* Determines if a node has ESTree-style loc information.
* @param {object} node The node to check.
* @returns {node is {loc:SourceLocation}} `true` if the node has ESTree-style loc information, `false` if not.
*/
function hasESTreeStyleLoc(node) {
return "loc" in node;
}
/**
* Determines if a node has position-style loc information.
* @param {object} node The node to check.
* @returns {node is {position:SourceLocation}} `true` if the node has position-style range information, `false` if not.
*/
function hasPosStyleLoc(node) {
return "position" in node;
}
/**
* Determines if a node has ESTree-style range information.
* @param {object} node The node to check.
* @returns {node is {range:SourceRange}} `true` if the node has ESTree-style range information, `false` if not.
*/
function hasESTreeStyleRange(node) {
return "range" in node;
}
/**
* Determines if a node has position-style range information.
* @param {object} node The node to check.
* @returns {node is {position:SourceLocationWithOffset}} `true` if the node has position-style range information, `false` if not.
*/
function hasPosStyleRange(node) {
return "position" in node;
}
/**
* Performs binary search to find the line number containing a given target index.
* Returns the lower bound - the index of the first element greater than the target.
* **Please note that the `lineStartIndices` should be sorted in ascending order**.
* - Time Complexity: O(log n) - Significantly faster than linear search for large files.
* @param {number[]} lineStartIndices Sorted array of line start indices.
* @param {number} targetIndex The target index to find the line number for.
* @returns {number} The line number for the target index.
*/
function findLineNumberBinarySearch(lineStartIndices, targetIndex) {
let low = 0;
let high = lineStartIndices.length - 1;
while (low < high) {
const mid = ((low + high) / 2) | 0; // Use bitwise OR to floor the division.
if (targetIndex < lineStartIndices[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A class to represent a step in the traversal process where a node is visited.
* @implements {VisitTraversalStep}
*/
class VisitNodeStep {
/**
* The type of the step.
* @type {"visit"}
* @readonly
*/
type = "visit";
/**
* The kind of the step. Represents the same data as the `type` property
* but it's a number for performance.
* @type {1}
* @readonly
*/
kind = 1;
/**
* The target of the step.
* @type {object}
*/
target;
/**
* The phase of the step.
* @type {1|2}
*/
phase;
/**
* The arguments of the step.
* @type {Array<any>}
*/
args;
/**
* Creates a new instance.
* @param {Object} options The options for the step.
* @param {object} options.target The target of the step.
* @param {1|2} options.phase The phase of the step.
* @param {Array<any>} options.args The arguments of the step.
*/
constructor({ target, phase, args }) {
this.target = target;
this.phase = phase;
this.args = args;
}
}
/**
* A class to represent a step in the traversal process where a
* method is called.
* @implements {CallTraversalStep}
*/
class CallMethodStep {
/**
* The type of the step.
* @type {"call"}
* @readonly
*/
type = "call";
/**
* The kind of the step. Represents the same data as the `type` property
* but it's a number for performance.
* @type {2}
* @readonly
*/
kind = 2;
/**
* The name of the method to call.
* @type {string}
*/
target;
/**
* The arguments to pass to the method.
* @type {Array<any>}
*/
args;
/**
* Creates a new instance.
* @param {Object} options The options for the step.
* @param {string} options.target The target of the step.
* @param {Array<any>} options.args The arguments of the step.
*/
constructor({ target, args }) {
this.target = target;
this.args = args;
}
}
/**
* A class to represent a directive comment.
* @implements {IDirective}
*/
class Directive {
/**
* The type of directive.
* @type {DirectiveType}
* @readonly
*/
type;
/**
* The node representing the directive.
* @type {unknown}
* @readonly
*/
node;
/**
* Everything after the "eslint-disable" portion of the directive,
* but before the "--" that indicates the justification.
* @type {string}
* @readonly
*/
value;
/**
* The justification for the directive.
* @type {string}
* @readonly
*/
justification;
/**
* Creates a new instance.
* @param {Object} options The options for the directive.
* @param {"disable"|"enable"|"disable-next-line"|"disable-line"} options.type The type of directive.
* @param {unknown} options.node The node representing the directive.
* @param {string} options.value The value of the directive.
* @param {string} options.justification The justification for the directive.
*/
constructor({ type, node, value, justification }) {
this.type = type;
this.node = node;
this.value = value;
this.justification = justification;
}
}
/**
* Source Code Base Object
* @template {SourceCodeBaseTypeOptions & {RootNode: object, SyntaxElementWithLoc: object}} [Options=SourceCodeBaseTypeOptions & {RootNode: object, SyntaxElementWithLoc: object}]
* @implements {TextSourceCode<Options>}
*/
class TextSourceCodeBase {
/**
* The lines of text in the source code.
* @type {Array<string>}
*/
#lines = [];
/**
* The indices of the start of each line in the source code.
* @type {Array<number>}
*/
#lineStartIndices = [0];
/**
* The pattern to match lineEndings in the source code.
* @type {RegExp}
*/
#lineEndingPattern;
/**
* The AST of the source code.
* @type {Options['RootNode']}
*/
ast;
/**
* The text of the source code.
* @type {string}
*/
text;
/**
* Creates a new instance.
* @param {Object} options The options for the instance.
* @param {string} options.text The source code text.
* @param {Options['RootNode']} options.ast The root AST node.
* @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. Defaults to `/\r?\n/u`.
*/
constructor({ text, ast, lineEndingPattern = /\r?\n/u }) {
this.ast = ast;
this.text = text;
// Remove the global(`g`) and sticky(`y`) flags from the `lineEndingPattern` to avoid issues with lastIndex.
this.#lineEndingPattern = new RegExp(
lineEndingPattern.source,
lineEndingPattern.flags.replace(/[gy]/gu, ""),
);
}
/**
* Finds the next line in the source text and updates `#lines` and `#lineStartIndices`.
* @param {string} text The text to search for the next line.
* @returns {boolean} `true` if a next line was found, `false` otherwise.
*/
#findNextLine(text) {
const match = this.#lineEndingPattern.exec(text);
if (!match) {
return false;
}
this.#lines.push(text.slice(0, match.index));
this.#lineStartIndices.push(
(this.#lineStartIndices.at(-1) ?? 0) +
match.index +
match[0].length,
);
return true;
}
/**
* Ensures `#lines` is lazily calculated from the source text.
* @returns {void}
*/
#ensureLines() {
// If `#lines` has already been calculated, do nothing.
if (this.#lines.length === this.#lineStartIndices.length) {
return;
}
while (
this.#findNextLine(this.text.slice(this.#lineStartIndices.at(-1)))
) {
// Continue parsing until no more matches are found.
}
this.#lines.push(this.text.slice(this.#lineStartIndices.at(-1)));
Object.freeze(this.#lines);
}
/**
* Ensures `#lineStartIndices` is lazily calculated up to the specified index.
* @param {number} index The index of a character in a file.
* @returns {void}
*/
#ensureLineStartIndicesFromIndex(index) {
// If we've already parsed up to or beyond this index, do nothing.
if (index <= (this.#lineStartIndices.at(-1) ?? 0)) {
return;
}
while (
index > (this.#lineStartIndices.at(-1) ?? 0) &&
this.#findNextLine(this.text.slice(this.#lineStartIndices.at(-1)))
) {
// Continue parsing until no more matches are found.
}
}
/**
* Ensures `#lineStartIndices` is lazily calculated up to the specified loc.
* @param {Object} loc A line/column location.
* @param {number} loc.line The line number of the location. (0 or 1-indexed based on language.)
* @param {number} lineStart The line number at which the parser starts counting.
* @returns {void}
*/
#ensureLineStartIndicesFromLoc(loc, lineStart) {
// Calculate line indices up to the potentially next line, as it is needed for the follow‑up calculation.
const nextLocLineIndex = loc.line - lineStart + 1;
const lastCalculatedLineIndex = this.#lineStartIndices.length - 1;
let additionalLinesNeeded = nextLocLineIndex - lastCalculatedLineIndex;
// If we've already parsed up to or beyond this line, do nothing.
if (additionalLinesNeeded <= 0) {
return;
}
while (
additionalLinesNeeded > 0 &&
this.#findNextLine(this.text.slice(this.#lineStartIndices.at(-1)))
) {
// Continue parsing until no more matches are found or we have enough lines.
additionalLinesNeeded -= 1;
}
}
/**
* Returns the loc information for the given node or token.
* @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the loc information for.
* @returns {SourceLocation} The loc information for the node or token.
* @throws {Error} If the node or token does not have loc information.
*/
getLoc(nodeOrToken) {
if (hasESTreeStyleLoc(nodeOrToken)) {
return nodeOrToken.loc;
}
if (hasPosStyleLoc(nodeOrToken)) {
return nodeOrToken.position;
}
throw new Error(
"Custom getLoc() method must be implemented in the subclass.",
);
}
/**
* Converts a source text index into a `{ line: number, column: number }` pair.
* @param {number} index The index of a character in a file.
* @throws {TypeError|RangeError} If non-numeric index or index out of range.
* @returns {{line: number, column: number}} A `{ line: number, column: number }` location object with 0 or 1-indexed line and 0 or 1-indexed column based on language.
* @public
*/
getLocFromIndex(index) {
if (typeof index !== "number") {
throw new TypeError("Expected `index` to be a number.");
}
if (index < 0 || index > this.text.length) {
throw new RangeError(
`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`,
);
}
const {
start: { line: lineStart, column: columnStart },
end: { line: lineEnd, column: columnEnd },
} = this.getLoc(this.ast);
// If the index is at the start, return the start location of the root node.
if (index === 0) {
return {
line: lineStart,
column: columnStart,
};
}
// If the index is `this.text.length`, return the location one "spot" past the last character of the file.
if (index === this.text.length) {
return {
line: lineEnd,
column: columnEnd,
};
}
// Ensure `#lineStartIndices` are lazily calculated.
this.#ensureLineStartIndicesFromIndex(index);
/*
* To figure out which line `index` is on, determine the last place at which index could
* be inserted into `#lineStartIndices` to keep the list sorted.
*/
const lineNumber =
(index >= (this.#lineStartIndices.at(-1) ?? 0)
? this.#lineStartIndices.length
: findLineNumberBinarySearch(this.#lineStartIndices, index)) -
1 +
lineStart;
return {
line: lineNumber,
column:
index -
this.#lineStartIndices[lineNumber - lineStart] +
columnStart,
};
}
/**
* Converts a `{ line: number, column: number }` pair into a source text index.
* @param {Object} loc A line/column location.
* @param {number} loc.line The line number of the location. (0 or 1-indexed based on language.)
* @param {number} loc.column The column number of the location. (0 or 1-indexed based on language.)
* @throws {TypeError|RangeError} If `loc` is not an object with a numeric
* `line` and `column`, if the `line` is less than or equal to zero or
* the `line` or `column` is out of the expected range.
* @returns {number} The index of the line/column location in a file.
* @public
*/
getIndexFromLoc(loc) {
if (
loc === null ||
typeof loc !== "object" ||
typeof loc.line !== "number" ||
typeof loc.column !== "number"
) {
throw new TypeError(
"Expected `loc` to be an object with numeric `line` and `column` properties.",
);
}
const {
start: { line: lineStart, column: columnStart },
end: { line: lineEnd, column: columnEnd },
} = this.getLoc(this.ast);
if (loc.line < lineStart || lineEnd < loc.line) {
throw new RangeError(
`Line number out of range (line ${loc.line} requested). Valid range: ${lineStart}-${lineEnd}`,
);
}
// If the loc is at the start, return the start index of the root node.
if (loc.line === lineStart && loc.column === columnStart) {
return 0;
}
// If the loc is at the end, return the index one "spot" past the last character of the file.
if (loc.line === lineEnd && loc.column === columnEnd) {
return this.text.length;
}
// Ensure `#lineStartIndices` are lazily calculated.
this.#ensureLineStartIndicesFromLoc(loc, lineStart);
const isLastLine = loc.line === lineEnd;
const lineStartIndex = this.#lineStartIndices[loc.line - lineStart];
const lineEndIndex = isLastLine
? this.text.length
: this.#lineStartIndices[loc.line - lineStart + 1];
const positionIndex = lineStartIndex + loc.column - columnStart;
if (
loc.column < columnStart ||
(isLastLine && positionIndex > lineEndIndex) ||
(!isLastLine && positionIndex >= lineEndIndex)
) {
throw new RangeError(
`Column number out of range (column ${loc.column} requested). Valid range for line ${loc.line}: ${columnStart}-${lineEndIndex - lineStartIndex + columnStart + (isLastLine ? 0 : -1)}`,
);
}
return positionIndex;
}
/**
* Returns the range information for the given node or token.
* @param {Options['SyntaxElementWithLoc']} nodeOrToken The node or token to get the range information for.
* @returns {SourceRange} The range information for the node or token.
* @throws {Error} If the node or token does not have range information.
*/
getRange(nodeOrToken) {
if (hasESTreeStyleRange(nodeOrToken)) {
return nodeOrToken.range;
}
if (hasPosStyleRange(nodeOrToken)) {
return [
nodeOrToken.position.start.offset,
nodeOrToken.position.end.offset,
];
}
throw new Error(
"Custom getRange() method must be implemented in the subclass.",
);
}
/* eslint-disable no-unused-vars -- Required to complete interface. */
/**
* Returns the parent of the given node.
* @param {Options['SyntaxElementWithLoc']} node The node to get the parent of.
* @returns {Options['SyntaxElementWithLoc']|undefined} The parent of the node.
* @throws {Error} If the method is not implemented in the subclass.
*/
getParent(node) {
throw new Error("Not implemented.");
}
/* eslint-enable no-unused-vars -- Required to complete interface. */
/**
* Gets all the ancestors of a given node
* @param {Options['SyntaxElementWithLoc']} node The node
* @returns {Array<Options['SyntaxElementWithLoc']>} All the ancestor nodes in the AST, not including the provided node, starting
* from the root node at index 0 and going inwards to the parent node.
* @throws {TypeError} When `node` is missing.
*/
getAncestors(node) {
if (!node) {
throw new TypeError("Missing required argument: node.");
}
const ancestorsStartingAtParent = [];
for (
let ancestor = this.getParent(node);
ancestor;
ancestor = this.getParent(ancestor)
) {
ancestorsStartingAtParent.push(ancestor);
}
return ancestorsStartingAtParent.reverse();
}
/**
* Gets the source code for the given node.
* @param {Options['SyntaxElementWithLoc']} [node] The AST node to get the text for.
* @param {number} [beforeCount] The number of characters before the node to retrieve.
* @param {number} [afterCount] The number of characters after the node to retrieve.
* @returns {string} The text representing the AST node.
* @public
*/
getText(node, beforeCount, afterCount) {
if (node) {
const range = this.getRange(node);
return this.text.slice(
Math.max(range[0] - (beforeCount || 0), 0),
range[1] + (afterCount || 0),
);
}
return this.text;
}
/**
* Gets the entire source text split into an array of lines.
* @returns {Array<string>} The source text as an array of lines.
* @public
*/
get lines() {
this.#ensureLines(); // Ensure `#lines` is lazily calculated.
return this.#lines;
}
/**
* Traverse the source code and return the steps that were taken.
* @returns {Iterable<TraversalStep>} The steps that were taken while traversing the source code.
*/
traverse() {
throw new Error("Not implemented.");
}
}
export { CallMethodStep, ConfigCommentParser, Directive, TextSourceCodeBase, VisitNodeStep };
@@ -0,0 +1 @@
{"version":3,"file":"use-motion-template.mjs","sources":["../../../src/value/use-motion-template.ts"],"sourcesContent":["\"use client\"\n\nimport { isMotionValue, MotionValue } from \"motion-dom\"\nimport { useCombineMotionValues } from \"./use-combine-values\"\n\n/**\n * Combine multiple motion values into a new one using a string template literal.\n *\n * ```jsx\n * import {\n * motion,\n * useSpring,\n * useMotionValue,\n * useMotionTemplate\n * } from \"framer-motion\"\n *\n * function Component() {\n * const shadowX = useSpring(0)\n * const shadowY = useMotionValue(0)\n * const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`\n *\n * return <motion.div style={{ filter: shadow }} />\n * }\n * ```\n *\n * @public\n */\nexport function useMotionTemplate(\n fragments: TemplateStringsArray,\n ...values: Array<MotionValue | number | string>\n) {\n /**\n * Create a function that will build a string from the latest motion values.\n */\n const numFragments = fragments.length\n\n function buildValue() {\n let output = ``\n\n for (let i = 0; i < numFragments; i++) {\n output += fragments[i]\n const value = values[i]\n if (value) {\n output += isMotionValue(value) ? value.get() : value\n }\n }\n\n return output\n }\n\n return useCombineMotionValues(values.filter(isMotionValue), buildValue)\n}\n"],"names":[],"mappings":";;;;AAKA;;;;;;;;;;;;;;;;;;;;;AAqBG;;AAKC;;AAEG;AACH;AAEA;;AAGI;AACI;AACA;;AAEI;;;AAIR;;;AAIR;;"}
@@ -0,0 +1,58 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepPartial = deepPartial;
const visit_js_1 = require("../core/visit.cjs");
const schemas = __importStar(require("./schemas.cjs"));
/** See `classic/deep-partial.ts`. Mini variant uses `mini.partial(...)`. */
function deepPartial(schema) {
return (0, visit_js_1.visit)(schema, {
object: (s) => schemas.partial(s),
// See `classic/deep-partial.ts`.
union: (s) => {
const def = s._zod.def;
return def.discriminator === undefined ? s : schemas.union(def.options);
},
});
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
@@ -0,0 +1,11 @@
"use client";
import { createContext } from 'react';
/**
* @public
*/
const PresenceContext =
/* @__PURE__ */ createContext(null);
export { PresenceContext };
//# sourceMappingURL=PresenceContext.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"otpauth.umd.min.js","sources":["../node_modules/@noble/hashes/utils.js","../node_modules/@noble/hashes/hmac.js","../node_modules/@noble/hashes/_md.js","../node_modules/@noble/hashes/legacy.js","../node_modules/@noble/hashes/_u64.js","../node_modules/@noble/hashes/sha2.js","../node_modules/@noble/hashes/sha3.js","../src/internal/global-scope.js","../src/internal/crypto/hmac-digest.js","../src/internal/encoding/base32.js","../src/internal/encoding/hex.js","../src/internal/encoding/latin1.js","../src/internal/encoding/utf8.js","../src/secret.js","../src/internal/crypto/random-bytes.js","../src/hotp.js","../src/internal/encoding/uint.js","../src/internal/crypto/timing-safe-equal.js","../src/totp.js","../src/uri.js","../src/version.js"],"sourcesContent":["/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return value;\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers trLine truncated
@@ -0,0 +1,956 @@
'use strict'
const util = require('../core/util')
const { kRedirectCacheControl } = require('../core/symbols')
const {
parseCacheControlHeader,
hasInvalidCacheControlDirective,
parseVaryHeader,
hasVaryStar,
isInvalidOrWildcardVaryHeader,
isEtagUsable
} = require('../util/cache')
const { parseHttpDate } = require('../util/date.js')
function noop () {}
class CacheController {
#blocked = false
#downstreamPaused = false
constructor (target) {
this.target = target
}
block () {
this.#blocked = true
}
release () {
this.#blocked = false
if (!this.#downstreamPaused) {
this.target.resume()
}
}
pause () {
this.#downstreamPaused = true
this.target.pause()
}
resume () {
this.#downstreamPaused = false
if (!this.#blocked) {
this.target.resume()
}
}
abort (reason) {
this.target.abort(reason)
}
get paused () { return this.#downstreamPaused }
get aborted () { return this.target.aborted }
get reason () { return this.target.reason }
get rawHeaders () { return this.target.rawHeaders }
set rawHeaders (value) { this.target.rawHeaders = value }
get rawTrailers () { return this.target.rawTrailers }
set rawTrailers (value) { this.target.rawTrailers = value }
}
/**
* @param {string | URL} a
* @param {string | URL} b
* @returns {boolean}
*/
function sameOrigin (a, b) {
try {
return new URL(String(a)).origin === new URL(String(b)).origin
} catch {
return String(a) === String(b)
}
}
// Status codes that we can use some heuristics on to cache
const HEURISTICALLY_CACHEABLE_STATUS_CODES = [
200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414, 501
]
// Status codes which semantic is not handled by the cache
// https://datatracker.ietf.org/doc/html/rfc9111#section-3
// This list should not grow beyond 206 unless the RFC is updated
// by a newer one including more. Please introduce another list if
// implementing caching of responses with the 'must-understand' directive.
const NOT_UNDERSTOOD_STATUS_CODES = [
206
]
const MAX_RESPONSE_AGE = 2147483647000
// Retention for revalidation-only entries (zero freshness lifetime but a
// validator present); each successful revalidation re-stores the entry.
const REVALIDATION_ONLY_RETENTION = 86400000 // 24 hours
function trimOWS (value) {
return value.replace(/^[\t ]+|[\t ]+$/g, '')
}
function arrayIncludes (array, value) {
for (let i = 0; i < array.length; i++) {
if (array[i] === value) {
return true
}
}
return false
}
function appendConnectionHeaderTokens (headersToRemove, connectionHeader) {
const values = Array.isArray(connectionHeader) ? connectionHeader : [connectionHeader]
for (let i = 0; i < values.length; i++) {
const tokens = values[i].split(',')
for (let j = 0; j < tokens.length; j++) {
headersToRemove.push(trimOWS(tokens[j]).toLowerCase())
}
}
}
function getSameOriginPath (cacheKey, location) {
if (typeof location !== 'string') {
return undefined
}
let originUrl
let requestUrl
let locationUrl
try {
originUrl = new URL(cacheKey.origin)
requestUrl = new URL(cacheKey.path, originUrl)
locationUrl = new URL(location, requestUrl)
} catch {
return undefined
}
if (locationUrl.origin !== originUrl.origin) {
return undefined
}
return locationUrl.pathname + locationUrl.search
}
function deleteCachedUri (store, cacheKey, path) {
deleteCachedValue(store, {
...cacheKey,
path
})
for (let i = 0; i < util.safeHTTPMethods.length; i++) {
const method = util.safeHTTPMethods[i]
if (method !== cacheKey.method) {
deleteCachedValue(store, {
...cacheKey,
method,
path
})
}
}
}
function deleteLocationTargets (store, cacheKey, headerValue) {
if (headerValue === undefined) {
return
}
const values = Array.isArray(headerValue) ? headerValue : [headerValue]
for (let i = 0; i < values.length; i++) {
const path = getSameOriginPath(cacheKey, values[i])
if (path !== undefined) {
deleteCachedUri(store, cacheKey, path)
}
}
}
function invalidateUnsafeRequest (store, cacheKey, resHeaders) {
deleteCachedUri(store, cacheKey, cacheKey.path)
deleteLocationTargets(store, cacheKey, resHeaders.location)
deleteLocationTargets(store, cacheKey, resHeaders['content-location'])
}
/**
* @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler
*
* @implements {DispatchHandler}
*/
class CacheHandler {
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
#cacheKey
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']}
*/
#cacheType
/**
* @type {number | undefined}
*/
#cacheByDefault
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheStore}
*/
#store
/**
* @type {import('../../types/dispatcher.d.ts').default.DispatchHandler}
*/
#handler
/**
* @type {CacheController | undefined}
*/
#downstreamController
/**
* @type {import('node:stream').Writable | undefined}
*/
#writeStream
/**
* The URLs visited while following redirects, shared by reference from the
* redirect handler through the request context. Carries the suppressed hops'
* cache-control under {@link kRedirectCacheControl}.
* @type {URL[] | undefined}
*/
#history
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
*/
constructor ({ store, type, cacheByDefault }, cacheKey, handler) {
this.#store = store
this.#cacheType = type
this.#cacheByDefault = cacheByDefault
this.#cacheKey = cacheKey
this.#handler = handler
}
onRequestStart (controller, context) {
this.#writeStream?.destroy()
this.#writeStream = undefined
this.#downstreamController = new CacheController(controller)
// The redirect handler threads the list of visited URLs through the
// handler-chain context. Keep a reference to it (it is mutated as redirects
// are followed) so onResponseStart can tell which request actually produced
// the response. Unlike the request options object, this reference is not
// broken by an interceptor that copies the options between the cache and
// the redirect.
this.#history = context?.history
this.#handler.onRequestStart?.(this.#downstreamController, context)
}
onBodySent (chunk) {
this.#handler.onBodySent?.(chunk)
}
onRequestSent () {
this.#handler.onRequestSent?.()
}
onRequestUpgrade (_controller, statusCode, headers, socket) {
this.#handler.onRequestUpgrade?.(this.#downstreamController, statusCode, headers, socket)
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {string} statusMessage
*/
onResponseStart (
controller,
statusCode,
resHeaders,
statusMessage
) {
const downstreamOnHeaders = () =>
this.#handler.onResponseStart?.(
this.#downstreamController,
statusCode,
resHeaders,
statusMessage
)
const handler = this
if (
!arrayIncludes(util.safeHTTPMethods, this.#cacheKey.method) &&
statusCode >= 200 &&
statusCode <= 399
) {
// Successful response to an unsafe method, delete it from cache
// https://www.rfc-editor.org/rfc/rfc9111.html#name-invalidating-stored-response
invalidateUnsafeRequest(this.#store, this.#cacheKey, resHeaders)
return downstreamOnHeaders()
}
// A cross-origin redirect can change the origin that actually produced the
// final response. Keying that response on the original (trusted) origin
// would let a redirect target control an entry for a URL the application
// trusts. The final request is the last URL in the redirect history; only
// cache when its origin still matches the cache key origin.
if (this.#history && this.#history.length > 0) {
const finalUrl = this.#history[this.#history.length - 1]
if (!sameOrigin(finalUrl.origin, this.#cacheKey.origin)) {
return downstreamOnHeaders()
}
}
// A redirect hop that is not forwarded can still carry a restrictive
// storage policy (for example `no-store`, or `private` for a shared cache).
// Honor it, otherwise a redirect that must not be stored could be laundered
// into a cacheable final response under the original key.
const redirectCacheControl = this.#history?.[kRedirectCacheControl]
if (redirectCacheControl) {
for (const hopCacheControl of redirectCacheControl) {
const hopDirectives = hopCacheControl ? parseCacheControlHeader(hopCacheControl) : {}
if (
hopDirectives['no-store'] === true ||
(this.#cacheType === 'shared' && hopDirectives.private === true)
) {
return downstreamOnHeaders()
}
}
}
const cacheControlHeader = resHeaders['cache-control']
const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {}
if (revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives)) {
deleteCachedValue(this.#store, this.#cacheKey)
return downstreamOnHeaders()
}
const heuristicallyCacheable = resHeaders['last-modified'] && arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode)
if (
!cacheControlHeader &&
!resHeaders['expires'] &&
!heuristicallyCacheable &&
!this.#cacheByDefault
) {
if (statusCode === 304 && resHeaders.vary && isInvalidOrWildcardVaryHeader(resHeaders.vary)) {
deleteCachedValue(this.#store, this.#cacheKey)
}
// Don't have anything to tell us this response is cachable and we're not
// caching by default
return downstreamOnHeaders()
}
if (!canCacheResponse(this.#cacheType, this.#cacheKey.method, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
if (statusCode === 304 && (cacheControlHeader || revalidationResponseDisallowsCachedReuse(this.#cacheType, resHeaders, cacheControlDirectives))) {
deleteCachedValue(this.#store, this.#cacheKey)
}
return downstreamOnHeaders()
}
const now = Date.now()
const resAge = Object.hasOwn(resHeaders, 'age') ? getAge(resHeaders.age) : undefined
if (resAge !== undefined && resAge >= MAX_RESPONSE_AGE) {
// Response considered stale
deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey)
return downstreamOnHeaders()
}
const resDate = Object.hasOwn(resHeaders, 'date') ? getDate(resHeaders.date) : undefined
if (resDate === null) {
deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey)
return downstreamOnHeaders()
}
const apparentAge = resDate ? Math.max(0, now - resDate.getTime()) : 0
const currentAge = Math.max(apparentAge, resAge ?? 0)
const hasValidator =
(typeof resHeaders.etag === 'string' && isEtagUsable(resHeaders.etag)) ||
typeof resHeaders['last-modified'] === 'string'
const staleAt =
determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives, hasValidator) ??
this.#cacheByDefault
// Zero freshness lifetime but a validator: stale from the start, yet still
// storable since each reuse is preceded by a revalidation request.
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.4
const revalidationOnly = staleAt === 0 && hasValidator
if (staleAt === undefined || (currentAge >= staleAt && !revalidationOnly)) {
if (cacheControlHeader || staleAt !== undefined) {
deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey)
}
return downstreamOnHeaders()
}
const baseTime = now - currentAge
const absoluteStaleAt = staleAt + baseTime
if (now >= absoluteStaleAt && !revalidationOnly) {
// Response is already stale
deleteCachedValueIfNotModified(statusCode, this.#store, this.#cacheKey)
return downstreamOnHeaders()
}
let varyDirectives
if (this.#cacheKey.headers && resHeaders.vary) {
varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers)
if (!varyDirectives) {
// Parse error
return downstreamOnHeaders()
}
}
const cachedAt = baseTime
const deleteAt = determineDeleteAt(baseTime, now, cacheControlDirectives, absoluteStaleAt)
const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives)
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value = {
statusCode,
statusMessage,
headers: strippedHeaders,
vary: varyDirectives,
cacheControlDirectives,
cachedAt,
staleAt: absoluteStaleAt,
deleteAt
}
// Not modified, re-use the cached value
// https://www.rfc-editor.org/rfc/rfc9111.html#name-handling-304-not-modified
if (statusCode === 304) {
let done = false
const finish304 = () => {
if (done) {
return
}
done = true
this.#downstreamController.release()
}
const handle304 = (cachedValue) => {
if (!cachedValue) {
// Do not create a new cache entry, as a 304 won't have a body - so cannot be cached.
downstreamOnHeaders()
finish304()
return
}
// Re-use the cached value: statuscode, statusmessage, headers and body
value.statusCode = cachedValue.statusCode
value.statusMessage = cachedValue.statusMessage
value.etag = cachedValue.etag
value.vary = varyDirectives ?? cachedValue.vary
value.headers = { ...cachedValue.headers, ...strippedHeaders }
downstreamOnHeaders()
this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value)
if (!this.#writeStream || !cachedValue?.body) {
finish304()
return
}
if (typeof cachedValue.body.values === 'function') {
const bodyIterator = cachedValue.body.values()
const streamCachedBody = () => {
if (done) {
return
}
for (const chunk of bodyIterator) {
const full = this.#writeStream?.write(chunk) === false
this.#handler.onResponseData?.(this.#downstreamController, chunk)
// when stream is full stop writing until we get a 'drain' event
if (full) {
return
}
}
finish304()
}
this.#writeStream
.on('error', function () {
handler.#writeStream = undefined
handler.#store.delete(handler.#cacheKey)
// Keep replaying downstream without the store
streamCachedBody()
})
.on('drain', () => {
streamCachedBody()
})
.on('close', function () {
if (handler.#writeStream === this) {
handler.#writeStream = undefined
// Keep replaying downstream without the store
streamCachedBody()
}
})
streamCachedBody()
} else if (typeof cachedValue.body.on === 'function') {
// Readable stream body (e.g. from async/remote cache stores)
cachedValue.body
.on('data', (chunk) => {
this.#writeStream?.write(chunk)
this.#handler.onResponseData?.(this.#downstreamController, chunk)
})
.on('end', () => {
this.#writeStream?.end()
finish304()
})
.on('error', () => {
this.#writeStream = undefined
this.#store.delete(this.#cacheKey)
finish304()
})
this.#writeStream
.on('error', function () {
handler.#writeStream = undefined
handler.#store.delete(handler.#cacheKey)
})
.on('close', function () {
if (handler.#writeStream === this) {
handler.#writeStream = undefined
}
})
} else {
finish304()
}
}
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const result = this.#store.get(this.#cacheKey)
// A 304 ends before the cached body is replayed. Keep the origin
// response paused until replay is complete.
this.#downstreamController.block()
controller.pause()
if (result && typeof result.then === 'function') {
result.then(handle304, () => handle304(undefined)).catch((err) => {
controller.abort(err)
})
} else {
handle304(result)
}
} else {
if (typeof resHeaders.etag === 'string' && isEtagUsable(resHeaders.etag)) {
value.etag = resHeaders.etag
}
this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value)
if (!this.#writeStream) {
return downstreamOnHeaders()
}
this.#writeStream
.on('drain', () => controller.resume())
.on('error', function () {
// TODO (fix): Make error somehow observable?
handler.#writeStream = undefined
// Delete the value in case the cache store is holding onto state from
// the call to createWriteStream
handler.#store.delete(handler.#cacheKey)
})
.on('close', function () {
if (handler.#writeStream === this) {
handler.#writeStream = undefined
}
// TODO (fix): Should we resume even if was paused downstream?
controller.resume()
})
downstreamOnHeaders()
}
}
onResponseData (controller, chunk) {
if (this.#writeStream?.write(chunk) === false) {
controller.pause()
}
this.#handler.onResponseData?.(this.#downstreamController, chunk)
}
onResponseEnd (controller, trailers) {
this.#writeStream?.end()
this.#handler.onResponseEnd?.(this.#downstreamController, trailers)
}
onResponseError (controller, err) {
this.#writeStream?.destroy(err)
this.#writeStream = undefined
this.#handler.onResponseError?.(this.#downstreamController, err)
}
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheStore} store
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
*/
function deleteCachedValue (store, cacheKey) {
try {
store.delete(cacheKey)?.catch?.(noop)
} catch {
// Fail silently
}
}
function deleteCachedValueIfNotModified (statusCode, store, cacheKey) {
if (statusCode === 304) {
deleteCachedValue(store, cacheKey)
}
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @returns {boolean}
*/
function revalidationResponseDisallowsCachedReuse (cacheType, resHeaders, cacheControlDirectives) {
return cacheControlDirectives['no-store'] === true ||
(cacheType === 'shared' && (
cacheControlDirectives.private === true ||
Object.hasOwn(resHeaders, 'set-cookie')
)) ||
(resHeaders.vary ? isInvalidOrWildcardVaryHeader(resHeaders.vary) : false)
}
/**
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
*
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType
* @param {string} method
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} [reqHeaders]
*/
function canCacheResponse (cacheType, method, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
if (!arrayIncludes(util.safeHTTPMethods, method)) {
return false
}
// Status code must be final and understood.
if (statusCode < 200 || arrayIncludes(NOT_UNDERSTOOD_STATUS_CODES, statusCode)) {
return false
}
// Responses with neither status codes that are heuristically cacheable, nor "explicit enough" caching
// directives, are not cacheable. "Explicit enough": see https://www.rfc-editor.org/rfc/rfc9111.html#section-3
if (!arrayIncludes(HEURISTICALLY_CACHEABLE_STATUS_CODES, statusCode) && !resHeaders['expires'] &&
!cacheControlDirectives.public &&
cacheControlDirectives['max-age'] === undefined &&
// RFC 9111: a private response directive, if the cache is not shared
!(cacheControlDirectives.private && cacheType === 'private') &&
!(cacheControlDirectives['s-maxage'] !== undefined && cacheType === 'shared')
) {
return false
}
if (cacheControlDirectives['no-store']) {
return false
}
if (cacheType === 'shared' && (
cacheControlDirectives.private === true ||
Object.hasOwn(resHeaders, 'set-cookie')
)) {
return false
}
// https://www.rfc-editor.org/rfc/rfc9111.html#section-4.1-5
if (resHeaders.vary && hasVaryStar(resHeaders.vary)) {
return false
}
// https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
if (reqHeaders != null && Object.hasOwn(reqHeaders, 'authorization')) {
if (
!cacheControlDirectives.public &&
!cacheControlDirectives['s-maxage'] &&
!cacheControlDirectives['must-revalidate']
) {
return false
}
if (typeof reqHeaders.authorization !== 'string') {
return false
}
if (
Array.isArray(cacheControlDirectives['no-cache']) &&
arrayIncludes(cacheControlDirectives['no-cache'], 'authorization')
) {
return false
}
if (
Array.isArray(cacheControlDirectives['private']) &&
arrayIncludes(cacheControlDirectives['private'], 'authorization')
) {
return false
}
}
return true
}
/**
* @param {string | string[]} dateHeader
* @returns {Date | null | undefined}
*/
function getDate (dateHeader) {
let dateValue = dateHeader
if (Array.isArray(dateValue)) {
if (dateValue.length !== 1) {
return null
}
dateValue = dateValue[0]
}
if (typeof dateValue !== 'string') {
return null
}
return parseHttpDate(dateValue)
}
/**
* @param {string | string[]} ageHeader
* @returns {number | undefined}
*/
function getAge (ageHeader) {
let ageValue = ageHeader
if (Array.isArray(ageValue)) {
if (ageValue.length !== 1) {
return MAX_RESPONSE_AGE
}
ageValue = ageValue[0]
}
if (typeof ageValue !== 'string' || !/^[\t ]*[0-9]+[\t ]*$/.test(ageValue)) {
return MAX_RESPONSE_AGE
}
const age = BigInt(ageValue.replace(/^[\t ]+|[\t ]+$/g, ''))
if (age >= BigInt(MAX_RESPONSE_AGE / 1000)) {
return MAX_RESPONSE_AGE
}
return Number(age) * 1000
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType
* @param {number} now
* @param {number | undefined} age
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {Date | undefined} responseDate
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {boolean} hasValidator whether the response has a validator (etag or
* last-modified) that revalidation requests can be made with
*
* @returns {number | undefined} time that the value is stale at in seconds or undefined if it shouldn't be cached
*/
function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheControlDirectives, hasValidator) {
if (cacheType === 'shared') {
// Prioritize s-maxage since we're a shared cache
// s-maxage > max-age > Expire
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10-3
if (hasInvalidCacheControlDirective(cacheControlDirectives, 's-maxage')) {
return 0
}
const sMaxAge = cacheControlDirectives['s-maxage']
if (sMaxAge !== undefined) {
if (sMaxAge > 0) {
return sMaxAge * 1000
}
// Immediately stale, but storable if we can revalidate it before reuse.
return 0
}
}
if (hasInvalidCacheControlDirective(cacheControlDirectives, 'max-age')) {
return 0
}
const maxAge = cacheControlDirectives['max-age']
if (maxAge !== undefined) {
if (maxAge > 0) {
return maxAge * 1000
}
// Immediately stale, but storable if we can revalidate it before reuse.
return 0
}
if (Object.hasOwn(resHeaders, 'expires')) {
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.3
if (typeof resHeaders.expires !== 'string') {
return 0
}
const expiresDate = parseHttpDate(resHeaders.expires)
if (!expiresDate) {
return 0
}
if (now >= expiresDate.getTime()) {
return 0
}
if (responseDate) {
if (responseDate >= expiresDate) {
return 0
}
const freshnessLifetime = expiresDate.getTime() - responseDate.getTime()
if (age !== undefined && age >= freshnessLifetime) {
return 0
}
return freshnessLifetime
}
return expiresDate.getTime() - now
}
if (typeof resHeaders['last-modified'] === 'string') {
// https://www.rfc-editor.org/rfc/rfc9111.html#name-calculating-heuristic-fresh
const lastModified = parseHttpDate(resHeaders['last-modified'])
if (lastModified) {
if (lastModified.getTime() >= now) {
return undefined
}
const responseAge = now - lastModified.getTime()
return responseAge * 0.1
}
}
if (cacheControlDirectives.immutable) {
// https://www.rfc-editor.org/rfc/rfc8246.html#section-2.2
return 31536000000
}
if (cacheControlDirectives['no-cache'] === true && hasValidator) {
// No freshness source, but a validator lets us revalidate before reuse.
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.4
return 0
}
return undefined
}
/**
* @param {number} baseTime
* @param {number} cachedAt
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {number} staleAt
*/
function determineDeleteAt (baseTime, cachedAt, cacheControlDirectives, staleAt) {
let staleWhileRevalidate = -Infinity
let staleIfError = -Infinity
let immutable = -Infinity
if (cacheControlDirectives['stale-while-revalidate']) {
staleWhileRevalidate = staleAt + (cacheControlDirectives['stale-while-revalidate'] * 1000)
}
if (cacheControlDirectives['stale-if-error']) {
staleIfError = staleAt + (cacheControlDirectives['stale-if-error'] * 1000)
}
if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
immutable = cachedAt + 31536000000
}
// When no stale directives or immutable flag, add a revalidation buffer
// equal to the freshness lifetime so the entry survives past staleAt long
// enough to be revalidated instead of silently disappearing.
//
// Response Date headers only have second precision, so baseTime can trail the
// actual cache insertion time by up to ~1s. Pad the buffer by that bounded
// skew so short-lived entries do not disappear exactly when they should be
// revalidated.
if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
const freshnessLifetime = staleAt - baseTime
if (freshnessLifetime <= 0) {
// Revalidation-only entry: no freshness lifetime to size the buffer on,
// so retain it for a bounded window instead.
return cachedAt + REVALIDATION_ONLY_RETENTION
}
const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1000)
return staleAt + freshnessLifetime + datePrecisionPadding
}
return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable)
}
/**
* Strips headers required to be removed in cached responses
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @returns {Record<string, string | string []>}
*/
function stripNecessaryHeaders (resHeaders, cacheControlDirectives) {
const headersToRemove = [
'connection',
'proxy-authenticate',
'proxy-authentication-info',
'proxy-authorization',
'proxy-connection',
'te',
'transfer-encoding',
'upgrade',
// We'll add age back when serving it
'age'
]
if (resHeaders['connection']) {
appendConnectionHeaderTokens(headersToRemove, resHeaders['connection'])
}
if (Array.isArray(cacheControlDirectives['no-cache'])) {
headersToRemove.push(...cacheControlDirectives['no-cache'])
}
if (Array.isArray(cacheControlDirectives['private'])) {
headersToRemove.push(...cacheControlDirectives['private'])
}
let strippedHeaders
for (const headerName of headersToRemove) {
if (Object.hasOwn(resHeaders, headerName)) {
strippedHeaders ??= { ...resHeaders }
delete strippedHeaders[headerName]
}
}
return strippedHeaders ?? resHeaders
}
module.exports = CacheHandler
@@ -0,0 +1,2 @@
import { n as CfWorkerSchemaDraft, t as CfWorkerJsonSchemaValidator } from "../cfWorkerProvider-B3ZJEoRM.mjs";
export { CfWorkerJsonSchemaValidator, type CfWorkerSchemaDraft };
@@ -0,0 +1,166 @@
// Hand-maintained declaration for the node:sqlite compatibility shim
// (lib/compat.js). The documented divergences from node:sqlite's surface
// are listed in the implementation file's header comment.
import type {
ApplyChangesetOptions,
Database,
Row,
Session,
} from './native.js';
/**
* A prepared statement in the node:sqlite StatementSync shape, wrapping
* this package's synchronous fast path.
*
* @since 9.1.0
*/
export declare class StatementSync {
/** True once finalized (explicitly or through dispose). */
get finalized(): boolean;
/** The statement's SQL text. */
get sourceSQL(): string;
/** The SQL with the most recent bound values substituted. */
get expandedSQL(): string;
/** The statement's result columns. */
columns(): Array<{
name: string;
database?: string;
table?: string;
column?: string;
type?: string;
}>;
/** Steps once and returns the first row (or undefined). */
get(...params: unknown[]): Row | undefined;
/** Steps to completion and returns every row. */
all(...params: unknown[]): Row[];
/** Runs the statement, returning `{ changes, lastInsertRowid }`. */
run(...params: unknown[]): {
changes: number | bigint;
lastInsertRowid: number | bigint;
};
/**
* A synchronous iterator over the rows. Divergence: the rows are
* materialised first (the sync fast path has no mid-cursor
* suspension).
*/
iterate(...params: unknown[]): IterableIterator<Row>;
/**
* Sets whether integers read as BigInt, re-preparing the statement
* (the integer mode belongs to the prepared statement here).
*/
setReadBigInts(value: boolean): void;
/** Sets whether rows are arrays. */
setReturnArrays(value: boolean): void;
/** Finalizes the statement. */
close(): void;
/** `using` support. */
[Symbol.dispose](): void;
}
/**
* A connection in the node:sqlite DatabaseSync shape, mapping onto this
* package's synchronous fast path.
*
* @since 9.1.0
*/
export declare class DatabaseSync {
/**
* Opens a connection (synchronously — the connection is usable the
* moment the constructor returns).
*/
constructor(
location: string,
options?: {
readOnly?: boolean;
open?: boolean;
enableForeignKeyConstraints?: boolean;
enableDoubleQuotedStringLiterals?: boolean;
allowExtension?: boolean;
timeout?: number;
},
);
/** The underlying connection (the full async surface). */
get native(): Database;
/** True while open. */
get open(): boolean;
/** Alias of `open` (node:sqlite's name). */
get isOpen(): boolean;
/** True inside an explicit transaction. */
get isTransaction(): boolean;
/** Runs a SQL script synchronously. */
exec(sql: string): undefined;
/** Prepares a statement synchronously. */
prepare(
sql: string,
options?: {
readBigInts?: boolean;
returnArrays?: boolean;
allowBareNamedParameters?: boolean;
allowUnknownNamedParameters?: boolean;
persistent?: boolean;
},
): StatementSync;
/** Registers a scalar SQL function. */
function(
name: string,
options?:
| ((...args: unknown[]) => unknown)
| {
deterministic?: boolean;
directOnly?: boolean;
varargs?: boolean;
},
fn?: (...args: unknown[]) => unknown,
): void;
/** Registers an aggregate (or window) SQL function. */
aggregate(
name: string,
spec: {
start: () => unknown;
step: (acc: unknown, ...args: unknown[]) => unknown;
result: (acc: unknown) => unknown;
inverse?: (acc: unknown, ...args: unknown[]) => unknown;
deterministic?: boolean;
varargs?: boolean;
},
): void;
/** Loads a SQLite extension (gated by allowExtension). */
loadExtension(path: string, entryPoint?: string): void;
/** The allowExtension gate. */
enableLoadExtension(allow: boolean): void;
/** Toggles SQLite defensive mode. */
enableDefensive(active: boolean): void;
/**
* The filesystem path of an attached database, or null for an
* in-memory or temporary one (node:sqlite's shape).
*/
location(dbName?: string): string | null;
/**
* Not available: this package's authorizer is declarative by design.
* Use `db.native.authorizer(policy)`.
*/
setAuthorizer(): never;
/** Creates a changeset-recording session (async divergence). */
createSession(options?: { table?: string }): Session;
/** Applies a changeset (async divergence). */
applyChangeset(
changeset: Uint8Array,
options?: ApplyChangesetOptions,
): Promise<void>;
/** Serializes the database (async divergence). */
serialize(): Promise<Uint8Array>;
/**
* Closes the connection, finalizing the statements prepared through
* it (as node:sqlite does). The close itself is queued: the
* connection refuses further work at once, the handle is released a
* turn later. A close that still fails is reported on the underlying
* connection's 'error' event.
*/
close(): void;
/**
* `await using` support: finalizes outstanding statements, then waits
* for the close to complete.
*/
[Symbol.asyncDispose](): Promise<void>;
}
@@ -0,0 +1,514 @@
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var accepts = require('accepts');
var isIP = require('node:net').isIP;
var typeis = require('type-is');
var http = require('node:http');
var fresh = require('fresh');
var parseRange = require('range-parser');
var parse = require('parseurl');
var proxyaddr = require('proxy-addr');
/**
* Request prototype.
* @public
*/
var req = Object.create(http.IncomingMessage.prototype)
/**
* Module exports.
* @public
*/
module.exports = req
/**
* Return request header.
*
* The `Referrer` header field is special-cased,
* both `Referrer` and `Referer` are interchangeable.
*
* Examples:
*
* req.get('Content-Type');
* // => "text/plain"
*
* req.get('content-type');
* // => "text/plain"
*
* req.get('Something');
* // => undefined
*
* Aliased as `req.header()`.
*
* @param {String} name
* @return {String}
* @public
*/
req.get =
req.header = function header(name) {
if (!name) {
throw new TypeError('name argument is required to req.get');
}
if (typeof name !== 'string') {
throw new TypeError('name must be a string to req.get');
}
var lc = name.toLowerCase();
switch (lc) {
case 'referer':
case 'referrer':
return this.headers.referrer
|| this.headers.referer;
default:
return this.headers[lc];
}
};
/**
* To do: update docs.
*
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single MIME type string
* such as "application/json", an extension name
* such as "json", a comma-delimited list such as "json, html, text/plain",
* an argument list such as `"json", "html", "text/plain"`,
* or an array `["json", "html", "text/plain"]`. When a list
* or array is given, the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* req.accepts('html');
* // => "html"
*
* // Accept: text/*, application/json
* req.accepts('html');
* // => "html"
* req.accepts('text/html');
* // => "text/html"
* req.accepts('json, text');
* // => "json"
* req.accepts('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* req.accepts('image/png');
* req.accepts('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* req.accepts(['html', 'json']);
* req.accepts('html', 'json');
* req.accepts('html, json');
* // => "json"
*
* @param {String|Array} type(s)
* @return {String|Array|Boolean}
* @public
*/
req.accepts = function(){
var accept = accepts(this);
return accept.types.apply(accept, arguments);
};
/**
* Check if the given `encoding`s are accepted.
*
* @param {String} ...encoding
* @return {String|Array}
* @public
*/
req.acceptsEncodings = function(){
var accept = accepts(this);
return accept.encodings.apply(accept, arguments);
};
/**
* Check if the given `charset`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {String} ...charset
* @return {String|Array}
* @public
*/
req.acceptsCharsets = function(){
var accept = accepts(this);
return accept.charsets.apply(accept, arguments);
};
/**
* Check if the given `lang`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
*
* @param {String} ...lang
* @return {String|Array}
* @public
*/
req.acceptsLanguages = function(...languages) {
return accepts(this).languages(...languages);
};
/**
* Parse Range header field, capping to the given `size`.
*
* Unspecified ranges such as "0-" require knowledge of your resource length. In
* the case of a byte range this is of course the total number of bytes. If the
* Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
* and `-2` when syntactically invalid.
*
* When ranges are returned, the array has a "type" property which is the type of
* range that is required (most commonly, "bytes"). Each array element is an object
* with a "start" and "end" property for the portion of the range.
*
* The "combine" option can be set to `true` and overlapping & adjacent ranges
* will be combined into a single range.
*
* NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
* should respond with 4 users when available, not 3.
*
* @param {number} size
* @param {object} [options]
* @param {boolean} [options.combine=false]
* @return {number|array}
* @public
*/
req.range = function range(size, options) {
var range = this.get('Range');
if (!range) return;
return parseRange(size, range, options);
};
/**
* Parse the query string of `req.url`.
*
* This uses the "query parser" setting to parse the raw
* string into an object.
*
* @return {String}
* @api public
*/
defineGetter(req, 'query', function query(){
var queryparse = this.app.get('query parser fn');
if (!queryparse) {
// parsing is disabled
return Object.create(null);
}
var querystring = parse(this).query;
return queryparse(querystring);
});
/**
* Check if the incoming request contains the "Content-Type"
* header field, and it contains the given mime `type`.
*
* Examples:
*
* // With Content-Type: text/html; charset=utf-8
* req.is('html');
* req.is('text/html');
* req.is('text/*');
* // => true
*
* // When Content-Type is application/json
* req.is('json');
* req.is('application/json');
* req.is('application/*');
* // => true
*
* req.is('html');
* // => false
*
* @param {String|Array} types...
* @return {String|false|null}
* @public
*/
req.is = function is(types) {
var arr = types;
// support flattened arguments
if (!Array.isArray(types)) {
arr = new Array(arguments.length);
for (var i = 0; i < arr.length; i++) {
arr[i] = arguments[i];
}
}
return typeis(this, arr);
};
/**
* Return the protocol string "http" or "https"
* when requested with TLS. When the "trust proxy"
* setting trusts the socket address, the
* "X-Forwarded-Proto" header field will be trusted
* and used if present.
*
* If you're running behind a reverse proxy that
* supplies https for you this may be enabled.
*
* @return {String}
* @public
*/
defineGetter(req, 'protocol', function protocol(){
var proto = this.socket.encrypted
? 'https'
: 'http';
var trust = this.app.get('trust proxy fn');
if (!trust(this.socket.remoteAddress, 0)) {
return proto;
}
// Note: X-Forwarded-Proto is normally only ever a
// single value, but this is to be safe.
var header = this.get('X-Forwarded-Proto') || proto
var index = header.indexOf(',')
return index !== -1
? header.substring(0, index).trim()
: header.trim()
});
/**
* Short-hand for:
*
* req.protocol === 'https'
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'secure', function secure(){
return this.protocol === 'https';
});
/**
* Return the remote address from the trusted proxy.
*
* The is the remote address on the socket unless
* "trust proxy" is set.
*
* @return {String}
* @public
*/
defineGetter(req, 'ip', function ip(){
var trust = this.app.get('trust proxy fn');
return proxyaddr(this, trust);
});
/**
* When "trust proxy" is set, trusted proxy addresses + client.
*
* For example if the value were "client, proxy1, proxy2"
* you would receive the array `["client", "proxy1", "proxy2"]`
* where "proxy2" is the furthest down-stream and "proxy1" and
* "proxy2" were trusted.
*
* @return {Array}
* @public
*/
defineGetter(req, 'ips', function ips() {
var trust = this.app.get('trust proxy fn');
var addrs = proxyaddr.all(this, trust);
// reverse the order (to farthest -> closest)
// and remove socket address
addrs.reverse().pop()
return addrs
});
/**
* Return subdomains as an array.
*
* Subdomains are the dot-separated parts of the host before the main domain of
* the app. By default, the domain of the app is assumed to be the last two
* parts of the host. This can be changed by setting "subdomain offset".
*
* For example, if the domain is "tobi.ferrets.example.com":
* If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
* If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
*
* @return {Array}
* @public
*/
defineGetter(req, 'subdomains', function subdomains() {
var hostname = this.hostname;
if (!hostname) return [];
var offset = this.app.get('subdomain offset');
var subdomains = !isIP(hostname)
? hostname.split('.').reverse()
: [hostname];
return subdomains.slice(offset);
});
/**
* Short-hand for `url.parse(req.url).pathname`.
*
* @return {String}
* @public
*/
defineGetter(req, 'path', function path() {
return parse(this).pathname;
});
/**
* Parse the "Host" header field to a host.
*
* When the "trust proxy" setting trusts the socket
* address, the "X-Forwarded-Host" header field will
* be trusted.
*
* @return {String}
* @public
*/
defineGetter(req, 'host', function host(){
var trust = this.app.get('trust proxy fn');
var val = this.get('X-Forwarded-Host');
if (!val || !trust(this.socket.remoteAddress, 0)) {
val = this.get('Host');
} else if (val.indexOf(',') !== -1) {
// Note: X-Forwarded-Host is normally only ever a
// single value, but this is to be safe.
val = val.substring(0, val.indexOf(',')).trimRight()
}
return val || undefined;
});
/**
* Parse the "Host" header field to a hostname.
*
* When the "trust proxy" setting trusts the socket
* address, the "X-Forwarded-Host" header field will
* be trusted.
*
* @return {String}
* @api public
*/
defineGetter(req, 'hostname', function hostname(){
var host = this.host;
if (!host) return;
// IPv6 literal support
var offset = host[0] === '['
? host.indexOf(']') + 1
: 0;
var index = host.indexOf(':', offset);
return index !== -1
? host.substring(0, index)
: host;
});
/**
* Check if the request is fresh, aka
* Last-Modified or the ETag
* still match.
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'fresh', function(){
var method = this.method;
var res = this.res
var status = res.statusCode
// GET or HEAD for weak freshness validation only
if ('GET' !== method && 'HEAD' !== method) return false;
// 2xx or 304 as per rfc2616 14.26
if ((status >= 200 && status < 300) || 304 === status) {
return fresh(this.headers, {
'etag': res.get('ETag'),
'last-modified': res.get('Last-Modified')
})
}
return false;
});
/**
* Check if the request is stale, aka
* "Last-Modified" and / or the "ETag" for the
* resource has changed.
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'stale', function stale(){
return !this.fresh;
});
/**
* Check if the request was an _XMLHttpRequest_.
*
* @return {Boolean}
* @public
*/
defineGetter(req, 'xhr', function xhr(){
var val = this.get('X-Requested-With') || '';
return val.toLowerCase() === 'xmlhttprequest';
});
/**
* Helper function for creating a getter on an object.
*
* @param {Object} obj
* @param {String} name
* @param {Function} getter
* @private
*/
function defineGetter(obj, name, getter) {
Object.defineProperty(obj, name, {
configurable: true,
enumerable: true,
get: getter
});
}
@@ -0,0 +1,168 @@
import * as util from "../core/util.js";
function getBelarusianPlural(count, one, few, many) {
const absCount = Math.abs(count);
const lastDigit = absCount % 10;
const lastTwoDigits = absCount % 100;
if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
return many;
}
if (lastDigit === 1) {
return one;
}
if (lastDigit >= 2 && lastDigit <= 4) {
return few;
}
return many;
}
const error = () => {
const Sizable = {
string: {
unit: {
one: "сімвал",
few: "сімвалы",
many: "сімвалаў",
},
verb: "мець",
},
array: {
unit: {
one: "элемент",
few: "элементы",
many: "элементаў",
},
verb: "мець",
},
set: {
unit: {
one: "элемент",
few: "элементы",
many: "элементаў",
},
verb: "мець",
},
map: {
unit: {
one: "элемент",
few: "элементы",
many: "элементаў",
},
verb: "мець",
},
file: {
unit: {
one: "байт",
few: "байты",
many: "байтаў",
},
verb: "мець",
},
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "увод",
email: "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 адрас",
mac: "MAC адрас",
cidrv4: "IPv4 дыяпазон",
cidrv6: "IPv6 дыяпазон",
base64: "радок у фармаце base64",
base64url: "радок у фармаце base64url",
json_string: "JSON радок",
e164: "нумар E.164",
credit_card: "нумар крэдытнай карты",
currency_code: "код валюты",
iban: "IBAN",
jwt: "JWT",
template_literal: "увод",
};
const TypeDictionary = {
nan: "NaN",
number: "лік",
array: "масіў",
};
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 sizing = getSizing(issue.origin);
if (sizing) {
const maxValue = Number(issue.maximum);
const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`;
}
return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
const minValue = Number(issue.minimum);
const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`;
}
return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`;
}
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 `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${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(),
};
}
@@ -0,0 +1 @@
{"version":3,"file":"dom-mini.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
@@ -0,0 +1,15 @@
/**
* Subtracts a specified number of milliseconds from a date.
* 从日期中减去指定的毫秒数。
*
* @param date - The date to subtract milliseconds from. (要从中减去毫秒的日期。)
* @param ms - The number of milliseconds to subtract. (要减去的毫秒数。)
* @returns A new date with the subtracted milliseconds. (减去毫秒后的新日期。)
* @example
* ```typescript
* // Subtract 500 milliseconds from 10/31/2021 5:45:50 PM
* const result = subMilliseconds(new Date(2021, 9, 31, 17, 45, 50, 500), 500);
* //=> Thu Oct 31 2021 17:45:49.000
* ```
*/
export default function subMilliseconds(date: Date, ms: number): Date;
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AACzD,YAAY,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAEH,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,OAAO,EACZ,KAAK,QAAQ,EAChB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACH,UAAU,EAEV,UAAU,IAAI,cAAc,EAC5B,KAAK,iBAAiB,GACzB,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,OAAO,GAAG,aAAa,GAAG,iBAAiB,CAAC;AAIxD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,QAAQ,CAIvE;AACD;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,EAAE,CAErE;AACD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAChC,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,EAAE,QAAQ,EAAE,QAAQ,KAAK,IAAI,EAC3D,OAAO,CAAC,EAAE,OAAO,EACjB,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAC7C,MAAM,CAOR;AACD;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC3B,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,KAAK,IAAI,EACzD,OAAO,CAAC,EAAE,OAAO,EACjB,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAC7C,MAAM,CAGR;AAED,OAAO,EACH,OAAO,IAAI,SAAS,EACpB,KAAK,SAAS,IAAI,kBAAkB,EACpC,SAAS,GACZ,MAAM,gBAAgB,CAAC;AAMxB,OAAO,KAAK,WAAW,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAAW,KAAK,IAAI,EAAE,MAAM,UAAU,CAAC;AAE9C,OAAO,EAAE,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,UAAU,CAAC;AAI9C;;;;;GAKG;AACH,wBAAgB,SAAS,CACrB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,OAAiC,GAC3C,IAAI,GAAG,IAAI,CAEb;AAED,OAAO,KAAK,QAAQ,MAAM,UAAU,CAAC"}
@@ -0,0 +1,15 @@
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
@@ -0,0 +1,148 @@
# Punycode.js [![punycode on npm](https://img.shields.io/npm/v/punycode)](https://www.npmjs.com/package/punycode) [![](https://data.jsdelivr.com/v1/package/npm/punycode/badge)](https://www.jsdelivr.com/package/npm/punycode)
Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891).
This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:
* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C)
* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)
* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)
* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)
* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))
This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated).
This project provides a CommonJS module that uses ES2015+ features and JavaScript module, which work in modern Node.js versions and browsers. For the old Punycode.js version that offers the same functionality in a UMD build with support for older pre-ES2015 runtimes, including Rhino, Ringo, and Narwhal, see [v1.4.1](https://github.com/mathiasbynens/punycode.js/releases/tag/v1.4.1).
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install punycode --save
```
In [Node.js](https://nodejs.org/):
> ⚠️ Note that userland modules don't hide core modules.
> For example, `require('punycode')` still imports the deprecated core module even if you executed `npm install punycode`.
> Use `require('punycode/')` to import userland modules rather than core modules.
```js
const punycode = require('punycode/');
```
## API
### `punycode.decode(string)`
Converts a Punycode string of ASCII symbols to a string of Unicode symbols.
```js
// decode domain name parts
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
```
### `punycode.encode(string)`
Converts a string of Unicode symbols to a Punycode string of ASCII symbols.
```js
// encode domain name parts
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
```
### `punycode.toUnicode(input)`
Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode.
```js
// decode domain names
punycode.toUnicode('xn--maana-pta.com');
// → 'mañana.com'
punycode.toUnicode('xn----dqo34k.com');
// → '☃-⌘.com'
// decode email addresses
punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');
// → 'джумла@джpумлатест.bрфa'
```
### `punycode.toASCII(input)`
Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII.
```js
// encode domain names
punycode.toASCII('mañana.com');
// → 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com');
// → 'xn----dqo34k.com'
// encode email addresses
punycode.toASCII('джумла@джpумлатест.bрфa');
// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'
```
### `punycode.ucs2`
#### `punycode.ucs2.decode(string)`
Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.
```js
punycode.ucs2.decode('abc');
// → [0x61, 0x62, 0x63]
// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:
punycode.ucs2.decode('\uD834\uDF06');
// → [0x1D306]
```
#### `punycode.ucs2.encode(codePoints)`
Creates a string based on an array of numeric code point values.
```js
punycode.ucs2.encode([0x61, 0x62, 0x63]);
// → 'abc'
punycode.ucs2.encode([0x1D306]);
// → '\uD834\uDF06'
```
### `punycode.version`
A string representing the current Punycode.js version number.
## For maintainers
### How to publish a new release
1. On the `main` branch, bump the version number in `package.json`:
```sh
npm version patch -m 'Release v%s'
```
Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/).
Note that this produces a Git commit + tag.
1. Push the release commit and tag:
```sh
git push && git push --tags
```
Our CI then automatically publishes the new release to npm, under both the [`punycode`](https://www.npmjs.com/package/punycode) and [`punycode.js`](https://www.npmjs.com/package/punycode.js) names.
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
Punycode.js is available under the [MIT](https://mths.be/mit) license.
@@ -0,0 +1,17 @@
import Promise = require('./index');
declare function register (module?: string, options?: register.Options): register.Register;
declare namespace register {
export interface Register {
Promise: typeof Promise;
implementation: string;
}
export interface Options {
Promise?: typeof Promise;
global?: boolean
}
}
export = register;
@@ -0,0 +1,18 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const ArrowDownUp = createLucideIcon("ArrowDownUp", [
["path", { d: "m3 16 4 4 4-4", key: "1co6wj" }],
["path", { d: "M7 20V4", key: "1yoxec" }],
["path", { d: "m21 8-4-4-4 4", key: "1c9v7m" }],
["path", { d: "M17 4v16", key: "7dpous" }]
]);
export { ArrowDownUp as default };
//# sourceMappingURL=arrow-down-up.js.map
@@ -0,0 +1,288 @@
/**
* 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: string);
}
/**
* 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: string);
}
/**
* Error to represent when an impl is already set.
*/
export class ImplAlreadySetError extends Error {
/**
* Creates a new instance.
*/
constructor();
}
/**
* A class representing a log entry.
*/
export class LogEntry {
/**
* Creates a new instance.
* @param {string} type The type of log entry.
* @param {any} [data] The data associated with the log entry.
*/
constructor(type: string, data?: any);
/**
* The type of log entry.
* @type {string}
*/
type: string;
/**
* The data associated with the log entry.
* @type {any}
*/
data: any;
/**
* The time at which the log entry was created.
* @type {number}
*/
timestamp: number;
}
/**
* A class representing a file system utility library.
* @implements {HfsImpl}
*/
export class Hfs implements HfsImpl {
/**
* Creates a new instance.
* @param {object} options The options for the instance.
* @param {HfsImpl} options.impl The implementation to use.
*/
constructor({ impl }: {
impl: HfsImpl;
});
/**
* 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: string): void;
/**
* 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: string): Array<LogEntry>;
/**
* Determines if the current implementation is the base implementation.
* @returns {boolean} True if the current implementation is the base implementation.
*/
isBaseImpl(): boolean;
/**
* Sets the implementation for this instance.
* @param {object} impl The implementation to use.
* @returns {void}
*/
setImpl(impl: object): void;
/**
* Resets the implementation for this instance back to its original.
* @returns {void}
*/
resetImpl(): void;
/**
* 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.
*/
text(filePath: string | URL): Promise<string | 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.
*/
json(filePath: string | URL): Promise<any | 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.
*/
arrayBuffer(filePath: string | URL): Promise<ArrayBuffer | undefined>;
/**
* 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.
*/
bytes(filePath: string | URL): Promise<Uint8Array | undefined>;
/**
* 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.
*/
write(filePath: string | URL, contents: string | ArrayBuffer | ArrayBufferView): Promise<void>;
/**
* 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.
*/
append(filePath: string | URL, contents: string | ArrayBuffer | ArrayBufferView): Promise<void>;
/**
* 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.
*/
isFile(filePath: string | URL): Promise<boolean>;
/**
* 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.
*/
isDirectory(dirPath: string | URL): Promise<boolean>;
/**
* 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.
*/
createDirectory(dirPath: string | URL): Promise<void>;
/**
* 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.
*/
delete(filePath: string | URL): Promise<boolean>;
/**
* 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.
*/
deleteAll(dirPath: string | URL): Promise<boolean>;
/**
* 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.
*/
list(dirPath: string | URL): AsyncIterable<HfsDirectoryEntry>;
/**
* 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.
*/
walk(dirPath: string | URL, { directoryFilter, entryFilter }?: {
directoryFilter?: (entry: HfsWalkEntry) => Promise<boolean> | boolean;
entryFilter?: (entry: HfsWalkEntry) => Promise<boolean> | boolean;
}): AsyncIterable<HfsWalkEntry>;
/**
* 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.
*/
size(filePath: string | URL): Promise<number>;
/**
* 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.
*/
lastModified(fileOrDirPath: string | URL): Promise<Date | undefined>;
/**
* 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.
*/
copy(source: string | URL, destination: string | URL): Promise<void>;
/**
* 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.
*/
copyAll(source: string | URL, destination: string | URL): Promise<void>;
/**
* 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.
*/
move(source: string | URL, destination: string | URL): Promise<void>;
/**
* 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.
*/
moveAll(source: string | URL, destination: string | URL): Promise<void>;
#private;
}
export type HfsImpl = import("@humanfs/types").HfsImpl;
export type HfsDirectoryEntry = import("@humanfs/types").HfsDirectoryEntry;
export type HfsWalkEntry = import("@humanfs/types").HfsWalkEntry;
@@ -0,0 +1,519 @@
flf2a$ 5 5 79 0 8
This font is (c) Michel Eftimakis 1995 -- Version 1.0 -- 3 may 1995
____________________________________________________________ /`____
| Michel Eftimakis | "Ascii-Artist" '\/ |
| Michel.Eftimakis@vlsi.com | Boo)- (00) ||
| Tel : (33) 92 96 27 19 | (_`'_) ||
|__ Fax : (33) 92 96 27 01 _________|____ FRANCE ___________ _!!_ ____||
|_____________________________________________________________________|
@
@
@
@
$$$$$$$$$@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
$$$$$$$$$@@
#########@
#########@
#########@
#########@
#########@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
_ _ _ __ __ _ @
/\ |_) / | \ |_ |_ / |_| @
/--\ |_) \_ |_/ |__ | \_? | | @
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@@
@
/| @
| @
@
$$$$$@@
_ @
) @
/_ @
@
$$$$$@@
_ @
_) @
_) @
@
$$$$$@@
. @
/| @
'-| @
@
$$$$$@@
_ @
|_ @
_) @
@
$$$$$@@
@
/ @
(_) @
@
$$$$$@@
__ @
/ @
/ @
@
$$$$$@@
_ @
(_) @
(_) @
@
$$$$$@@
@
@
@
@
@@
@
@
@
@
$$$$$$$$$@@
#########@
#########@
#########@
#########@
#########@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
######### ######### ___ ######### ######### @
##[`'`']# \`~'/ ##'\v/`## /\*/\ ##|`+'|## '\v/` ##\`~'/## [`'`'] @
###| |## (o o) ##(o 0)## /(o o)\ ##(o o)## (o 0) ##(o o)## | | @
###|__|## \ / \ ###(_)### (_) ###(_)### (_) ###\ / \# |__| @
######### " ######### ######### ####"####$$$$$$$$$@@
@
'\v/` @
(o 0) @
(_) @
$$$$$$$$$@@
@
\`~'/ @
(o o) @
\ / \ @
$$$$"$$$$@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
|`+'| @
(o o) @
(_) @
$$$$$$$$$@@
@
|:+:| @
(o:o) @
(:) @
$$$$$$$$$@@
@
@
@
@
@@
@
':v:` @
(o:0) @
(:) @
$$$$$$$$$@@
_ @
(:) @
|:| @
|:| @
$$$$$$$$$@@
_ @
(_) @
| | @
|_| @
$$$$$$$$$@@
___ @
/\*/\ @
/(o o)\ @
(_) @
$$$$$$$$$@@
@
[`'`'] @
| | @
|__| @
$$$$$$$$$@@
@
@
@
@
@@
@
[`'`'] @
|::| @
|::| @
$$$$$$$$$@@
@
@
@
@
@@
@
\`.'/ @
(o:o) @
\:/:\ @
$$$$"$$$$@@
___ @
/\:/\ @
/(o:o)\ @
(:) @
$$$$$$$$$@@
@
@
@
@
@@
######### ######### ######### ######### @
######### ######### ######### ######### @
######### ######### ######### ######### @
######### ######### ######### ######### @
######### ######### ######### #########$$$$$$$$$@@
_ ######### _ ######### _ ######### _ #########@
(_) ###(_)### (_) ###(_)### (_) ###(_)### (_) ###(_)###@
| | ###| |### | | ###| |### | | ###| |### | | ###| |###@
|_| ###|_|### |_| ###|_|### |_| ###|_|### |_| ###|_|###@
$$$$$$$$$######### ######### ######### #########@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
######### ######### ######### #########@
[`'`'] ##\`.'/## ':v:` ##/\:/\## |:+:| ##':v:`## \`.'/ ##[`'`']#@
|::| ##(o:o)## (o:0) #/(o:o)\# (o:o) ##(o:0)## (o:o) ###|::|##@
|::| ###\:/:\# (:) ###(:)### (:) ###(:)### \:/:\ ###|::|##@
$$$$$$$$$####"#### ######### ######### " #########@@
#########@
##'\v/`##@
##(o 0)##@
###(_)###@
#########@@
#########@
##\`~'/##@
##(o o)##@
###\ / \#@
####"####@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
#########@
##|`+'|##@
##(o o)##@
###(_)###@
#########@@
#########@
##|:+:|##@
##(o:o)##@
###(:)###@
#########@@
@
@
@
@
@@
#########@
##':v:`##@
##(o:0)##@
###(:)###@
#########@@
#########@
###(:)###@
###|:|###@
###|:|###@
#########@@
#########@
###(_)###@
###| |###@
###|_|###@
#########@@
#########@
##/\*/\##@
#/(o o)\#@
###(_)###@
#########@@
#########@
##[`'`']#@
###| |##@
###|__|##@
#########@@
@
@
@
@
@@
#########@
##[`'`']#@
###|::|##@
###|::|##@
#########@@
@
@
@
@
@@
#########@
##\`.'/##@
##(o:o)##@
###\:/:\#@
####"####@@
#########@
##/\:/\##@
#/(o:o)\#@
###(:)###@
#########@@
@
@
@
@
@@
######### ######### ######### #########@
######### ######### ######### #########@
######### ######### ######### #########@
######### ######### ######### #########@
$$$$$$$$$######### ######### ######### #########@@
######### _ ######### _ ######### _ ######### _ @
###(:)### (:) ###(:)### (:) ###(:)### (:) ###(:)### (:) @
###|:|### |:| ###|:|### |:| ###|:|### |:| ###|:|### |:| @
###|:|### |:| ###|:|### |:| ###|:|### |:| ###|:|### |:| @
######### ######### ######### #########$$$$$$$$$@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@
@
@
@
@@
@@ -0,0 +1,160 @@
import MatchL33t from '../dictionary/variants/matching/l33t.mjs';
import MatchReverse from '../dictionary/variants/matching/reverse.mjs';
import MatchDictionary from '../dictionary/matching.mjs';
import { MatcherBaseClass } from '../../types.mjs';
/*
*-------------------------------------------------------------------------------
* word sequences (oneTwoThree, fourFiveSix) ------------------------------
*-------------------------------------------------------------------------------
*/
class MatchWordSequence extends MatcherBaseClass {
constructor(options) {
super(options);
this.dictionary = new MatchDictionary(this.options, true);
this.dictionaryL33t = new MatchL33t(this.options, true);
this.dictionaryReverse = new MatchReverse(this.options, true);
}
match(matchOptions) {
const {
password
} = matchOptions;
// Get all dictionary matches first
const dictionaryMatches = this.dictionary.match(matchOptions);
const dictionaryL33tMatches = this.dictionaryL33t.match(matchOptions);
const dictionaryReverseMatches = this.dictionaryReverse.match(matchOptions);
const filteredDictionaryMatches = this.filterDictionaryMatches([...dictionaryMatches, ...dictionaryL33tMatches, ...dictionaryReverseMatches]);
// Convert dictionary matches to our internal format
const wordMatches = this.convertToWordMatches(filteredDictionaryMatches);
// Find sequences of consecutive words
return this.findWordSequences(wordMatches, password);
}
filterDictionaryMatches(matches) {
// sort by start index, then by end index
return [...matches].sort((a, b) => {
if (a.i !== b.i) return a.i - b.i;
if (a.j !== b.j) return a.j - b.j;
// prefer forward over reversed
if (a.reversed !== b.reversed) return a.reversed ? 1 : -1;
// prefer non-l33t
if (a.l33t !== b.l33t) return a.l33t ? 1 : -1;
// prefer better rank
return a.rank - b.rank;
})
// Keep only non-overlapping matches, favoring earlier ones
.reduce((acc, match) => {
const last = acc[acc.length - 1];
if (!last || match.i > last.j) {
acc.push(match);
}
return acc;
}, []);
}
convertToWordMatches(dictionaryMatches) {
return dictionaryMatches.map(match => ({
word: match.matchedWord,
i: match.i,
j: match.j,
rank: match.rank,
dictionaryName: match.dictionaryName
}));
}
findWordSequences(wordMatches, password) {
const sequences = [];
if (wordMatches.length === 0) {
return sequences;
}
// Sort matches by start position
const sortedMatches = [...wordMatches].sort((a, b) => a.i - b.i);
// Find all possible sequences
for (let startIdx = 0; startIdx < sortedMatches.length; startIdx += 1) {
const sequencesFromStart = this.findSequencesFromStart(sortedMatches, startIdx, password);
sequences.push(...sequencesFromStart);
}
return sequences;
}
// eslint-disable-next-line max-statements
findSequencesFromStart(sortedMatches, startIdx, password) {
const sequences = [];
const startMatch = sortedMatches[startIdx];
// Start with single word sequence
let currentSequence = [startMatch];
let currentEnd = startMatch.j;
// Try to extend the sequence
for (let nextIdx = startIdx + 1; nextIdx < sortedMatches.length; nextIdx += 1) {
const nextMatch = sortedMatches[nextIdx];
// Only extend if the next word can form a valid sequence
if (this.isValidWordSequence(currentSequence, nextMatch, password)) {
currentSequence.push(nextMatch);
currentEnd = nextMatch.j;
} else if (nextMatch.i > currentEnd) {
// Gap found, save current sequence and start new one
if (currentSequence.length > 1) {
sequences.push(this.createWordSequenceMatch(currentSequence, password));
}
currentSequence = [nextMatch];
currentEnd = nextMatch.j;
}
// If nextMatch.i <= currentEnd, it overlaps, so we skip it
}
// Don't forget the last sequence
if (currentSequence.length > 1) {
sequences.push(this.createWordSequenceMatch(currentSequence, password));
}
return sequences;
}
isValidWordSequence(currentSequence, nextMatch, password) {
// Get the text between the last word and the next word
const lastWord = currentSequence[currentSequence.length - 1];
const textBetween = password.slice(lastWord.j + 1, nextMatch.i);
// Check for common word separators
const separators = ['', ' ', '-', '_', '.', ''];
// For simple concatenation (no separator)
const isSimpleConcat = textBetween === '';
// For snake_case or kebab-case, check for separators
const hasValidSeparator = separators.some(sep => textBetween === sep);
// For camelCase, we need to check if the next word starts with uppercase
// and there's no separator (or just a single character that could be uppercase)
const isCamelCase = textBetween.length === 1 && textBetween === textBetween.toUpperCase() && textBetween !== textBetween.toLowerCase();
return hasValidSeparator || isSimpleConcat || isCamelCase;
}
createWordSequenceMatch(sequence, password) {
const firstMatch = sequence[0];
const lastMatch = sequence[sequence.length - 1];
const words = sequence.map(match => match.word);
// Determine if sequence is ascending (by rank)
const ranks = sequence.map(match => match.rank);
const ascending = ranks.every((rank, i) => i === 0 || rank >= ranks[i - 1]);
// Use the most common dictionary name, or the first one
const dictionaryNames = sequence.map(match => match.dictionaryName);
const dictionaryName = this.getMostCommon(dictionaryNames) || firstMatch.dictionaryName;
return {
pattern: 'wordSequence',
i: firstMatch.i,
j: lastMatch.j,
token: password.slice(firstMatch.i, lastMatch.j + 1),
words,
wordCount: words.length,
dictionaryName,
ascending
};
}
getMostCommon(array) {
if (array.length === 0) return null;
const counts = new Map();
let maxCount = 0;
let mostCommon = null;
array.forEach(item => {
const count = (counts.get(item) || 0) + 1;
counts.set(item, count);
if (count > maxCount) {
maxCount = count;
mostCommon = item;
}
});
return mostCommon;
}
}
export { MatchWordSequence as default };
//# sourceMappingURL=matching.mjs.map
@@ -0,0 +1,10 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/adapter/vercel/handler.ts
/**
* @deprecated `hono/vercel` will be removed in v5. Install `@hono/vercel` and import from there instead.
*/
const handle = (app) => (req) => {
return app.fetch(req);
};
//#endregion
exports.handle = handle;
@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2017_full: LibDefinition;
@@ -0,0 +1 @@
module.exports={A:{A:{"1":"B","2":"_IB","132":"A","260":"_vC"},B:{"1":"_J"},C:{"1":"_H _fO _iI _WC _L","2":"_g","1025":"hC _rD"},D:{"1":"_0L","132":"_VF"},E:{"2":"_e","513":"_dB","644":"_1Q"},F:{"1":"_xL","2":"_0D"},G:{"513":"_8C","644":"_1"},H:{"2":"1D"},I:{"1":"_X","132":"_W"},J:{"1":"A","132":"D"},K:{"1":"_XD","2":"_gB"},L:{"1":"I"},M:{"1":"YC"},N:{"1":"B","132":"A"},O:{"1":"bC"},P:{"1":"_F"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"_C"}},B:1,C:"Cross-Origin Resource Sharing",D:true};
@@ -0,0 +1,27 @@
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
@@ -0,0 +1,20 @@
#ifndef FS_EVENTS_H
#define FS_EVENTS_H
#include <CoreServices/CoreServices.h>
#include "../Backend.hh"
class FSEventsBackend : public Backend {
public:
void start() override;
~FSEventsBackend();
void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override;
void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override;
void subscribe(WatcherRef watcher) override;
void unsubscribe(WatcherRef watcher) override;
private:
void startStream(WatcherRef watcher, FSEventStreamEventId id);
CFRunLoopRef mRunLoop;
};
#endif
@@ -0,0 +1,35 @@
/**
* JSON Web Token (JWT) Decryption (JWT is in JWE format)
*
* @module
*/
import type * as types from '../types.d.ts';
/** Combination of JWE Decryption options and JWT Claims Set verification options. */
export interface JWTDecryptOptions extends types.DecryptOptions, types.JWTClaimVerificationOptions {
}
/**
* Interface for JWT Decryption dynamic key resolution. No token components have been verified at
* the time of this function call.
*/
export interface JWTDecryptGetKey extends types.GetKeyFunction<types.CompactJWEHeaderParameters, types.FlattenedJWE> {
}
/**
* Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT
* Claims Set.
*
* This function is exported (as a named export) from the main `'jose'` module entry point as well
* as from its subpath export `'jose/jwt/decrypt'`.
*
* @param jwt JSON Web Token value (encoded as JWE).
* @param key Private Key or Secret to decrypt and verify the JWT with. See
* {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
* @param options JWT Decryption and JWT Claims Set validation options.
*/
export declare function jwtDecrypt<PayloadType = types.JWTPayload>(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTDecryptOptions): Promise<types.JWTDecryptResult<PayloadType>>;
/**
* @param jwt JSON Web Token value (encoded as JWE).
* @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See
* {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
* @param options JWT Decryption and JWT Claims Set validation options.
*/
export declare function jwtDecrypt<PayloadType = types.JWTPayload>(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise<types.JWTDecryptResult<PayloadType> & types.ResolvedKey>;
@@ -0,0 +1,373 @@
flf2a$ 1 1 11 -1 12 0
decimal.flf by Karlton Wirsing based on
binary.flf (C) 1994 by Victor Parada (vparada@inf.utfsm.cl) 94/12/05
figlet 2.1 font, includes ISO Latin-1, excludes "-D" option chars.
Spaces are not shown as binary. If this is required, change "$@" below
to " @". Change to "@" to remove the hardspace between words.
Note that figlet always removes spaces when it moves words to a new line.
Try option "-m 0" to remove the space between letters (octets).
$@
33 @
34 @
35 @
36 @
37 @
38 @
39 @
40 @
41 @
42 @
43 @
44 @
45 @
46 @
47 @
48 @
49 @
50 @
51 @
52 @
53 @
54 @
55 @
56 @
57 @
58 @
59 @
60 @
61 @
62 @
63 @
64 @
65 @
66 @
67 @
68 @
69 @
70 @
71 @
72 @
73 @
74 @
75 @
76 @
77 @
78 @
79 @
80 @
81 @
82 @
83 @
84 @
85 @
86 @
87 @
88 @
89 @
90 @
91 @
92 @
93 @
94 @
95 @
96 @
97 @
98 @
99 @
100 @
101 @
102 @
103 @
104 @
105 @
106 @
107 @
108 @
109 @
110 @
111 @
112 @
113 @
114 @
115 @
116 @
117 @
118 @
119 @
120 @
121 @
122 @
123 @
124 @
125 @
126 @
@
@
@
@
@
@
@
127
127 @
128
128 @
129
129 @
130
130 @
131
131 @
132
132 @
133
133 @
134
134 @
135
135 @
136
136 @
137
137 @
138
138 @
139
139 @
140
140 @
141
141 @
142
142 @
143
143 @
144
144 @
145
145 @
146
146 @
147
147 @
148
148 @
149
149 @
150
150 @
151
151 @
152
152 @
153
153 @
154
154 @
155
155 @
156
156 @
157
157 @
158
158 @
159
159 @
160
160 @
161
161 @
162
162 @
163
163 @
164
164 @
165
165 @
166
166 @
167
167 @
168
168 @
169
169 @
170
170 @
171
171 @
172
172 @
173
173 @
174
174 @
175
175 @
176
176 @
177
177 @
178
178 @
179
179 @
180
180 @
181
181 @
182
182 @
183
183 @
184
184 @
185
185 @
186
186 @
187
187 @
188
188 @
189
189 @
190
190 @
191
191 @
192
192 @
193
193 @
194
194 @
195
195 @
196
196 @
197
197 @
198
198 @
199
199 @
200
200 @
201
201 @
202
202 @
203
203 @
204
204 @
205
205 @
206
206 @
207
207 @
208
208 @
209
209 @
210
210 @
211
211 @
212
212 @
213
213 @
214
214 @
215
215 @
216
216 @
217
217 @
218
218 @
219
219 @
220
220 @
221
221 @
222
222 @
223
223 @
224
224 @
225
225 @
226
226 @
227
227 @
228
228 @
229
229 @
230
230 @
231
231 @
232
232 @
233
233 @
234
234 @
235
235 @
236
236 @
237
237 @
238
238 @
239
239 @
240
240 @
241
241 @
242
242 @
243
243 @
244
244 @
245
245 @
246
246 @
247
247 @
248
248 @
249
249 @
250
250 @
251
251 @
252
252 @
253
253 @
254
254 @
255
255 @
@@ -0,0 +1,8 @@
export type CrossEnvOptions = {
shell?: boolean;
};
export type ProcessResult = {
exitCode: number | null;
signal?: string | null;
};
export declare function crossEnv(args: string[], options?: CrossEnvOptions): ProcessResult | null;
@@ -0,0 +1,161 @@
# @vitejs/plugin-react [![npm](https://img.shields.io/npm/v/@vitejs/plugin-react.svg)](https://npmjs.com/package/@vitejs/plugin-react)
The default Vite plugin for React projects.
- enable [Fast Refresh](https://www.npmjs.com/package/react-refresh) in development (requires react >= 16.9)
- use the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html)
- small installation size
```js
// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})
```
## Options
### include
Includes `.js`, `.jsx`, `.ts` & `.tsx` by default. This option can be used to add fast refresh to `.mdx` files:
```js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import mdx from '@mdx-js/rollup'
export default defineConfig({
plugins: [
{ enforce: 'pre', ...mdx() },
react({ include: /\.(mdx|js|jsx|ts|tsx)$/ }),
],
})
```
### exclude
The default value is `/node_modules/`. You may use it to exclude JSX/TSX files that runs in a worker or are not React files.
Except if explicitly desired, you should keep `node_modules` in the exclude list:
```js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [
react({ exclude: [/\/pdf\//, /\.solid\.tsx$/, /\/node_modules\//] }),
],
})
```
### jsxImportSource
Control where the JSX factory is imported from. By default, this is inferred from `jsxImportSource` from corresponding a tsconfig file for a transformed file.
```js
react({ jsxImportSource: '@emotion/react' })
```
### jsxRuntime
By default, the plugin uses the [automatic JSX runtime](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). However, if you encounter any issues, you may opt out using the `jsxRuntime` option.
```js
react({ jsxRuntime: 'classic' })
```
### reactRefreshHost
The `reactRefreshHost` option is only necessary in a module federation context. It enables HMR to work between a remote & host application. In your remote Vite config, you would add your host origin:
```js
react({ reactRefreshHost: 'http://localhost:3000' })
```
Under the hood, this simply updates the React Fash Refresh runtime URL from `/@react-refresh` to `http://localhost:3000/@react-refresh` to ensure there is only one Refresh runtime across the whole application. Note that if you define `base` option in the host application, you need to include it in the option, like: `http://localhost:3000/{base}`.
## React Compiler
[React Compiler](https://react.dev/learn/react-compiler) support is available via the exported `reactCompilerPreset` helper, which requires [`@rolldown/plugin-babel`](https://npmx.dev/package/@rolldown/plugin-babel) and [`babel-plugin-react-compiler`](https://npmx.dev/package/babel-plugin-react-compiler) as peer dependencies:
```sh
npm install -D @rolldown/plugin-babel babel-plugin-react-compiler
```
```js
// vite.config.js
import { defineConfig } from 'vite'
import react, { reactCompilerPreset } from '@vitejs/plugin-react'
import babel from '@rolldown/plugin-babel'
export default defineConfig({
plugins: [react(), babel({ presets: [reactCompilerPreset()] })],
})
```
The `reactCompilerPreset` accepts an optional options object with the following properties:
- `compilationMode` — Set to `'annotation'` to only compile components annotated with `"use memo"`.
- `target` — Set to `'17'` or `'18'` to target older React versions (uses `react-compiler-runtime` instead of `react/compiler-runtime`).
```js
babel({
presets: [reactCompilerPreset({ compilationMode: 'annotation' })],
})
```
> [!TIP]
>
> `reactCompilerPreset` is only a convenient helper with a preconfigured filter. You can configure override the filters to fit your project structure or code. For example, if you know a large portion of your files are never React/hook-related or won't benefit from the React Compiler, you can aggressively exclude them via `rolldown.filter`:
>
> ```js
> const myPreset = reactCompilerPreset()
> myPreset.rolldown.filter.id.exclude = ['src/legacy/**', 'src/utils/**']
>
> babel({
> presets: [myPreset],
> })
> ```
## `@vitejs/plugin-react/preamble`
The package provides `@vitejs/plugin-react/preamble` to initialize HMR runtime from client entrypoint for SSR applications which don't use [`transformIndexHtml` API](https://vite.dev/guide/api-javascript.html#vitedevserver). For example:
```js
// [entry.client.js]
import '@vitejs/plugin-react/preamble'
```
Alternatively, you can manually call `transformIndexHtml` during SSR, which sets up equivalent initialization code. Here's an example for an Express server:
```js
app.get('/', async (req, res, next) => {
try {
let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8')
// Transform HTML using Vite plugins.
html = await viteServer.transformIndexHtml(req.url, html)
res.send(html)
} catch (e) {
return next(e)
}
})
```
Otherwise, you'll get the following error:
```
Uncaught Error: @vitejs/plugin-react can't detect preamble. Something is wrong.
```
## Consistent components exports
For React refresh to work correctly, your file should only export React components. You can find a good explanation in the [Gatsby docs](https://www.gatsbyjs.com/docs/reference/local-development/fast-refresh/#how-it-works).
If an incompatible change in exports is found, the module will be invalidated and HMR will propagate. To make it easier to export simple constants alongside your component, the module is only invalidated when their value changes.
You can catch mistakes and get more detailed warnings with this [ESLint rule](https://github.com/ArnaudBarre/eslint-plugin-react-refresh), or the equivalent [Oxlint rule](https://oxc.rs/docs/guide/usage/linter/rules/react/only-export-components.html).
@@ -0,0 +1,15 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Framer = createLucideIcon("Framer", [
["path", { d: "M5 16V9h14V2H5l14 14h-7m-7 0 7 7v-7m-7 0h7", key: "1a2nng" }]
]);
export { Framer as default };
//# sourceMappingURL=framer.js.map
@@ -0,0 +1,7 @@
import { AssetCrossOriginConfig, RouterManagedTag } from '@tanstack/router-core';
/**
* Build the list of head/link/meta/script tags to render for active matches.
* Used internally by `HeadContent`.
*/
export declare const useTags: (assetCrossOrigin?: AssetCrossOriginConfig) => RouterManagedTag[];
export declare function uniqBy<T>(arr: Array<T>, fn: (item: T) => string): T[];
@@ -0,0 +1 @@
export { validate, validateAsync, parse, safeParse, parseAsync, safeParseAsync, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync, } from "../core/index.js";
@@ -0,0 +1,148 @@
export const xmlReplacer: RegExp = /["$&'<>\u0080-\uFFFF]/g;
const xmlCodeMap = new Map([
[34, "&quot;"],
[38, "&amp;"],
[39, "&apos;"],
[60, "&lt;"],
[62, "&gt;"],
]);
// For compatibility with node < 4, we wrap `codePointAt`
export const getCodePoint: (c: string, index: number) => number =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
String.prototype.codePointAt == null
? (c: string, index: number): number =>
(c.charCodeAt(index) & 0xfc_00) === 0xd8_00
? (c.charCodeAt(index) - 0xd8_00) * 0x4_00 +
c.charCodeAt(index + 1) -
0xdc_00 +
0x1_00_00
: c.charCodeAt(index)
: // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
(input: string, index: number): number => input.codePointAt(index)!;
/**
* Encodes all non-ASCII characters, as well as characters not valid in XML
* documents using XML entities.
*
* If a character has no equivalent entity, a
* numeric hexadecimal reference (eg. `&#xfc;`) will be used.
*/
export function encodeXML(input: string): string {
let returnValue = "";
let lastIndex = 0;
let match;
while ((match = xmlReplacer.exec(input)) !== null) {
const { index } = match;
const char = input.charCodeAt(index);
const next = xmlCodeMap.get(char);
if (next === undefined) {
returnValue += `${input.substring(lastIndex, index)}&#x${getCodePoint(
input,
index,
).toString(16)};`;
// Increase by 1 if we have a surrogate pair
lastIndex = xmlReplacer.lastIndex += Number(
(char & 0xfc_00) === 0xd8_00,
);
} else {
returnValue += input.substring(lastIndex, index) + next;
lastIndex = index + 1;
}
}
return returnValue + input.substr(lastIndex);
}
/**
* Encodes all non-ASCII characters, as well as characters not valid in XML
* documents using numeric hexadecimal reference (eg. `&#xfc;`).
*
* Have a look at `escapeUTF8` if you want a more concise output at the expense
* of reduced transportability.
*
* @param data String to escape.
*/
export const escape: typeof encodeXML = encodeXML;
/**
* Creates a function that escapes all characters matched by the given regular
* expression using the given map of characters to escape to their entities.
*
* @param regex Regular expression to match characters to escape.
* @param map Map of characters to escape to their entities.
*
* @returns Function that escapes all characters matched by the given regular
* expression using the given map of characters to escape to their entities.
*/
function getEscaper(
regex: RegExp,
map: Map<number, string>,
): (data: string) => string {
return function escape(data: string): string {
let match;
let lastIndex = 0;
let result = "";
while ((match = regex.exec(data))) {
if (lastIndex !== match.index) {
result += data.substring(lastIndex, match.index);
}
// We know that this character will be in the map.
result += map.get(match[0].charCodeAt(0))!;
// Every match will be of length 1
lastIndex = match.index + 1;
}
return result + data.substring(lastIndex);
};
}
/**
* Encodes all characters not valid in XML documents using XML entities.
*
* Note that the output will be character-set dependent.
*
* @param data String to escape.
*/
export const escapeUTF8: (data: string) => string = /* #__PURE__ */ getEscaper(
/["&'<>]/g,
xmlCodeMap,
);
/**
* Encodes all characters that have to be escaped in HTML attributes,
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
*
* @param data String to escape.
*/
export const escapeAttribute: (data: string) => string =
/* #__PURE__ */ getEscaper(
/["&\u00A0]/g,
new Map([
[34, "&quot;"],
[38, "&amp;"],
[160, "&nbsp;"],
]),
);
/**
* Encodes all characters that have to be escaped in HTML text,
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
*
* @param data String to escape.
*/
export const escapeText: (data: string) => string = /* #__PURE__ */ getEscaper(
/[&<>\u00A0]/g,
new Map([
[38, "&amp;"],
[60, "&lt;"],
[62, "&gt;"],
[160, "&nbsp;"],
]),
);
@@ -0,0 +1,275 @@
# ObjectSchema Package
## Overview
A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than `Object.assign()`. This is used in the [`@eslint/config-array`](https://npmjs.com/package/@eslint/config-array) package but can also be used on its own.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/object-schema
# or
yarn add @eslint/object-schema
# or
pnpm install @eslint/object-schema
# or
bun add @eslint/object-schema
```
For Deno:
```shell
deno add @eslint/object-schema
```
## Usage
Import the `ObjectSchema` constructor:
```js
// using ESM
import { ObjectSchema } from "@eslint/object-schema";
// using CommonJS
const { ObjectSchema } = require("@eslint/object-schema");
const schema = new ObjectSchema({
// define a definition for the "downloads" key
downloads: {
required: true,
merge(value1 = 0, value2) {
return value1 + value2;
},
validate(value) {
if (typeof value !== "number") {
throw new Error("Expected downloads to be a number.");
}
},
},
// define a strategy for the "versions" key
versions: {
required: true,
merge(value1 = [], value2) {
return value1.concat(value2);
},
validate(value) {
if (!Array.isArray(value)) {
throw new Error("Expected versions to be an array.");
}
},
},
});
const record1 = {
downloads: 25,
versions: ["v1.0.0", "v1.1.0", "v1.2.0"],
};
const record2 = {
downloads: 125,
versions: ["v2.0.0", "v2.1.0", "v3.0.0"],
};
// make sure the records are valid
schema.validate(record1);
schema.validate(record2);
// merge together (schema.merge() accepts any number of objects)
const result = schema.merge(record1, record2);
// result looks like this:
// {
// downloads: 150,
// versions: ["v1.0.0", "v1.1.0", "v1.2.0", "v2.0.0", "v2.1.0", "v3.0.0"],
// }
```
## Tips and Tricks
### Named merge strategies
Instead of specifying a `merge()` method, you can specify one of the following strings to use a default merge strategy:
- `"assign"` - use `Object.assign()` to merge the two values into one object.
- `"overwrite"` - the second value always replaces the first.
- `"replace"` - the second value replaces the first if the second is not `undefined`.
For example:
```js
const schema = new ObjectSchema({
name: {
merge: "replace",
validate() {},
},
});
```
### Named validation strategies
Instead of specifying a `validate()` method, you can specify one of the following strings to use a default validation strategy:
- `"array"` - value must be an array.
- `"boolean"` - value must be a boolean.
- `"number"` - value must be a number.
- `"object"` - value must be a non-null object, including arrays and non-plain objects.
- `"object?"` - value must be an object or null, including arrays and non-plain objects.
- `"string"` - value must be a string.
- `"string!"` - value must be a non-empty string.
For example:
```js
const schema = new ObjectSchema({
name: {
merge: "replace",
validate: "string",
},
});
```
### Built-in strategy classes
The package also exports the built-in merge and validation strategies as two classes with static methods:
- `MergeStrategy` - built-in merge functions (`assign`, `overwrite`, `replace`).
- `ValidationStrategy` - built-in validation functions (`array`, `boolean`, `number`, `object`, `object?`, `string`, `string!`).
These are the same strategies used when you specify a strategy by name (for example, `merge: "replace"`). You can reference the functions directly if you prefer passing a function instead of a string:
```js
import {
ObjectSchema,
MergeStrategy,
ValidationStrategy,
} from "@eslint/object-schema";
const schema = new ObjectSchema({
name: {
required: true,
merge: MergeStrategy.replace,
validate: ValidationStrategy["string!"],
},
options: {
required: false,
merge: MergeStrategy.assign,
validate: ValidationStrategy["object?"],
},
});
```
Note: Because `object?` and `string!` aren't valid identifiers, you must access them using bracket notation (for example, `ValidationStrategy["object?"]`).
### Subschemas
If you are defining a key that is, itself, an object, you can simplify the process by using a subschema. Instead of defining `merge()` and `validate()`, set a `schema` property that contains a schema definition, like this:
```js
const schema = new ObjectSchema({
name: {
schema: {
first: {
merge: "replace",
validate: "string",
},
last: {
merge: "replace",
validate: "string",
},
},
},
});
schema.validate({
name: {
first: "n",
last: "z",
},
});
```
### Remove Keys During Merge
If the merge strategy for a key returns `undefined`, then the key will not appear in the final object. For example:
```js
const schema = new ObjectSchema({
date: {
merge() {
return undefined;
},
validate(value) {
if (isNaN(Date.parse(value))) {
throw new Error("Invalid date.");
}
},
},
});
const object1 = { date: "5/5/2005" };
const object2 = { date: "6/6/2006" };
const result = schema.merge(object1, object2);
console.log("date" in result); // false
```
### Requiring Another Key Be Present
If you'd like the presence of one key to require the presence of another key, you can use the `requires` property to specify an array of other properties that any key requires. For example:
```js
const schema = new ObjectSchema({
date: {
merge() {
return undefined;
},
validate(value) {
if (isNaN(Date.parse(value))) {
throw new Error("Invalid date.");
}
},
},
time: {
requires: ["date"],
merge(first, second) {
return second;
},
validate(value) {
// ...
},
},
});
// throws error: Key "time" requires keys "date".
schema.validate({
time: "13:45",
});
```
In this example, even though `date` is an optional key, it is required to be present whenever `time` is present.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="#"><img src="https://images.opencollective.com/aeriusventilations-org/avatar.png" alt="aeriusventilation's Org" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="TestMu AI Open Source Office (Formerly LambdaTest)" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->
@@ -0,0 +1,296 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.allExpandedTypes = exports.VISITOR_KEYS = exports.NODE_UNION_SHAPES__PRIVATE = exports.NODE_PARENT_VALIDATIONS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.ALIAS_KEYS = void 0;
exports.arrayOf = arrayOf;
exports.arrayOfType = arrayOfType;
exports.assertEach = assertEach;
exports.assertNodeOrValueType = assertNodeOrValueType;
exports.assertNodeType = assertNodeType;
exports.assertOneOf = assertOneOf;
exports.assertOptionalChainStart = assertOptionalChainStart;
exports.assertShape = assertShape;
exports.assertValueType = assertValueType;
exports.chain = chain;
exports.default = defineType;
exports.defineAliasedType = defineAliasedType;
exports.validate = validate;
exports.validateArrayOfType = validateArrayOfType;
exports.validateOptional = validateOptional;
exports.validateOptionalType = validateOptionalType;
exports.validateType = validateType;
var _is = require("../validators/is.js");
var _validate = require("../validators/validate.js");
const VISITOR_KEYS = exports.VISITOR_KEYS = {};
const ALIAS_KEYS = exports.ALIAS_KEYS = {};
const FLIPPED_ALIAS_KEYS = exports.FLIPPED_ALIAS_KEYS = {};
const NODE_FIELDS = exports.NODE_FIELDS = {};
const BUILDER_KEYS = exports.BUILDER_KEYS = {};
const DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {};
const NODE_PARENT_VALIDATIONS = exports.NODE_PARENT_VALIDATIONS = {};
const NODE_UNION_SHAPES__PRIVATE = exports.NODE_UNION_SHAPES__PRIVATE = {};
function getType(val) {
if (Array.isArray(val)) {
return "array";
} else if (val === null) {
return "null";
} else {
return typeof val;
}
}
function validate(validate) {
return {
validate
};
}
function validateType(...typeNames) {
return validate(assertNodeType(...typeNames));
}
function validateOptional(validate) {
return {
validate,
optional: true
};
}
function validateOptionalType(...typeNames) {
return {
validate: assertNodeType(...typeNames),
optional: true
};
}
function arrayOf(elementType) {
return chain(assertValueType("array"), assertEach(elementType));
}
function arrayOfType(...typeNames) {
return arrayOf(assertNodeType(...typeNames));
}
function validateArrayOfType(...typeNames) {
return validate(arrayOfType(...typeNames));
}
function assertEach(callback) {
const childValidator = process.env.BABEL_TYPES_8_BREAKING ? _validate.validateChild : () => {};
function validator(node, key, val) {
if (!Array.isArray(val)) return;
let i = 0;
const subKey = {
toString() {
return `${key}[${i}]`;
}
};
for (; i < val.length; i++) {
const v = val[i];
callback(node, subKey, v);
childValidator(node, subKey, v);
}
}
validator.each = callback;
return validator;
}
function assertOneOf(...values) {
function validate(node, key, val) {
if (!values.includes(val)) {
throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`);
}
}
validate.oneOf = values;
return validate;
}
const allExpandedTypes = exports.allExpandedTypes = [];
function assertNodeType(...types) {
const expandedTypes = new Set();
allExpandedTypes.push({
types,
set: expandedTypes
});
function validate(node, key, val) {
const valType = val == null ? void 0 : val.type;
if (valType != null) {
if (expandedTypes.has(valType)) {
(0, _validate.validateChild)(node, key, val);
return;
}
if (valType === "Placeholder") {
for (const type of types) {
if ((0, _is.default)(type, val)) {
(0, _validate.validateChild)(node, key, val);
return;
}
}
}
}
throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(valType)}`);
}
validate.oneOfNodeTypes = types;
return validate;
}
function assertNodeOrValueType(...types) {
function validate(node, key, val) {
const primitiveType = getType(val);
for (const type of types) {
if (primitiveType === type || (0, _is.default)(type, val)) {
(0, _validate.validateChild)(node, key, val);
return;
}
}
throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`);
}
validate.oneOfNodeOrValueTypes = types;
return validate;
}
function assertValueType(type) {
function validate(node, key, val) {
if (getType(val) === type) {
return;
}
throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`);
}
validate.type = type;
return validate;
}
function assertShape(shape) {
const keys = Object.keys(shape);
function validate(node, key, val) {
const errors = [];
for (const property of keys) {
try {
(0, _validate.validateField)(node, property, val[property], shape[property]);
} catch (error) {
if (error instanceof TypeError) {
errors.push(error.message);
continue;
}
throw error;
}
}
if (errors.length) {
throw new TypeError(`Property ${key} of ${node.type} expected to have the following:\n${errors.join("\n")}`);
}
}
validate.shapeOf = shape;
return validate;
}
function assertOptionalChainStart() {
function validate(node) {
var _current;
let current = node;
while (node) {
const {
type
} = current;
if (type === "OptionalCallExpression") {
if (current.optional) return;
current = current.callee;
continue;
}
if (type === "OptionalMemberExpression") {
if (current.optional) return;
current = current.object;
continue;
}
break;
}
throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${(_current = current) == null ? void 0 : _current.type}`);
}
return validate;
}
function chain(...fns) {
function validate(...args) {
for (const fn of fns) {
fn(...args);
}
}
validate.chainOf = fns;
if (fns.length >= 2 && "type" in fns[0] && fns[0].type === "array" && !("each" in fns[1])) {
throw new Error(`An assertValueType("array") validator can only be followed by an assertEach(...) validator.`);
}
return validate;
}
const validTypeOpts = new Set(["aliases", "builder", "deprecatedAlias", "fields", "inherits", "visitor", "validate", "unionShape"]);
const validFieldKeys = new Set(["default", "optional", "deprecated", "validate"]);
const store = {};
function defineAliasedType(...aliases) {
return (type, opts = {}) => {
let defined = opts.aliases;
if (!defined) {
var _store$opts$inherits$;
if (opts.inherits) defined = (_store$opts$inherits$ = store[opts.inherits].aliases) == null ? void 0 : _store$opts$inherits$.slice();
defined != null ? defined : defined = [];
opts.aliases = defined;
}
const additional = aliases.filter(a => !defined.includes(a));
defined.unshift(...additional);
defineType(type, opts);
};
}
function defineType(type, opts = {}) {
const inherits = opts.inherits && store[opts.inherits] || {};
let fields = opts.fields;
if (!fields) {
fields = {};
if (inherits.fields) {
const keys = Object.getOwnPropertyNames(inherits.fields);
for (const key of keys) {
const field = inherits.fields[key];
const def = field.default;
if (Array.isArray(def) ? def.length > 0 : def && typeof def === "object") {
throw new Error("field defaults can only be primitives or empty arrays currently");
}
fields[key] = {
default: Array.isArray(def) ? [] : def,
optional: field.optional,
deprecated: field.deprecated,
validate: field.validate
};
}
}
}
const visitor = opts.visitor || inherits.visitor || [];
const aliases = opts.aliases || inherits.aliases || [];
const builder = opts.builder || inherits.builder || opts.visitor || [];
for (const k of Object.keys(opts)) {
if (!validTypeOpts.has(k)) {
throw new Error(`Unknown type option "${k}" on ${type}`);
}
}
if (opts.deprecatedAlias) {
DEPRECATED_KEYS[opts.deprecatedAlias] = type;
}
for (const key of visitor.concat(builder)) {
fields[key] = fields[key] || {};
}
for (const key of Object.keys(fields)) {
const field = fields[key];
if (field.default !== undefined && !builder.includes(key)) {
field.optional = true;
}
if (field.default === undefined) {
field.default = null;
} else if (!field.validate && field.default != null) {
field.validate = assertValueType(getType(field.default));
}
for (const k of Object.keys(field)) {
if (!validFieldKeys.has(k)) {
throw new Error(`Unknown field key "${k}" on ${type}.${key}`);
}
}
}
VISITOR_KEYS[type] = opts.visitor = visitor;
BUILDER_KEYS[type] = opts.builder = builder;
NODE_FIELDS[type] = opts.fields = fields;
ALIAS_KEYS[type] = opts.aliases = aliases;
aliases.forEach(alias => {
FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || [];
FLIPPED_ALIAS_KEYS[alias].push(type);
});
if (opts.validate) {
NODE_PARENT_VALIDATIONS[type] = opts.validate;
}
if (opts.unionShape) {
NODE_UNION_SHAPES__PRIVATE[type] = opts.unionShape;
}
store[type] = opts;
}
//# sourceMappingURL=utils.js.map
@@ -0,0 +1,25 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.decorators = void 0;
const base_config_1 = require("./base-config");
exports.decorators = {
libs: [],
variables: [
['ClassMemberDecoratorContext', base_config_1.TYPE],
['DecoratorContext', base_config_1.TYPE],
['DecoratorMetadataObject', base_config_1.TYPE],
['DecoratorMetadata', base_config_1.TYPE],
['ClassDecoratorContext', base_config_1.TYPE],
['ClassMethodDecoratorContext', base_config_1.TYPE],
['ClassGetterDecoratorContext', base_config_1.TYPE],
['ClassSetterDecoratorContext', base_config_1.TYPE],
['ClassAccessorDecoratorContext', base_config_1.TYPE],
['ClassAccessorDecoratorTarget', base_config_1.TYPE],
['ClassAccessorDecoratorResult', base_config_1.TYPE],
['ClassFieldDecoratorContext', base_config_1.TYPE],
],
};
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 typescript-eslint and other contributors
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.
@@ -0,0 +1 @@
{"version":3,"file":"users-2.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1 @@
{"version":3,"file":"SwitchLayoutGroupContext.mjs","sources":["../../../src/context/SwitchLayoutGroupContext.ts"],"sourcesContent":["\"use client\"\n\nimport type { Transition, IProjectionNode } from \"motion-dom\"\nimport { createContext } from \"react\"\n\nexport interface SwitchLayoutGroup {\n register?: (member: IProjectionNode) => void\n deregister?: (member: IProjectionNode) => void\n}\n\nexport type SwitchLayoutGroupContext = SwitchLayoutGroup &\n InitialPromotionConfig\n\nexport type InitialPromotionConfig = {\n /**\n * The initial transition to use when the elements in this group mount (and automatically promoted).\n * Subsequent updates should provide a transition in the promote method.\n */\n transition?: Transition\n /**\n * If the follow tree should preserve its opacity when the lead is promoted on mount\n */\n shouldPreserveFollowOpacity?: (member: IProjectionNode) => boolean\n}\n\n/**\n * Internal, exported only for usage in Framer\n */\nexport const SwitchLayoutGroupContext = createContext<SwitchLayoutGroupContext>(\n {}\n)\n"],"names":[],"mappings":";;;AAyBA;;AAEG;;;"}
@@ -0,0 +1,6 @@
export { VitestNodeSnapshotEnvironment as VitestSnapshotEnvironment } from './chunks/node.COQbm6gK.js';
import '@vitest/snapshot/environment';
import './chunks/utils.BX5Fg8C4.js';
import '@vitest/utils/timers';
console.warn("Importing from \"vitest/snapshot\" is deprecated since Vitest 4.1. Please use \"vitest/runtime\" instead.");
@@ -0,0 +1,25 @@
(MIT License)
Copyright (c) 2013 [Ramesh Nair](http://www.hiddentao.com/)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
{"version":3,"names":["dispose_SuppressedError","error","suppressed","SuppressedError","stack","Error","prototype","Object","create","constructor","value","writable","configurable","_dispose","hasError","next","length","r","pop","p","d","call","v","a","Promise","resolve","then","err","e"],"sources":["../../src/helpers/dispose.js"],"sourcesContent":["/* @minVersion 7.22.0 */\n/* @onlyBabel7 */\n\nfunction dispose_SuppressedError(error, suppressed) {\n if (typeof SuppressedError !== \"undefined\") {\n dispose_SuppressedError = SuppressedError;\n } else {\n dispose_SuppressedError = function SuppressedError(error, suppressed) {\n this.suppressed = suppressed;\n this.error = error;\n this.stack = new Error().stack;\n };\n dispose_SuppressedError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: dispose_SuppressedError,\n writable: true,\n configurable: true,\n },\n });\n }\n return new dispose_SuppressedError(error, suppressed);\n}\n\nexport default function _dispose(stack, error, hasError) {\n function next() {\n while (stack.length > 0) {\n try {\n var r = stack.pop();\n var p = r.d.call(r.v);\n if (r.a) return Promise.resolve(p).then(next, err);\n } catch (e) {\n return err(e);\n }\n }\n if (hasError) throw error;\n }\n\n function err(e) {\n error = hasError ? new dispose_SuppressedError(error, e) : e;\n hasError = true;\n\n return next();\n }\n\n return next();\n}\n"],"mappings":";;;;;;AAGA,SAASA,uBAAuBA,CAACC,KAAK,EAAEC,UAAU,EAAE;EAClD,IAAI,OAAOC,eAAe,KAAK,WAAW,EAAE;IAC1CH,uBAAuB,GAAGG,eAAe;EAC3C,CAAC,MAAM;IACLH,uBAAuB,GAAG,SAASG,eAAeA,CAACF,KAAK,EAAEC,UAAU,EAAE;MACpE,IAAI,CAACA,UAAU,GAAGA,UAAU;MAC5B,IAAI,CAACD,KAAK,GAAGA,KAAK;MAClB,IAAI,CAACG,KAAK,GAAG,IAAIC,KAAK,CAAC,CAAC,CAACD,KAAK;IAChC,CAAC;IACDJ,uBAAuB,CAACM,SAAS,GAAGC,MAAM,CAACC,MAAM,CAACH,KAAK,CAACC,SAAS,EAAE;MACjEG,WAAW,EAAE;QACXC,KAAK,EAAEV,uBAAuB;QAC9BW,QAAQ,EAAE,IAAI;QACdC,YAAY,EAAE;MAChB;IACF,CAAC,CAAC;EACJ;EACA,OAAO,IAAIZ,uBAAuB,CAACC,KAAK,EAAEC,UAAU,CAAC;AACvD;AAEe,SAASW,QAAQA,CAACT,KAAK,EAAEH,KAAK,EAAEa,QAAQ,EAAE;EACvD,SAASC,IAAIA,CAAA,EAAG;IACd,OAAOX,KAAK,CAACY,MAAM,GAAG,CAAC,EAAE;MACvB,IAAI;QACF,IAAIC,CAAC,GAAGb,KAAK,CAACc,GAAG,CAAC,CAAC;QACnB,IAAIC,CAAC,GAAGF,CAAC,CAACG,CAAC,CAACC,IAAI,CAACJ,CAAC,CAACK,CAAC,CAAC;QACrB,IAAIL,CAAC,CAACM,CAAC,EAAE,OAAOC,OAAO,CAACC,OAAO,CAACN,CAAC,CAAC,CAACO,IAAI,CAACX,IAAI,EAAEY,GAAG,CAAC;MACpD,CAAC,CAAC,OAAOC,CAAC,EAAE;QACV,OAAOD,GAAG,CAACC,CAAC,CAAC;MACf;IACF;IACA,IAAId,QAAQ,EAAE,MAAMb,KAAK;EAC3B;EAEA,SAAS0B,GAAGA,CAACC,CAAC,EAAE;IACd3B,KAAK,GAAGa,QAAQ,GAAG,IAAId,uBAAuB,CAACC,KAAK,EAAE2B,CAAC,CAAC,GAAGA,CAAC;IAC5Dd,QAAQ,GAAG,IAAI;IAEf,OAAOC,IAAI,CAAC,CAAC;EACf;EAEA,OAAOA,IAAI,CAAC,CAAC;AACf","ignoreList":[]}
@@ -0,0 +1 @@
{"version":3,"file":"SafeFragment.js","names":[],"sources":["../../src/SafeFragment.tsx"],"sourcesContent":["import * as React from 'react'\n\nexport function SafeFragment(props: any) {\n return <>{props.children}</>\n}\n"],"mappings":";;;AAEA,SAAgB,aAAa,OAAY;AACvC,QAAO,oBAAA,UAAA,EAAA,UAAG,MAAM,UAAY,CAAA"}
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../src/index.ts", "../src/primitive.tsx"],
"sourcesContent": ["export * from './primitive';\nexport type * from './types';\n", "/* eslint-disable no-restricted-properties */\n\n/* eslint-disable no-restricted-globals */\nexport const canUseDOM = !!(\n typeof window !== 'undefined' &&\n window.document &&\n window.document.createElement\n);\n/* eslint-enable no-restricted-globals */\n\nexport function composeEventHandlers<E extends { defaultPrevented: boolean }>(\n originalEventHandler?: (event: E) => void,\n ourEventHandler?: (event: E) => void,\n { checkForDefaultPrevented = true } = {}\n) {\n return function handleEvent(event: E) {\n originalEventHandler?.(event);\n\n if (checkForDefaultPrevented === false || !event.defaultPrevented) {\n return ourEventHandler?.(event);\n }\n };\n}\n\nexport function getOwnerWindow(element: Node | null | undefined) {\n if (!canUseDOM) {\n throw new Error('Cannot access window outside of the DOM');\n }\n // eslint-disable-next-line no-restricted-globals\n return element?.ownerDocument?.defaultView ?? window;\n}\n\nexport function getOwnerDocument(element: Node | null | undefined) {\n if (!canUseDOM) {\n throw new Error('Cannot access document outside of the DOM');\n }\n // eslint-disable-next-line no-restricted-globals\n return element?.ownerDocument ?? document;\n}\n\n/**\n * Lifted from https://github.com/ariakit/ariakit/blob/main/packages/ariakit-core/src/utils/dom.ts#L37\n * MIT License, Copyright (c) AriaKit.\n */\nexport function getActiveElement(\n node: Node | null | undefined,\n activeDescendant = false\n): HTMLElement | null {\n const { activeElement } = getOwnerDocument(node);\n if (!activeElement?.nodeName) {\n // `activeElement` might be an empty object if we're interacting with elements\n // inside of an iframe.\n return null;\n }\n\n if (isFrame(activeElement) && activeElement.contentDocument) {\n return getActiveElement(activeElement.contentDocument.body, activeDescendant);\n }\n\n if (activeDescendant) {\n const id = activeElement.getAttribute('aria-activedescendant');\n if (id) {\n const element = getOwnerDocument(activeElement).getElementById(id);\n if (element) {\n return element;\n }\n }\n }\n\n return activeElement as HTMLElement | null;\n}\n\nexport function isFrame(element: Element): element is HTMLIFrameElement {\n return element.tagName === 'IFRAME';\n}\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,YAAY,CAAC,EACxB,OAAO,WAAW,eAClB,OAAO,YACP,OAAO,SAAS;AAIX,SAAS,qBACd,sBACA,iBACA,EAAE,2BAA2B,KAAK,IAAI,CAAC,GACvC;AACA,SAAO,SAAS,YAAY,OAAU;AACpC,2BAAuB,KAAK;AAE5B,QAAI,6BAA6B,SAAS,CAAC,MAAM,kBAAkB;AACjE,aAAO,kBAAkB,KAAK;AAAA,IAChC;AAAA,EACF;AACF;AAEO,SAAS,eAAe,SAAkC;AAC/D,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,SAAO,SAAS,eAAe,eAAe;AAChD;AAEO,SAAS,iBAAiB,SAAkC;AACjE,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D;AAEA,SAAO,SAAS,iBAAiB;AACnC;AAMO,SAAS,iBACd,MACA,mBAAmB,OACC;AACpB,QAAM,EAAE,cAAc,IAAI,iBAAiB,IAAI;AAC/C,MAAI,CAAC,eAAe,UAAU;AAG5B,WAAO;AAAA,EACT;AAEA,MAAI,QAAQ,aAAa,KAAK,cAAc,iBAAiB;AAC3D,WAAO,iBAAiB,cAAc,gBAAgB,MAAM,gBAAgB;AAAA,EAC9E;AAEA,MAAI,kBAAkB;AACpB,UAAM,KAAK,cAAc,aAAa,uBAAuB;AAC7D,QAAI,IAAI;AACN,YAAM,UAAU,iBAAiB,aAAa,EAAE,eAAe,EAAE;AACjE,UAAI,SAAS;AACX,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,QAAQ,SAAgD;AACtE,SAAO,QAAQ,YAAY;AAC7B;",
"names": []
}
@@ -0,0 +1 @@
{"version":3,"file":"pen.js","sources":["../../../src/icons/pen.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Pen\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjEuMTc0IDYuODEyYTEgMSAwIDAgMC0zLjk4Ni0zLjk4N0wzLjg0MiAxNi4xNzRhMiAyIDAgMCAwLS41LjgzbC0xLjMyMSA0LjM1MmEuNS41IDAgMCAwIC42MjMuNjIybDQuMzUzLTEuMzJhMiAyIDAgMCAwIC44My0uNDk3eiIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/pen\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst Pen = createLucideIcon('Pen', [\n [\n 'path',\n {\n d: 'M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z',\n key: '1a8usu',\n },\n ],\n]);\n\nexport default Pen;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,iBAAiB,KAAO,CAAA,CAAA,CAAA;AAAA,CAClC,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA;AACF,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-dom.react-server.production.js');
} else {
module.exports = require('./cjs/react-dom.react-server.development.js');
}
@@ -0,0 +1 @@
{"version":3,"file":"error.js","sourceRoot":"","sources":["../../../lib/vocabularies/jtd/error.ts"],"names":[],"mappings":";;;AACA,mDAA6C;AAQ7C,SAAgB,SAAS,CAAC,CAAS;IACjC,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,CAAC,CAAC;QAC1C,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,CAAC;KACzC,CAAA;AACH,CAAC;AALD,8BAKC;AAED,SAAgB,gBAAgB,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACzE,OAAO,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAC,CAAC,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAA;AACzE,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe,CAAC,EAAC,YAAY,EAAkB,EAAE,CAAS;IACxE,OAAO,IAAA,WAAC,EAAA,UAAU,CAAC,eAAe,CAAC,CAAC,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,CAAA,GAAG,CAAA;AAC/D,CAAC;AAFD,0CAEC"}
@@ -0,0 +1,164 @@
#include "DirTree.hh"
#include <inttypes.h>
// "Meyer's singleton", construction is ordered by use, likewise (reverse) for destruction.
// https://stackoverflow.com/a/17713799
// https://laristra.github.io/flecsi/src/developer-guide/patterns/meyers_singleton.html
static std::mutex& mDirCacheMutex() {
static std::mutex mutex;
return mutex;
}
static std::unordered_map<std::string, std::weak_ptr<DirTree>>& dirTreeCache() {
static std::unordered_map<std::string, std::weak_ptr<DirTree>> cache;
return cache;
}
struct DirTreeDeleter {
void operator()(DirTree *tree) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
std::unordered_map<std::string, std::weak_ptr<DirTree>> &cache = dirTreeCache();
cache.erase(tree->root);
delete tree;
// Free up memory.
if (cache.size() == 0) {
cache.rehash(0);
}
}
};
std::shared_ptr<DirTree> DirTree::getCached(std::string root) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
std::unordered_map<std::string, std::weak_ptr<DirTree>> &cache = dirTreeCache();
auto found = cache.find(root);
std::shared_ptr<DirTree> tree;
// Use cached tree, or create an empty one.
if (found != cache.end()) {
tree = found->second.lock();
} else {
tree = std::shared_ptr<DirTree>(new DirTree(root), DirTreeDeleter());
cache.emplace(root, tree);
}
return tree;
}
DirTree::DirTree(std::string root, FILE *f) : root(root), isComplete(true) {
size_t size;
if (fscanf(f, "%zu", &size)) {
for (size_t i = 0; i < size; i++) {
DirEntry entry(f);
entries.emplace(entry.path, entry);
}
}
}
// Internal find method that has no lock
DirEntry *DirTree::_find(std::string path) {
auto found = entries.find(path);
if (found == entries.end()) {
return NULL;
}
return &found->second;
}
DirEntry *DirTree::add(std::string path, uint64_t mtime, bool isDir) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
DirEntry entry(path, mtime, isDir);
auto it = entries.emplace(entry.path, entry);
return &it.first->second;
}
DirEntry *DirTree::find(std::string path) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
return _find(path);
}
DirEntry *DirTree::update(std::string path, uint64_t mtime) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
DirEntry *found = _find(path);
if (found) {
found->mtime = mtime;
}
return found;
}
void DirTree::remove(std::string path) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
DirEntry *found = _find(path);
// Remove all sub-entries if this is a directory
if (found && found->isDir) {
std::string pathStart = path + DIR_SEP;
for (auto it = entries.begin(); it != entries.end();) {
if (it->first.rfind(pathStart, 0) == 0) {
it = entries.erase(it);
} else {
it++;
}
}
}
entries.erase(path);
}
void DirTree::write(FILE *f) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
fprintf(f, "%zu\n", entries.size());
for (auto it = entries.begin(); it != entries.end(); it++) {
it->second.write(f);
}
}
void DirTree::getChanges(DirTree *snapshot, EventList &events) {
std::lock_guard<std::mutex> lock(mDirCacheMutex());
std::lock_guard<std::mutex> snapshotLock(snapshot->mMutex);
for (auto it = entries.begin(); it != entries.end(); it++) {
auto found = snapshot->entries.find(it->first);
if (found == snapshot->entries.end()) {
events.create(it->second.path);
} else if (found->second.mtime != it->second.mtime && !found->second.isDir && !it->second.isDir) {
events.update(it->second.path);
}
}
for (auto it = snapshot->entries.begin(); it != snapshot->entries.end(); it++) {
size_t count = entries.count(it->first);
if (count == 0) {
events.remove(it->second.path);
}
}
}
DirEntry::DirEntry(std::string p, uint64_t t, bool d) {
path = p;
mtime = t;
isDir = d;
state = NULL;
}
DirEntry::DirEntry(FILE *f) {
size_t size;
if (fscanf(f, "%zu", &size)) {
path.resize(size);
if (fread(&path[0], sizeof(char), size, f)) {
int d = 0;
fscanf(f, "%" PRIu64 " %d\n", &mtime, &d);
isDir = d == 1;
}
}
}
void DirEntry::write(FILE *f) const {
fprintf(f, "%zu%s%" PRIu64 " %d\n", path.size(), path.c_str(), mtime, isDir);
}
@@ -0,0 +1 @@
{"version":3,"file":"book-dashed.js","sources":["../../../src/icons/book-dashed.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name BookDashed\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgMTdoMS41IiAvPgogIDxwYXRoIGQ9Ik0xMiAyMmgxLjUiIC8+CiAgPHBhdGggZD0iTTEyIDJoMS41IiAvPgogIDxwYXRoIGQ9Ik0xNy41IDIySDE5YTEgMSAwIDAgMCAxLTEiIC8+CiAgPHBhdGggZD0iTTE3LjUgMkgxOWExIDEgMCAwIDEgMSAxdjEuNSIgLz4KICA8cGF0aCBkPSJNMjAgMTR2M2gtMi41IiAvPgogIDxwYXRoIGQ9Ik0yMCA4LjVWMTAiIC8+CiAgPHBhdGggZD0iTTQgMTBWOC41IiAvPgogIDxwYXRoIGQ9Ik00IDE5LjVWMTQiIC8+CiAgPHBhdGggZD0iTTQgNC41QTIuNSAyLjUgMCAwIDEgNi41IDJIOCIgLz4KICA8cGF0aCBkPSJNOCAyMkg2LjVhMSAxIDAgMCAxIDAtNUg4IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/book-dashed\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst BookDashed = createLucideIcon('BookDashed', [\n ['path', { d: 'M12 17h1.5', key: '1gkc67' }],\n ['path', { d: 'M12 22h1.5', key: '1my7sn' }],\n ['path', { d: 'M12 2h1.5', key: '19tvb7' }],\n ['path', { d: 'M17.5 22H19a1 1 0 0 0 1-1', key: '10akbh' }],\n ['path', { d: 'M17.5 2H19a1 1 0 0 1 1 1v1.5', key: '1vrfjs' }],\n ['path', { d: 'M20 14v3h-2.5', key: '1naeju' }],\n ['path', { d: 'M20 8.5V10', key: '1ctpfu' }],\n ['path', { d: 'M4 10V8.5', key: '1o3zg5' }],\n ['path', { d: 'M4 19.5V14', key: 'ob81pf' }],\n ['path', { d: 'M4 4.5A2.5 2.5 0 0 1 6.5 2H8', key: 's8vcyb' }],\n ['path', { d: 'M8 22H6.5a1 1 0 0 1 0-5H8', key: '1cu73q' }],\n]);\n\nexport default BookDashed;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAa,iBAAiB,YAAc,CAAA,CAAA,CAAA;AAAA,CAAA,CAChD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA6B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1D,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7D,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAiB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC7D,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA6B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5D,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,132 @@
import { Client } from '../../client/index.js';
import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js';
import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js';
/**
* Multiple Clients MCP Example
*
* This client demonstrates how to:
* 1. Create multiple MCP clients in parallel
* 2. Each client calls a single tool
* 3. Track notifications from each client independently
*/
// Command line args processing
const args = process.argv.slice(2);
const serverUrl = args[0] || 'http://localhost:3000/mcp';
async function createAndRunClient(config) {
console.log(`[${config.id}] Creating client: ${config.name}`);
const client = new Client({
name: config.name,
version: '1.0.0'
});
const transport = new StreamableHTTPClientTransport(new URL(serverUrl));
// Set up client-specific error handler
client.onerror = error => {
console.error(`[${config.id}] Client error:`, error);
};
// Set up client-specific notification handler
client.setNotificationHandler(LoggingMessageNotificationSchema, notification => {
console.log(`[${config.id}] Notification: ${notification.params.data}`);
});
try {
// Connect to the server
await client.connect(transport);
console.log(`[${config.id}] Connected to MCP server`);
// Call the specified tool
console.log(`[${config.id}] Calling tool: ${config.toolName}`);
const toolRequest = {
method: 'tools/call',
params: {
name: config.toolName,
arguments: {
...config.toolArguments,
// Add client ID to arguments for identification in notifications
caller: config.id
}
}
};
const result = await client.request(toolRequest, CallToolResultSchema);
console.log(`[${config.id}] Tool call completed`);
// Keep the connection open for a bit to receive notifications
await new Promise(resolve => setTimeout(resolve, 5000));
// Disconnect
await transport.close();
console.log(`[${config.id}] Disconnected from MCP server`);
return { id: config.id, result };
}
catch (error) {
console.error(`[${config.id}] Error:`, error);
throw error;
}
}
async function main() {
console.log('MCP Multiple Clients Example');
console.log('============================');
console.log(`Server URL: ${serverUrl}`);
console.log('');
try {
// Define client configurations
const clientConfigs = [
{
id: 'client1',
name: 'basic-client-1',
toolName: 'start-notification-stream',
toolArguments: {
interval: 3, // 1 second between notifications
count: 5 // Send 5 notifications
}
},
{
id: 'client2',
name: 'basic-client-2',
toolName: 'start-notification-stream',
toolArguments: {
interval: 2, // 2 seconds between notifications
count: 3 // Send 3 notifications
}
},
{
id: 'client3',
name: 'basic-client-3',
toolName: 'start-notification-stream',
toolArguments: {
interval: 1, // 0.5 second between notifications
count: 8 // Send 8 notifications
}
}
];
// Start all clients in parallel
console.log(`Starting ${clientConfigs.length} clients in parallel...`);
console.log('');
const clientPromises = clientConfigs.map(config => createAndRunClient(config));
const results = await Promise.all(clientPromises);
// Display results from all clients
console.log('\n=== Final Results ===');
results.forEach(({ id, result }) => {
console.log(`\n[${id}] Tool result:`);
if (Array.isArray(result.content)) {
result.content.forEach((item) => {
if (item.type === 'text' && item.text) {
console.log(` ${item.text}`);
}
else {
console.log(` ${item.type} content:`, item);
}
});
}
else {
console.log(` Unexpected result format:`, result);
}
});
console.log('\n=== All clients completed successfully ===');
}
catch (error) {
console.error('Error running multiple clients:', error);
process.exit(1);
}
}
// Start the example
main().catch((error) => {
console.error('Error running MCP multiple clients example:', error);
process.exit(1);
});
//# sourceMappingURL=multipleClientsParallel.js.map
@@ -0,0 +1,27 @@
import { FlattenedEncrypt } from '../flattened/encrypt.js';
export class CompactEncrypt {
#flattened;
constructor(plaintext) {
this.#flattened = new FlattenedEncrypt(plaintext);
}
setContentEncryptionKey(cek) {
this.#flattened.setContentEncryptionKey(cek);
return this;
}
setInitializationVector(iv) {
this.#flattened.setInitializationVector(iv);
return this;
}
setProtectedHeader(protectedHeader) {
this.#flattened.setProtectedHeader(protectedHeader);
return this;
}
setKeyManagementParameters(parameters) {
this.#flattened.setKeyManagementParameters(parameters);
return this;
}
async encrypt(key, options) {
const jwe = await this.#flattened.encrypt(key, options);
return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');
}
}
@@ -0,0 +1,39 @@
declare function getPattern(): RegExp;
/**
* A list of bot identifiers to be used in a regular expression against user agent strings.
*/
declare const list: string[];
/**
* Check if the given user agent includes a bot pattern.
*/
declare function isbot(userAgent?: string | null): boolean;
/**
* Check if the given user agent includes a bot pattern. Naive implementation (less accurate).
*/
declare const isbotNaive: typeof isbot;
/**
* Create a custom isbot function with a custom pattern.
*/
declare const createIsbot: (customPattern: RegExp) => typeof isbot;
/**
* Create a custom isbot function with a custom pattern.
*/
declare const createIsbotFromList: (list: string[]) => typeof isbot;
/**
* Find the first part of the user agent that matches a bot pattern.
*/
declare const isbotMatch: (userAgent: Parameters<typeof isbot>[0]) => string | null;
/**
* Find all parts of the user agent that match a bot pattern.
*/
declare const isbotMatches: (userAgent: Parameters<typeof isbot>[0]) => string[];
/**
* Find the first bot pattern that match the given user agent.
*/
declare const isbotPattern: (userAgent: Parameters<typeof isbot>[0]) => string | null;
/**
* Find all bot patterns that match the given user agent.
*/
declare const isbotPatterns: (userAgent: Parameters<typeof isbot>[0]) => string[];
export { createIsbot, createIsbotFromList, getPattern, isbot, isbotMatch, isbotMatches, isbotNaive, isbotPattern, isbotPatterns, list };
@@ -0,0 +1,496 @@
import htmlDecodeTree from "./generated/decode-data-html.js";
import xmlDecodeTree from "./generated/decode-data-xml.js";
import decodeCodePoint, { replaceCodePoint, fromCodePoint, } from "./decode_codepoint.js";
// Re-export for use by eg. htmlparser2
export { htmlDecodeTree, xmlDecodeTree, decodeCodePoint };
export { replaceCodePoint, fromCodePoint } from "./decode_codepoint.js";
var CharCodes;
(function (CharCodes) {
CharCodes[CharCodes["NUM"] = 35] = "NUM";
CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS";
CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
CharCodes[CharCodes["NINE"] = 57] = "NINE";
CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z";
CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A";
CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F";
CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z";
})(CharCodes || (CharCodes = {}));
/** Bit that needs to be set to convert an upper case ASCII character to lower case */
const TO_LOWER_BIT = 0b100000;
export var BinTrieFlags;
(function (BinTrieFlags) {
BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
})(BinTrieFlags || (BinTrieFlags = {}));
function isNumber(code) {
return code >= CharCodes.ZERO && code <= CharCodes.NINE;
}
function isHexadecimalCharacter(code) {
return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) ||
(code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F));
}
function isAsciiAlphaNumeric(code) {
return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) ||
(code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) ||
isNumber(code));
}
/**
* Checks if the given character is a valid end character for an entity in an attribute.
*
* Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
* See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
*/
function isEntityInAttributeInvalidEnd(code) {
return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
}
var EntityDecoderState;
(function (EntityDecoderState) {
EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart";
EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart";
EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal";
EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex";
EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity";
})(EntityDecoderState || (EntityDecoderState = {}));
export var DecodingMode;
(function (DecodingMode) {
/** Entities in text nodes that can end with any character. */
DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy";
/** Only allow entities terminated with a semicolon. */
DecodingMode[DecodingMode["Strict"] = 1] = "Strict";
/** Entities in attributes have limitations on ending characters. */
DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute";
})(DecodingMode || (DecodingMode = {}));
/**
* Token decoder with support of writing partial entities.
*/
export class EntityDecoder {
constructor(
/** The tree used to decode entities. */
decodeTree,
/**
* The function that is called when a codepoint is decoded.
*
* For multi-byte named entities, this will be called multiple times,
* with the second codepoint, and the same `consumed` value.
*
* @param codepoint The decoded codepoint.
* @param consumed The number of bytes consumed by the decoder.
*/
emitCodePoint,
/** An object that is used to produce errors. */
errors) {
this.decodeTree = decodeTree;
this.emitCodePoint = emitCodePoint;
this.errors = errors;
/** The current state of the decoder. */
this.state = EntityDecoderState.EntityStart;
/** Characters that were consumed while parsing an entity. */
this.consumed = 1;
/**
* The result of the entity.
*
* Either the result index of a numeric entity, or the codepoint of a
* numeric entity.
*/
this.result = 0;
/** The current index in the decode tree. */
this.treeIndex = 0;
/** The number of characters that were consumed in excess. */
this.excess = 1;
/** The mode in which the decoder is operating. */
this.decodeMode = DecodingMode.Strict;
}
/** Resets the instance to make it reusable. */
startEntity(decodeMode) {
this.decodeMode = decodeMode;
this.state = EntityDecoderState.EntityStart;
this.result = 0;
this.treeIndex = 0;
this.excess = 1;
this.consumed = 1;
}
/**
* Write an entity to the decoder. This can be called multiple times with partial entities.
* If the entity is incomplete, the decoder will return -1.
*
* Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
* entity is incomplete, and resume when the next string is written.
*
* @param string The string containing the entity (or a continuation of the entity).
* @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
*/
write(str, offset) {
switch (this.state) {
case EntityDecoderState.EntityStart: {
if (str.charCodeAt(offset) === CharCodes.NUM) {
this.state = EntityDecoderState.NumericStart;
this.consumed += 1;
return this.stateNumericStart(str, offset + 1);
}
this.state = EntityDecoderState.NamedEntity;
return this.stateNamedEntity(str, offset);
}
case EntityDecoderState.NumericStart: {
return this.stateNumericStart(str, offset);
}
case EntityDecoderState.NumericDecimal: {
return this.stateNumericDecimal(str, offset);
}
case EntityDecoderState.NumericHex: {
return this.stateNumericHex(str, offset);
}
case EntityDecoderState.NamedEntity: {
return this.stateNamedEntity(str, offset);
}
}
}
/**
* Switches between the numeric decimal and hexadecimal states.
*
* Equivalent to the `Numeric character reference state` in the HTML spec.
*
* @param str The string containing the entity (or a continuation of the entity).
* @param offset The current offset.
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
*/
stateNumericStart(str, offset) {
if (offset >= str.length) {
return -1;
}
if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
this.state = EntityDecoderState.NumericHex;
this.consumed += 1;
return this.stateNumericHex(str, offset + 1);
}
this.state = EntityDecoderState.NumericDecimal;
return this.stateNumericDecimal(str, offset);
}
addToNumericResult(str, start, end, base) {
if (start !== end) {
const digitCount = end - start;
this.result =
this.result * Math.pow(base, digitCount) +
parseInt(str.substr(start, digitCount), base);
this.consumed += digitCount;
}
}
/**
* Parses a hexadecimal numeric entity.
*
* Equivalent to the `Hexademical character reference state` in the HTML spec.
*
* @param str The string containing the entity (or a continuation of the entity).
* @param offset The current offset.
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
*/
stateNumericHex(str, offset) {
const startIdx = offset;
while (offset < str.length) {
const char = str.charCodeAt(offset);
if (isNumber(char) || isHexadecimalCharacter(char)) {
offset += 1;
}
else {
this.addToNumericResult(str, startIdx, offset, 16);
return this.emitNumericEntity(char, 3);
}
}
this.addToNumericResult(str, startIdx, offset, 16);
return -1;
}
/**
* Parses a decimal numeric entity.
*
* Equivalent to the `Decimal character reference state` in the HTML spec.
*
* @param str The string containing the entity (or a continuation of the entity).
* @param offset The current offset.
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
*/
stateNumericDecimal(str, offset) {
const startIdx = offset;
while (offset < str.length) {
const char = str.charCodeAt(offset);
if (isNumber(char)) {
offset += 1;
}
else {
this.addToNumericResult(str, startIdx, offset, 10);
return this.emitNumericEntity(char, 2);
}
}
this.addToNumericResult(str, startIdx, offset, 10);
return -1;
}
/**
* Validate and emit a numeric entity.
*
* Implements the logic from the `Hexademical character reference start
* state` and `Numeric character reference end state` in the HTML spec.
*
* @param lastCp The last code point of the entity. Used to see if the
* entity was terminated with a semicolon.
* @param expectedLength The minimum number of characters that should be
* consumed. Used to validate that at least one digit
* was consumed.
* @returns The number of characters that were consumed.
*/
emitNumericEntity(lastCp, expectedLength) {
var _a;
// Ensure we consumed at least one digit.
if (this.consumed <= expectedLength) {
(_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
return 0;
}
// Figure out if this is a legit end of the entity
if (lastCp === CharCodes.SEMI) {
this.consumed += 1;
}
else if (this.decodeMode === DecodingMode.Strict) {
return 0;
}
this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
if (this.errors) {
if (lastCp !== CharCodes.SEMI) {
this.errors.missingSemicolonAfterCharacterReference();
}
this.errors.validateNumericCharacterReference(this.result);
}
return this.consumed;
}
/**
* Parses a named entity.
*
* Equivalent to the `Named character reference state` in the HTML spec.
*
* @param str The string containing the entity (or a continuation of the entity).
* @param offset The current offset.
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
*/
stateNamedEntity(str, offset) {
const { decodeTree } = this;
let current = decodeTree[this.treeIndex];
// The mask is the number of bytes of the value, including the current byte.
let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
for (; offset < str.length; offset++, this.excess++) {
const char = str.charCodeAt(offset);
this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
if (this.treeIndex < 0) {
return this.result === 0 ||
// If we are parsing an attribute
(this.decodeMode === DecodingMode.Attribute &&
// We shouldn't have consumed any characters after the entity,
(valueLength === 0 ||
// And there should be no invalid characters.
isEntityInAttributeInvalidEnd(char)))
? 0
: this.emitNotTerminatedNamedEntity();
}
current = decodeTree[this.treeIndex];
valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
// If the branch is a value, store it and continue
if (valueLength !== 0) {
// If the entity is terminated by a semicolon, we are done.
if (char === CharCodes.SEMI) {
return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
}
// If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it.
if (this.decodeMode !== DecodingMode.Strict) {
this.result = this.treeIndex;
this.consumed += this.excess;
this.excess = 0;
}
}
}
return -1;
}
/**
* Emit a named entity that was not terminated with a semicolon.
*
* @returns The number of characters consumed.
*/
emitNotTerminatedNamedEntity() {
var _a;
const { result, decodeTree } = this;
const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
this.emitNamedEntityData(result, valueLength, this.consumed);
(_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference();
return this.consumed;
}
/**
* Emit a named entity.
*
* @param result The index of the entity in the decode tree.
* @param valueLength The number of bytes in the entity.
* @param consumed The number of characters consumed.
*
* @returns The number of characters consumed.
*/
emitNamedEntityData(result, valueLength, consumed) {
const { decodeTree } = this;
this.emitCodePoint(valueLength === 1
? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH
: decodeTree[result + 1], consumed);
if (valueLength === 3) {
// For multi-byte values, we need to emit the second byte.
this.emitCodePoint(decodeTree[result + 2], consumed);
}
return consumed;
}
/**
* Signal to the parser that the end of the input was reached.
*
* Remaining data will be emitted and relevant errors will be produced.
*
* @returns The number of characters consumed.
*/
end() {
var _a;
switch (this.state) {
case EntityDecoderState.NamedEntity: {
// Emit a named entity if we have one.
return this.result !== 0 &&
(this.decodeMode !== DecodingMode.Attribute ||
this.result === this.treeIndex)
? this.emitNotTerminatedNamedEntity()
: 0;
}
// Otherwise, emit a numeric entity if we have one.
case EntityDecoderState.NumericDecimal: {
return this.emitNumericEntity(0, 2);
}
case EntityDecoderState.NumericHex: {
return this.emitNumericEntity(0, 3);
}
case EntityDecoderState.NumericStart: {
(_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
return 0;
}
case EntityDecoderState.EntityStart: {
// Return 0 if we have no entity.
return 0;
}
}
}
}
/**
* Creates a function that decodes entities in a string.
*
* @param decodeTree The decode tree.
* @returns A function that decodes entities in a string.
*/
function getDecoder(decodeTree) {
let ret = "";
const decoder = new EntityDecoder(decodeTree, (str) => (ret += fromCodePoint(str)));
return function decodeWithTrie(str, decodeMode) {
let lastIndex = 0;
let offset = 0;
while ((offset = str.indexOf("&", offset)) >= 0) {
ret += str.slice(lastIndex, offset);
decoder.startEntity(decodeMode);
const len = decoder.write(str,
// Skip the "&"
offset + 1);
if (len < 0) {
lastIndex = offset + decoder.end();
break;
}
lastIndex = offset + len;
// If `len` is 0, skip the current `&` and continue.
offset = len === 0 ? lastIndex + 1 : lastIndex;
}
const result = ret + str.slice(lastIndex);
// Make sure we don't keep a reference to the final string.
ret = "";
return result;
};
}
/**
* Determines the branch of the current node that is taken given the current
* character. This function is used to traverse the trie.
*
* @param decodeTree The trie.
* @param current The current node.
* @param nodeIdx The index right after the current node and its value.
* @param char The current character.
* @returns The index of the next node, or -1 if no branch is taken.
*/
export function determineBranch(decodeTree, current, nodeIdx, char) {
const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
// Case 1: Single branch encoded in jump offset
if (branchCount === 0) {
return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
}
// Case 2: Multiple branches encoded in jump table
if (jumpOffset) {
const value = char - jumpOffset;
return value < 0 || value >= branchCount
? -1
: decodeTree[nodeIdx + value] - 1;
}
// Case 3: Multiple branches encoded in dictionary
// Binary search for the character.
let lo = nodeIdx;
let hi = lo + branchCount - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
const midVal = decodeTree[mid];
if (midVal < char) {
lo = mid + 1;
}
else if (midVal > char) {
hi = mid - 1;
}
else {
return decodeTree[mid + branchCount];
}
}
return -1;
}
const htmlDecoder = getDecoder(htmlDecodeTree);
const xmlDecoder = getDecoder(xmlDecodeTree);
/**
* Decodes an HTML string.
*
* @param str The string to decode.
* @param mode The decoding mode.
* @returns The decoded string.
*/
export function decodeHTML(str, mode = DecodingMode.Legacy) {
return htmlDecoder(str, mode);
}
/**
* Decodes an HTML string in an attribute.
*
* @param str The string to decode.
* @returns The decoded string.
*/
export function decodeHTMLAttribute(str) {
return htmlDecoder(str, DecodingMode.Attribute);
}
/**
* Decodes an HTML string, requiring all entities to be terminated by a semicolon.
*
* @param str The string to decode.
* @returns The decoded string.
*/
export function decodeHTMLStrict(str) {
return htmlDecoder(str, DecodingMode.Strict);
}
/**
* Decodes an XML string, requiring all entities to be terminated by a semicolon.
*
* @param str The string to decode.
* @returns The decoded string.
*/
export function decodeXML(str) {
return xmlDecoder(str, DecodingMode.Strict);
}
//# sourceMappingURL=decode.js.map
@@ -0,0 +1,9 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
export { default } from './columns-3.js';
//# sourceMappingURL=panels-left-right.js.map
@@ -0,0 +1,27 @@
import { useMatch } from "./useMatch.js";
//#region src/useLoaderData.tsx
/**
* Read and select the current route's loader data with type‑safety.
*
* Options:
* - `from`/`strict`: Choose which route's data to read and strictness
* - `select`: Map the loader data to a derived value
* - `structuralSharing`: Enable structural sharing for stable references
*
* @returns The loader data (or selected value) for the matched route.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLoaderDataHook
*/
function useLoaderData(opts) {
return useMatch({
from: opts.from,
strict: opts.strict,
structuralSharing: opts.structuralSharing,
select: (s) => {
return opts.select ? opts.select(s.loaderData) : s.loaderData;
}
});
}
//#endregion
export { useLoaderData };
//# sourceMappingURL=useLoaderData.js.map
@@ -0,0 +1,24 @@
Copyright 2012-2015 Yahoo! Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yahoo! Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,12 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib repo
Object.defineProperty(exports, "__esModule", { value: true });
exports.es2022_string = void 0;
const base_config_1 = require("./base-config");
exports.es2022_string = {
libs: [],
variables: [['String', base_config_1.TYPE]],
};
@@ -0,0 +1,29 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare namespace Intl {
/**
* The `Intl.getCanonicalLocales()` method returns an array containing
* the canonical locale names. Duplicates will be omitted and elements
* will be validated as structurally valid language tags.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales)
*
* @param locale A list of String values for which to get the canonical locale names
* @returns An array containing the canonical and validated locale names.
*/
function getCanonicalLocales(locale?: string | readonly string[]): string[];
}
@@ -0,0 +1,194 @@
import { backOff } from "./backoff";
import { BackoffOptions } from "./options";
describe("BackOff", () => {
const mockSuccessResponse = { success: true };
const mockFailResponse = { success: false };
let backOffRequest: () => Promise<any>;
let backOffOptions: BackoffOptions;
function initBackOff() {
return backOff(backOffRequest, backOffOptions);
}
function promiseThatIsResolved() {
return () => Promise.resolve(mockSuccessResponse);
}
function promiseThatIsRejected() {
return () => Promise.reject(mockFailResponse);
}
function promiseThatFailsOnceThenSucceeds() {
return (() => {
let firstAttempt = true;
const request = () => {
if (firstAttempt) {
firstAttempt = false;
return Promise.reject(mockFailResponse);
}
return Promise.resolve(mockSuccessResponse);
};
return request;
})();
}
beforeEach(() => {
backOffOptions = { startingDelay: 0 };
backOffRequest = jest.fn(promiseThatIsResolved());
});
describe("when request function is a promise that resolves", () => {
it("returns the resolved value", () => {
const request = initBackOff();
return request.then(response =>
expect(response).toBe(mockSuccessResponse)
);
});
it("calls the request function only once", () => {
const request = initBackOff();
return request.then(() =>
expect(backOffRequest).toHaveBeenCalledTimes(1)
);
});
it(`when the #backOffOptions.numOfAttempts is 0,
it overrides the value and calls the method only once`, () => {
backOffOptions.numOfAttempts = 0;
const request = initBackOff();
return request.then(() =>
expect(backOffRequest).toHaveBeenCalledTimes(1)
);
});
});
describe(`when the #backOffOptions.startingDelay is 100ms`, () => {
const startingDelay = 100;
beforeEach(() => (backOffOptions.startingDelay = startingDelay));
it(`does not delay the first attempt`, () => {
const startTime = Date.now();
const request = initBackOff();
return request.then(() => {
const endTime = Date.now();
const duration = endTime - startTime;
const roundedDuration = Math.round(duration / 100) * 100;
expect(roundedDuration).toBe(0);
});
});
it(`when #backOffOptions.delayFirstAttempt is 'true',
it delays the first attempt`, () => {
backOffOptions.delayFirstAttempt = true;
const startTime = Date.now();
const request = initBackOff();
return request.then(() => {
const endTime = Date.now();
const duration = endTime - startTime;
const roundedDuration = Math.round(duration / 100) * 100;
expect(roundedDuration).toBe(startingDelay);
});
});
});
describe("when request function is a promise that is rejected", () => {
beforeEach(() => (backOffRequest = promiseThatIsRejected()));
it("returns the rejected value", () => {
const request = initBackOff();
return request.catch(err => expect(err).toBe(mockFailResponse));
});
it("retries the request as many times as specified in #BackOffOptions.numOfAttempts", async () => {
const numOfAttemps = 2;
backOffOptions.numOfAttempts = numOfAttemps;
backOffRequest = jest.fn(() => Promise.reject(mockFailResponse));
try {
await initBackOff();
} catch {
expect(backOffRequest).toHaveBeenCalledTimes(numOfAttemps);
}
});
it(`when the #BackOffOptions.retry function is set to always return false,
it only calls request function one time`, async () => {
backOffOptions.retry = () => false;
backOffOptions.numOfAttempts = 2;
backOffRequest = jest.fn(() => Promise.reject(mockFailResponse));
try {
await initBackOff();
} catch {
expect(backOffRequest).toHaveBeenCalledTimes(1);
}
});
});
it("when the #BackOffOptions.retry function returns a promise, it awaits it", async () => {
const retryDuration = 100;
backOffOptions.retry = () =>
new Promise(resolve => setTimeout(() => resolve(true), retryDuration));
backOffRequest = promiseThatFailsOnceThenSucceeds();
const start = Date.now();
await initBackOff();
const end = Date.now();
const duration = end - start;
const roundedDuration =
Math.round(duration / retryDuration) * retryDuration;
expect(roundedDuration).toBe(retryDuration);
});
describe(`when calling #backOff with a function that throws an error the first time, and succeeds the second time`, () => {
beforeEach(
() => (backOffRequest = jest.fn(promiseThatFailsOnceThenSucceeds()))
);
it(`returns a successful response`, () => {
const request = initBackOff();
return request.then(response =>
expect(response).toBe(mockSuccessResponse)
);
});
it("calls the request function two times", async () => {
await initBackOff();
expect(backOffRequest).toHaveBeenCalledTimes(2);
});
it(`when setting the #BackOffOption.timeMultiple to a value,
when setting the #BackOffOption.delayFirstAttempt to true,
it applies a delay between the first and the second call`, async () => {
const startingDelay = 100;
const timeMultiple = 3;
const totalExpectedDelay = startingDelay + timeMultiple * startingDelay;
backOffOptions.startingDelay = startingDelay;
backOffOptions.timeMultiple = timeMultiple;
backOffOptions.delayFirstAttempt = true;
const start = Date.now();
await initBackOff();
const end = Date.now();
const duration = end - start;
const roundedDuration =
Math.round(duration / startingDelay) * startingDelay;
expect(roundedDuration).toBe(totalExpectedDelay);
});
});
});
@@ -0,0 +1 @@
{"version":3,"names":["_usingCtx","_disposeSuppressedError","SuppressedError","error","suppressed","err","Error","name","empty","stack","using","isAwait","value","Object","TypeError","dispose","Symbol","asyncDispose","undefined","inner","call","e","Promise","reject","push","v","d","a","u","bind","state","resource","next","pop","resolve","then","disposalResult"],"sources":["../../src/helpers/usingCtx.ts"],"sourcesContent":["/* @minVersion 7.23.9 */\n\ntype Stack =\n | {\n v: Disposable | AsyncDisposable;\n d: null | undefined | DisposeLike;\n a: boolean;\n }\n | {\n d: null | undefined;\n a: true;\n };\n\ntype DisposeLike = () => void | PromiseLike<void>;\n\ninterface UsingCtxReturn {\n e: object;\n u: (value: Disposable | null | undefined) => Disposable | null | undefined;\n a: (\n value: AsyncDisposable | Disposable | null | undefined,\n ) => AsyncDisposable | Disposable | null | undefined;\n d: DisposeLike;\n}\n\nconst enum StateFlag {\n NONE = 0,\n NEEDS_AWAIT = 1,\n HAS_AWAITED = 2,\n}\n\nexport default function _usingCtx(): UsingCtxReturn {\n var _disposeSuppressedError =\n typeof SuppressedError === \"function\"\n ? SuppressedError\n : (function (error: Error, suppressed: Error) {\n var err = new Error() as SuppressedError;\n err.name = \"SuppressedError\";\n err.error = error;\n err.suppressed = suppressed;\n return err;\n } as SuppressedErrorConstructor),\n empty = {},\n stack: Stack[] = [];\n function using(\n isAwait: true,\n value: AsyncDisposable | Disposable | null | undefined,\n ): AsyncDisposable | Disposable | null | undefined;\n function using(\n isAwait: false,\n value: Disposable | null | undefined,\n ): Disposable | null | undefined;\n function using(\n isAwait: boolean,\n value: AsyncDisposable | Disposable | null | undefined,\n ): AsyncDisposable | Disposable | null | undefined {\n if (value != null) {\n if (Object(value) !== value) {\n throw new TypeError(\n \"using declarations can only be used with objects, functions, null, or undefined.\",\n );\n }\n // core-js-pure uses Symbol.for for polyfilling well-known symbols\n if (isAwait) {\n // value can either be an AsyncDisposable or a Disposable\n // Try AsyncDisposable first\n var dispose: DisposeLike | null | undefined = (\n value as AsyncDisposable\n )[Symbol.asyncDispose || Symbol[\"for\"](\"Symbol.asyncDispose\")];\n }\n if (dispose === undefined) {\n dispose = (value as Disposable)[\n Symbol.dispose || Symbol[\"for\"](\"Symbol.dispose\")\n ];\n if (isAwait) {\n var inner = dispose;\n }\n }\n if (typeof dispose !== \"function\") {\n throw new TypeError(\"Object is not disposable.\");\n }\n // @ts-expect-error use before assignment\n if (inner) {\n dispose = function () {\n try {\n inner.call(value);\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(e);\n }\n };\n }\n stack.push({ v: value, d: dispose, a: isAwait });\n } else if (isAwait) {\n // provide the nullish `value` as `d` for minification gain\n stack.push({ d: value, a: isAwait });\n }\n return value;\n }\n return {\n // error\n e: empty,\n // using\n u: using.bind(null, false),\n // await using\n // full generic signature to avoid type widening\n a: using.bind<\n null,\n [true],\n [AsyncDisposable | Disposable | null | undefined],\n AsyncDisposable | Disposable | null | undefined\n >(null, true),\n // dispose\n d: function () {\n var error = this.e,\n state: StateFlag = StateFlag.NONE,\n resource;\n\n function next(): Promise<void> | void {\n while ((resource = stack.pop())) {\n try {\n if (!resource.a && state === StateFlag.NEEDS_AWAIT) {\n state = StateFlag.NONE;\n stack.push(resource);\n return Promise.resolve().then(next);\n }\n if (resource.d) {\n var disposalResult = resource.d.call(resource.v);\n if (resource.a) {\n state |= StateFlag.HAS_AWAITED;\n return Promise.resolve(disposalResult).then(next, err);\n }\n } else {\n state |= StateFlag.NEEDS_AWAIT;\n }\n } catch (e) {\n return err(e as Error);\n }\n }\n if (state === StateFlag.NEEDS_AWAIT) {\n if (error !== empty) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(error);\n } else {\n return Promise.resolve();\n Line truncated
@@ -0,0 +1,8 @@
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;
@@ -0,0 +1 @@
{"version":3,"file":"indian-rupee.js","sources":["../../../src/icons/indian-rupee.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name IndianRupee\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNiAzaDEyIiAvPgogIDxwYXRoIGQ9Ik02IDhoMTIiIC8+CiAgPHBhdGggZD0ibTYgMTMgOC41IDgiIC8+CiAgPHBhdGggZD0iTTYgMTNoMyIgLz4KICA8cGF0aCBkPSJNOSAxM2M2LjY2NyAwIDYuNjY3LTEwIDAtMTAiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/indian-rupee\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst IndianRupee = createLucideIcon('IndianRupee', [\n ['path', { d: 'M6 3h12', key: 'ggurg9' }],\n ['path', { d: 'M6 8h12', key: '6g4wlu' }],\n ['path', { d: 'm6 13 8.5 8', key: 'u1kupk' }],\n ['path', { d: 'M6 13h3', key: 'wdp6ag' }],\n ['path', { d: 'M9 13c6.667 0 6.667-10 0-10', key: '1nkvk2' }],\n]);\n\nexport default IndianRupee;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAc,iBAAiB,aAAe,CAAA,CAAA,CAAA;AAAA,CAAA,CAClD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAe,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC5C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA+B,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC9D,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,83 @@
isexe:2.0.0 -- The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
which:2.0.2 -- The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
path-key:3.1.1 -- MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
cross-spawn:7.0.6 -- The MIT License (MIT)
Copyright (c) 2018 Made With MOXY Lda <hello@moxy.studio>
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.
shebang-regex:3.0.0 -- MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
shebang-command:2.0.0 -- MIT License
Copyright (c) Kevin Mårtensson <kevinmartensson@gmail.com> (github.com/kevva)
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.