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,8 @@
"use client";
import * as React$1 from "react";
//#region src/routerContext.tsx
var routerContext = React$1.createContext(null);
//#endregion
export { routerContext };
//# sourceMappingURL=routerContext.js.map
@@ -0,0 +1,11 @@
//#region src/utils/compress.ts
/**
* @module
* Constants for compression.
*/
/**
* Match for compressible content type.
*/
const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;
//#endregion
export { COMPRESSIBLE_CONTENT_TYPE_REGEX };
@@ -0,0 +1,13 @@
const animationMaps = new WeakMap();
const animationMapKey = (name, pseudoElement = "") => `${name}:${pseudoElement}`;
function getAnimationMap(element) {
let map = animationMaps.get(element);
if (!map) {
map = new Map();
animationMaps.set(element, map);
}
return map;
}
export { animationMapKey, getAnimationMap };
//# sourceMappingURL=active-animations.mjs.map
@@ -0,0 +1,353 @@
const {
deepNormalizeScriptCov,
normalizeFunctionCov,
normalizeProcessCov,
normalizeRangeTree,
normalizeScriptCov,
} = require("./normalize");
const { RangeTree } = require("./range-tree");
/**
* Merges a list of process coverages.
*
* The result is normalized.
* The input values may be mutated, it is not safe to use them after passing
* them to this function.
* The computation is synchronous.
*
* @param processCovs Process coverages to merge.
* @return Merged process coverage.
*/
function mergeProcessCovs(processCovs) {
if (processCovs.length === 0) {
return { result: [] };
}
const urlToScripts = new Map();
for (const processCov of processCovs) {
for (const scriptCov of processCov.result) {
let scriptCovs = urlToScripts.get(scriptCov.url);
if (scriptCovs === undefined) {
scriptCovs = [];
urlToScripts.set(scriptCov.url, scriptCovs);
}
scriptCovs.push(scriptCov);
}
}
const result = [];
for (const scripts of urlToScripts.values()) {
// assert: `scripts.length > 0`
result.push(mergeScriptCovs(scripts));
}
const merged = { result };
normalizeProcessCov(merged);
return merged;
}
/**
* Merges a list of matching script coverages.
*
* Scripts are matching if they have the same `url`.
* The result is normalized.
* The input values may be mutated, it is not safe to use them after passing
* them to this function.
* The computation is synchronous.
*
* @param scriptCovs Process coverages to merge.
* @return Merged script coverage, or `undefined` if the input list was empty.
*/
function mergeScriptCovs(scriptCovs) {
if (scriptCovs.length === 0) {
return undefined;
} else if (scriptCovs.length === 1) {
const merged = scriptCovs[0];
deepNormalizeScriptCov(merged);
return merged;
}
const first = scriptCovs[0];
const scriptId = first.scriptId;
const url = first.url;
const rangeToFuncs = new Map();
for (const scriptCov of scriptCovs) {
for (const funcCov of scriptCov.functions) {
const rootRange = stringifyFunctionRootRange(funcCov);
let funcCovs = rangeToFuncs.get(rootRange);
if (
funcCovs === undefined ||
// if the entry in rangeToFuncs is function-level granularity and
// the new coverage is block-level, prefer block-level.
(!funcCovs[0].isBlockCoverage && funcCov.isBlockCoverage)
) {
funcCovs = [];
rangeToFuncs.set(rootRange, funcCovs);
} else if (funcCovs[0].isBlockCoverage && !funcCov.isBlockCoverage) {
// if the entry in rangeToFuncs is block-level granularity, we should
// not append function level granularity.
continue;
}
funcCovs.push(funcCov);
}
}
const functions = [];
for (const funcCovs of rangeToFuncs.values()) {
// assert: `funcCovs.length > 0`
functions.push(mergeFunctionCovs(funcCovs));
}
const merged = { scriptId, url, functions };
normalizeScriptCov(merged);
return merged;
}
/**
* Returns a string representation of the root range of the function.
*
* This string can be used to match function with same root range.
* The string is derived from the start and end offsets of the root range of
* the function.
* This assumes that `ranges` is non-empty (true for valid function coverages).
*
* @param funcCov Function coverage with the range to stringify
* @internal
*/
function stringifyFunctionRootRange(funcCov) {
const rootRange = funcCov.ranges[0];
return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`;
}
/**
* Merges a list of matching function coverages.
*
* Functions are matching if their root ranges have the same span.
* The result is normalized.
* The input values may be mutated, it is not safe to use them after passing
* them to this function.
* The computation is synchronous.
*
* @param funcCovs Function coverages to merge.
* @return Merged function coverage, or `undefined` if the input list was empty.
*/
function mergeFunctionCovs(funcCovs) {
if (funcCovs.length === 0) {
return undefined;
} else if (funcCovs.length === 1) {
const merged = funcCovs[0];
normalizeFunctionCov(merged);
return merged;
}
const functionName = funcCovs[0].functionName;
const trees = [];
for (const funcCov of funcCovs) {
// assert: `fn.ranges.length > 0`
// assert: `fn.ranges` is sorted
trees.push(RangeTree.fromSortedRanges(funcCov.ranges));
}
// assert: `trees.length > 0`
const mergedTree = mergeRangeTrees(trees);
normalizeRangeTree(mergedTree);
const ranges = mergedTree.toRanges();
const isBlockCoverage = !(ranges.length === 1 && ranges[0].count === 0);
const merged = { functionName, ranges, isBlockCoverage };
// assert: `merged` is normalized
return merged;
}
/**
* @precondition Same `start` and `end` for all the trees
*/
function mergeRangeTrees(trees) {
if (trees.length <= 1) {
return trees[0];
}
const first = trees[0];
let delta = 0;
for (const tree of trees) {
delta += tree.delta;
}
const children = mergeRangeTreeChildren(trees);
return new RangeTree(first.start, first.end, delta, children);
}
class RangeTreeWithParent {
parentIndex;
tree;
constructor(parentIndex, tree) {
this.parentIndex = parentIndex;
this.tree = tree;
}
}
class StartEvent {
offset;
trees;
constructor(offset, trees) {
this.offset = offset;
this.trees = trees;
}
static compare(a, b) {
return a.offset - b.offset;
}
}
class StartEventQueue {
queue;
nextIndex;
pendingOffset;
pendingTrees;
constructor(queue) {
this.queue = queue;
this.nextIndex = 0;
this.pendingOffset = 0;
this.pendingTrees = undefined;
}
static fromParentTrees(parentTrees) {
const startToTrees = new Map();
for (const [parentIndex, parentTree] of parentTrees.entries()) {
for (const child of parentTree.children) {
let trees = startToTrees.get(child.start);
if (trees === undefined) {
trees = [];
startToTrees.set(child.start, trees);
}
trees.push(new RangeTreeWithParent(parentIndex, child));
}
}
const queue = [];
for (const [startOffset, trees] of startToTrees) {
queue.push(new StartEvent(startOffset, trees));
}
queue.sort(StartEvent.compare);
return new StartEventQueue(queue);
}
setPendingOffset(offset) {
this.pendingOffset = offset;
}
pushPendingTree(tree) {
if (this.pendingTrees === undefined) {
this.pendingTrees = [];
}
this.pendingTrees.push(tree);
}
next() {
const pendingTrees = this.pendingTrees;
const nextEvent = this.queue[this.nextIndex];
if (pendingTrees === undefined) {
this.nextIndex++;
return nextEvent;
} else if (nextEvent === undefined) {
this.pendingTrees = undefined;
return new StartEvent(this.pendingOffset, pendingTrees);
} else {
if (this.pendingOffset < nextEvent.offset) {
this.pendingTrees = undefined;
return new StartEvent(this.pendingOffset, pendingTrees);
} else {
if (this.pendingOffset === nextEvent.offset) {
this.pendingTrees = undefined;
for (const tree of pendingTrees) {
nextEvent.trees.push(tree);
}
}
this.nextIndex++;
return nextEvent;
}
}
}
}
function mergeRangeTreeChildren(parentTrees) {
const result = [];
const startEventQueue = StartEventQueue.fromParentTrees(parentTrees);
const parentToNested = new Map();
let openRange;
while (true) {
const event = startEventQueue.next();
if (event === undefined) {
break;
}
if (openRange !== undefined && openRange.end <= event.offset) {
result.push(nextChild(openRange, parentToNested));
openRange = undefined;
}
if (openRange === undefined) {
let openRangeEnd = event.offset + 1;
for (const { parentIndex, tree } of event.trees) {
openRangeEnd = Math.max(openRangeEnd, tree.end);
insertChild(parentToNested, parentIndex, tree);
}
startEventQueue.setPendingOffset(openRangeEnd);
openRange = { start: event.offset, end: openRangeEnd };
} else {
for (const { parentIndex, tree } of event.trees) {
if (tree.end > openRange.end) {
const right = tree.split(openRange.end);
startEventQueue.pushPendingTree(
new RangeTreeWithParent(parentIndex, right),
);
}
insertChild(parentToNested, parentIndex, tree);
}
}
}
if (openRange !== undefined) {
result.push(nextChild(openRange, parentToNested));
}
return result;
}
function insertChild(parentToNested, parentIndex, tree) {
let nested = parentToNested.get(parentIndex);
if (nested === undefined) {
nested = [];
parentToNested.set(parentIndex, nested);
}
nested.push(tree);
}
function nextChild(openRange, parentToNested) {
const matchingTrees = [];
for (const nested of parentToNested.values()) {
if (
nested.length === 1 &&
nested[0].start === openRange.start &&
nested[0].end === openRange.end
) {
matchingTrees.push(nested[0]);
} else {
matchingTrees.push(
new RangeTree(openRange.start, openRange.end, 0, nested),
);
}
}
parentToNested.clear();
return mergeRangeTrees(matchingTrees);
}
module.exports = {
mergeProcessCovs,
mergeScriptCovs,
mergeFunctionCovs,
};
@@ -0,0 +1,66 @@
import { HistoryAction } from '@tanstack/history';
import { AnyRoute, AnyRouter, ParseRoute, RegisteredRouter } from '@tanstack/router-core';
import * as React from 'react';
type ShouldBlockFnLocation<out TRouteId, out TFullPath, out TAllParams, out TFullSearchSchema> = {
routeId: TRouteId;
fullPath: TFullPath;
pathname: string;
params: TAllParams;
search: TFullSearchSchema;
};
type MakeShouldBlockFnLocationUnion<TRouter extends AnyRouter = RegisteredRouter, TRoute extends AnyRoute = ParseRoute<TRouter['routeTree']>> = TRoute extends any ? ShouldBlockFnLocation<TRoute['id'], TRoute['fullPath'], TRoute['types']['allParams'], TRoute['types']['fullSearchSchema']> : never;
type BlockerResolver<TRouter extends AnyRouter = RegisteredRouter> = {
status: 'blocked';
current: MakeShouldBlockFnLocationUnion<TRouter>;
next: MakeShouldBlockFnLocationUnion<TRouter>;
action: HistoryAction;
proceed: () => void;
reset: () => void;
} | {
status: 'idle';
current: undefined;
next: undefined;
action: undefined;
proceed: undefined;
reset: undefined;
};
type ShouldBlockFnArgs<TRouter extends AnyRouter = RegisteredRouter> = {
current: MakeShouldBlockFnLocationUnion<TRouter>;
next: MakeShouldBlockFnLocationUnion<TRouter>;
action: HistoryAction;
};
export type ShouldBlockFn<TRouter extends AnyRouter = RegisteredRouter> = (args: ShouldBlockFnArgs<TRouter>) => boolean | Promise<boolean>;
export type UseBlockerOpts<TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = boolean> = {
shouldBlockFn: ShouldBlockFn<TRouter>;
enableBeforeUnload?: boolean | (() => boolean);
disabled?: boolean;
withResolver?: TWithResolver;
};
type LegacyBlockerFn = () => Promise<any> | any;
type LegacyBlockerOpts = {
blockerFn?: LegacyBlockerFn;
condition?: boolean | any;
};
export declare function useBlocker<TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = false>(opts: UseBlockerOpts<TRouter, TWithResolver>): TWithResolver extends true ? BlockerResolver<TRouter> : void;
/**
* @deprecated Use the shouldBlockFn property instead
*/
export declare function useBlocker(blockerFnOrOpts?: LegacyBlockerOpts): BlockerResolver;
/**
* @deprecated Use the UseBlockerOpts object syntax instead
*/
export declare function useBlocker(blockerFn?: LegacyBlockerFn, condition?: boolean | any): BlockerResolver;
export declare function Block<TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = boolean>(opts: PromptProps<TRouter, TWithResolver>): React.ReactNode;
/**
* @deprecated Use the UseBlockerOpts property instead
*/
export declare function Block(opts: LegacyPromptProps): React.ReactNode;
type LegacyPromptProps = {
blockerFn?: LegacyBlockerFn;
condition?: boolean | any;
children?: React.ReactNode | ((params: BlockerResolver) => React.ReactNode);
};
type PromptProps<TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = boolean, TParams = TWithResolver extends true ? BlockerResolver<TRouter> : void> = UseBlockerOpts<TRouter, TWithResolver> & {
children?: React.ReactNode | ((params: TParams) => React.ReactNode);
};
export {};
@@ -0,0 +1 @@
export declare const getRelativePath: (pathA: string[], pathB: string[]) => string;
@@ -0,0 +1,79 @@
"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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getParsedConfigFile = getParsedConfigFile;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const compilerOptions_1 = require("./compilerOptions");
/**
* Parses a TSConfig file using the same logic as tsserver.
*
* @param configFile the path to the tsconfig.json file, relative to `projectDirectory`
* @param projectDirectory the project directory to use as the CWD, defaults to `process.cwd()`
*/
function getParsedConfigFile(tsserver, configFile, projectDirectory) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, @typescript-eslint/internal/eqeq-nullish
if (tsserver.sys === undefined) {
throw new Error('`getParsedConfigFile` is only supported in a Node-like environment.');
}
const parsed = tsserver.getParsedCommandLineOfConfigFile(configFile, compilerOptions_1.CORE_COMPILER_OPTIONS, {
fileExists: fs.existsSync,
getCurrentDirectory,
onUnRecoverableConfigFileDiagnostic: diag => {
throw new Error(formatDiagnostics([diag])); // ensures that `parsed` is defined.
},
readDirectory: tsserver.sys.readDirectory,
readFile: file => fs.readFileSync(path.isAbsolute(file) ? file : path.join(getCurrentDirectory(), file), 'utf-8'),
useCaseSensitiveFileNames: tsserver.sys.useCaseSensitiveFileNames,
});
if (parsed?.errors.length) {
throw new Error([
"Unable to parse the specified 'tsconfig' file. Ensure it's correct and has valid syntax.",
formatDiagnostics(parsed.errors),
].join('\n\n'));
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return parsed;
function getCurrentDirectory() {
return projectDirectory ? path.resolve(projectDirectory) : process.cwd();
}
function formatDiagnostics(diagnostics) {
return tsserver.formatDiagnostics(diagnostics, {
getCanonicalFileName: f => f,
getCurrentDirectory,
getNewLine: () => '\n',
});
}
}
@@ -0,0 +1,20 @@
/**
* @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 Move = createLucideIcon("Move", [
["path", { d: "M12 2v20", key: "t6zp3m" }],
["path", { d: "m15 19-3 3-3-3", key: "11eu04" }],
["path", { d: "m19 9 3 3-3 3", key: "1mg7y2" }],
["path", { d: "M2 12h20", key: "9i4pu4" }],
["path", { d: "m5 9-3 3 3 3", key: "j64kie" }],
["path", { d: "m9 5 3-3 3 3", key: "l8vdw6" }]
]);
export { Move as default };
//# sourceMappingURL=move.js.map
@@ -0,0 +1,84 @@
/**
* @license React
* use-sync-external-store-with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
var React = require("react");
function is(x, y) {
return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
var objectIs = "function" === typeof Object.is ? Object.is : is,
useSyncExternalStore = React.useSyncExternalStore,
useRef = React.useRef,
useEffect = React.useEffect,
useMemo = React.useMemo,
useDebugValue = React.useDebugValue;
exports.useSyncExternalStoreWithSelector = function (
subscribe,
getSnapshot,
getServerSnapshot,
selector,
isEqual
) {
var instRef = useRef(null);
if (null === instRef.current) {
var inst = { hasValue: !1, value: null };
instRef.current = inst;
} else inst = instRef.current;
instRef = useMemo(
function () {
function memoizedSelector(nextSnapshot) {
if (!hasMemo) {
hasMemo = !0;
memoizedSnapshot = nextSnapshot;
nextSnapshot = selector(nextSnapshot);
if (void 0 !== isEqual && inst.hasValue) {
var currentSelection = inst.value;
if (isEqual(currentSelection, nextSnapshot))
return (memoizedSelection = currentSelection);
}
return (memoizedSelection = nextSnapshot);
}
currentSelection = memoizedSelection;
if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
var nextSelection = selector(nextSnapshot);
if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
return (memoizedSnapshot = nextSnapshot), currentSelection;
memoizedSnapshot = nextSnapshot;
return (memoizedSelection = nextSelection);
}
var hasMemo = !1,
memoizedSnapshot,
memoizedSelection,
maybeGetServerSnapshot =
void 0 === getServerSnapshot ? null : getServerSnapshot;
return [
function () {
return memoizedSelector(getSnapshot());
},
null === maybeGetServerSnapshot
? void 0
: function () {
return memoizedSelector(maybeGetServerSnapshot());
}
];
},
[getSnapshot, getServerSnapshot, selector, isEqual]
);
var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
useEffect(
function () {
inst.hasValue = !0;
inst.value = value;
},
[value]
);
useDebugValue(value);
return value;
};
@@ -0,0 +1 @@
{"version":3,"file":"refrigerator.js","sources":["../../../src/icons/refrigerator.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Refrigerator\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNSA2YTQgNCAwIDAgMSA0LTRoNmE0IDQgMCAwIDEgNCA0djE0YTIgMiAwIDAgMS0yIDJIN2EyIDIgMCAwIDEtMi0yVjZaIiAvPgogIDxwYXRoIGQ9Ik01IDEwaDE0IiAvPgogIDxwYXRoIGQ9Ik0xNSA3djYiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/refrigerator\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 Refrigerator = createLucideIcon('Refrigerator', [\n [\n 'path',\n { d: 'M5 6a4 4 0 0 1 4-4h6a4 4 0 0 1 4 4v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6Z', key: 'fpq118' },\n ],\n ['path', { d: 'M5 10h14', key: 'elsbfy' }],\n ['path', { d: 'M15 7v6', key: '1nx30x' }],\n]);\n\nexport default Refrigerator;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAe,iBAAiB,cAAgB,CAAA,CAAA,CAAA;AAAA,CACpD,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA,CAAE,CAAA,CAAG,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,CAA0E,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,QAAS,CAAA,CAAA;AAAA,CAC/F,CAAA,CAAA,CAAA;AAAA,CAAA,CACA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,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;AAC1C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"square-plus.js","sources":["../../../src/icons/square-plus.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name SquarePlus\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMTgiIGhlaWdodD0iMTgiIHg9IjMiIHk9IjMiIHJ4PSIyIiAvPgogIDxwYXRoIGQ9Ik04IDEyaDgiIC8+CiAgPHBhdGggZD0iTTEyIDh2OCIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/square-plus\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 SquarePlus = createLucideIcon('SquarePlus', [\n ['rect', { width: '18', height: '18', x: '3', y: '3', rx: '2', key: 'afitv7' }],\n ['path', { d: 'M8 12h8', key: '1wcyev' }],\n ['path', { d: 'M12 8v8', key: 'napkw2' }],\n]);\n\nexport default SquarePlus;\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,CAAA,CAAQ,CAAA,CAAA,CAAE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,MAAM,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAG,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC9E,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;AAC1C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSEnumScope = void 0;
const ScopeBase_1 = require("./ScopeBase");
const ScopeType_1 = require("./ScopeType");
class TSEnumScope extends ScopeBase_1.ScopeBase {
constructor(scopeManager, upperScope, block) {
super(scopeManager, ScopeType_1.ScopeType.tsEnum, upperScope, block, false);
}
}
exports.TSEnumScope = TSEnumScope;
@@ -0,0 +1,43 @@
{
"name": "electron-to-chromium",
"version": "1.5.459",
"description": "Provides a list of electron-to-chromium version mappings",
"main": "index.js",
"files": [
"versions.js",
"full-versions.js",
"chromium-versions.js",
"full-chromium-versions.js",
"versions.json",
"full-versions.json",
"chromium-versions.json",
"full-chromium-versions.json",
"LICENSE"
],
"scripts": {
"build": "node build.mjs",
"update": "node automated-update.js",
"test": "nyc ava --verbose",
"report": "nyc report --reporter=text-lcov > coverage.lcov"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Kilian/electron-to-chromium.git"
},
"keywords": [
"electron",
"chrome",
"chromium",
"browserslist",
"browserlist"
],
"author": "Kilian Valkhof",
"license": "ISC",
"devDependencies": {
"ava": "^7.0.0",
"compare-versions": "^6.1.1",
"node-fetch": "^3.3.2",
"nyc": "^18.0.0",
"shelljs": "^0.10.0"
}
}
@@ -0,0 +1,195 @@
"use client";
import { createMotionComponentWithFeatures } from './create.mjs';
/**
* HTML components
*/
const MotionA = /*@__PURE__*/ createMotionComponentWithFeatures("a");
const MotionAbbr = /*@__PURE__*/ createMotionComponentWithFeatures("abbr");
const MotionAddress = /*@__PURE__*/ createMotionComponentWithFeatures("address");
const MotionArea = /*@__PURE__*/ createMotionComponentWithFeatures("area");
const MotionArticle = /*@__PURE__*/ createMotionComponentWithFeatures("article");
const MotionAside = /*@__PURE__*/ createMotionComponentWithFeatures("aside");
const MotionAudio = /*@__PURE__*/ createMotionComponentWithFeatures("audio");
const MotionB = /*@__PURE__*/ createMotionComponentWithFeatures("b");
const MotionBase = /*@__PURE__*/ createMotionComponentWithFeatures("base");
const MotionBdi = /*@__PURE__*/ createMotionComponentWithFeatures("bdi");
const MotionBdo = /*@__PURE__*/ createMotionComponentWithFeatures("bdo");
const MotionBig = /*@__PURE__*/ createMotionComponentWithFeatures("big");
const MotionBlockquote =
/*@__PURE__*/ createMotionComponentWithFeatures("blockquote");
const MotionBody = /*@__PURE__*/ createMotionComponentWithFeatures("body");
const MotionButton = /*@__PURE__*/ createMotionComponentWithFeatures("button");
const MotionCanvas = /*@__PURE__*/ createMotionComponentWithFeatures("canvas");
const MotionCaption = /*@__PURE__*/ createMotionComponentWithFeatures("caption");
const MotionCite = /*@__PURE__*/ createMotionComponentWithFeatures("cite");
const MotionCode = /*@__PURE__*/ createMotionComponentWithFeatures("code");
const MotionCol = /*@__PURE__*/ createMotionComponentWithFeatures("col");
const MotionColgroup = /*@__PURE__*/ createMotionComponentWithFeatures("colgroup");
const MotionData = /*@__PURE__*/ createMotionComponentWithFeatures("data");
const MotionDatalist = /*@__PURE__*/ createMotionComponentWithFeatures("datalist");
const MotionDd = /*@__PURE__*/ createMotionComponentWithFeatures("dd");
const MotionDel = /*@__PURE__*/ createMotionComponentWithFeatures("del");
const MotionDetails = /*@__PURE__*/ createMotionComponentWithFeatures("details");
const MotionDfn = /*@__PURE__*/ createMotionComponentWithFeatures("dfn");
const MotionDialog = /*@__PURE__*/ createMotionComponentWithFeatures("dialog");
const MotionDiv = /*@__PURE__*/ createMotionComponentWithFeatures("div");
const MotionDl = /*@__PURE__*/ createMotionComponentWithFeatures("dl");
const MotionDt = /*@__PURE__*/ createMotionComponentWithFeatures("dt");
const MotionEm = /*@__PURE__*/ createMotionComponentWithFeatures("em");
const MotionEmbed = /*@__PURE__*/ createMotionComponentWithFeatures("embed");
const MotionFieldset = /*@__PURE__*/ createMotionComponentWithFeatures("fieldset");
const MotionFigcaption =
/*@__PURE__*/ createMotionComponentWithFeatures("figcaption");
const MotionFigure = /*@__PURE__*/ createMotionComponentWithFeatures("figure");
const MotionFooter = /*@__PURE__*/ createMotionComponentWithFeatures("footer");
const MotionForm = /*@__PURE__*/ createMotionComponentWithFeatures("form");
const MotionH1 = /*@__PURE__*/ createMotionComponentWithFeatures("h1");
const MotionH2 = /*@__PURE__*/ createMotionComponentWithFeatures("h2");
const MotionH3 = /*@__PURE__*/ createMotionComponentWithFeatures("h3");
const MotionH4 = /*@__PURE__*/ createMotionComponentWithFeatures("h4");
const MotionH5 = /*@__PURE__*/ createMotionComponentWithFeatures("h5");
const MotionH6 = /*@__PURE__*/ createMotionComponentWithFeatures("h6");
const MotionHead = /*@__PURE__*/ createMotionComponentWithFeatures("head");
const MotionHeader = /*@__PURE__*/ createMotionComponentWithFeatures("header");
const MotionHgroup = /*@__PURE__*/ createMotionComponentWithFeatures("hgroup");
const MotionHr = /*@__PURE__*/ createMotionComponentWithFeatures("hr");
const MotionHtml = /*@__PURE__*/ createMotionComponentWithFeatures("html");
const MotionI = /*@__PURE__*/ createMotionComponentWithFeatures("i");
const MotionIframe = /*@__PURE__*/ createMotionComponentWithFeatures("iframe");
const MotionImg = /*@__PURE__*/ createMotionComponentWithFeatures("img");
const MotionInput = /*@__PURE__*/ createMotionComponentWithFeatures("input");
const MotionIns = /*@__PURE__*/ createMotionComponentWithFeatures("ins");
const MotionKbd = /*@__PURE__*/ createMotionComponentWithFeatures("kbd");
const MotionKeygen = /*@__PURE__*/ createMotionComponentWithFeatures("keygen");
const MotionLabel = /*@__PURE__*/ createMotionComponentWithFeatures("label");
const MotionLegend = /*@__PURE__*/ createMotionComponentWithFeatures("legend");
const MotionLi = /*@__PURE__*/ createMotionComponentWithFeatures("li");
const MotionLink = /*@__PURE__*/ createMotionComponentWithFeatures("link");
const MotionMain = /*@__PURE__*/ createMotionComponentWithFeatures("main");
const MotionMap = /*@__PURE__*/ createMotionComponentWithFeatures("map");
const MotionMark = /*@__PURE__*/ createMotionComponentWithFeatures("mark");
const MotionMenu = /*@__PURE__*/ createMotionComponentWithFeatures("menu");
const MotionMenuitem = /*@__PURE__*/ createMotionComponentWithFeatures("menuitem");
const MotionMeter = /*@__PURE__*/ createMotionComponentWithFeatures("meter");
const MotionNav = /*@__PURE__*/ createMotionComponentWithFeatures("nav");
const MotionObject = /*@__PURE__*/ createMotionComponentWithFeatures("object");
const MotionOl = /*@__PURE__*/ createMotionComponentWithFeatures("ol");
const MotionOptgroup = /*@__PURE__*/ createMotionComponentWithFeatures("optgroup");
const MotionOption = /*@__PURE__*/ createMotionComponentWithFeatures("option");
const MotionOutput = /*@__PURE__*/ createMotionComponentWithFeatures("output");
const MotionP = /*@__PURE__*/ createMotionComponentWithFeatures("p");
const MotionParam = /*@__PURE__*/ createMotionComponentWithFeatures("param");
const MotionPicture = /*@__PURE__*/ createMotionComponentWithFeatures("picture");
const MotionPre = /*@__PURE__*/ createMotionComponentWithFeatures("pre");
const MotionProgress = /*@__PURE__*/ createMotionComponentWithFeatures("progress");
const MotionQ = /*@__PURE__*/ createMotionComponentWithFeatures("q");
const MotionRp = /*@__PURE__*/ createMotionComponentWithFeatures("rp");
const MotionRt = /*@__PURE__*/ createMotionComponentWithFeatures("rt");
const MotionRuby = /*@__PURE__*/ createMotionComponentWithFeatures("ruby");
const MotionS = /*@__PURE__*/ createMotionComponentWithFeatures("s");
const MotionSamp = /*@__PURE__*/ createMotionComponentWithFeatures("samp");
const MotionScript = /*@__PURE__*/ createMotionComponentWithFeatures("script");
const MotionSection = /*@__PURE__*/ createMotionComponentWithFeatures("section");
const MotionSelect = /*@__PURE__*/ createMotionComponentWithFeatures("select");
const MotionSmall = /*@__PURE__*/ createMotionComponentWithFeatures("small");
const MotionSource = /*@__PURE__*/ createMotionComponentWithFeatures("source");
const MotionSpan = /*@__PURE__*/ createMotionComponentWithFeatures("span");
const MotionStrong = /*@__PURE__*/ createMotionComponentWithFeatures("strong");
const MotionStyle = /*@__PURE__*/ createMotionComponentWithFeatures("style");
const MotionSub = /*@__PURE__*/ createMotionComponentWithFeatures("sub");
const MotionSummary = /*@__PURE__*/ createMotionComponentWithFeatures("summary");
const MotionSup = /*@__PURE__*/ createMotionComponentWithFeatures("sup");
const MotionTable = /*@__PURE__*/ createMotionComponentWithFeatures("table");
const MotionTbody = /*@__PURE__*/ createMotionComponentWithFeatures("tbody");
const MotionTd = /*@__PURE__*/ createMotionComponentWithFeatures("td");
const MotionTextarea = /*@__PURE__*/ createMotionComponentWithFeatures("textarea");
const MotionTfoot = /*@__PURE__*/ createMotionComponentWithFeatures("tfoot");
const MotionTh = /*@__PURE__*/ createMotionComponentWithFeatures("th");
const MotionThead = /*@__PURE__*/ createMotionComponentWithFeatures("thead");
const MotionTime = /*@__PURE__*/ createMotionComponentWithFeatures("time");
const MotionTitle = /*@__PURE__*/ createMotionComponentWithFeatures("title");
const MotionTr = /*@__PURE__*/ createMotionComponentWithFeatures("tr");
const MotionTrack = /*@__PURE__*/ createMotionComponentWithFeatures("track");
const MotionU = /*@__PURE__*/ createMotionComponentWithFeatures("u");
const MotionUl = /*@__PURE__*/ createMotionComponentWithFeatures("ul");
const MotionVideo = /*@__PURE__*/ createMotionComponentWithFeatures("video");
const MotionWbr = /*@__PURE__*/ createMotionComponentWithFeatures("wbr");
const MotionWebview = /*@__PURE__*/ createMotionComponentWithFeatures("webview");
/**
* SVG components
*/
const MotionAnimate = /*@__PURE__*/ createMotionComponentWithFeatures("animate");
const MotionCircle = /*@__PURE__*/ createMotionComponentWithFeatures("circle");
const MotionDefs = /*@__PURE__*/ createMotionComponentWithFeatures("defs");
const MotionDesc = /*@__PURE__*/ createMotionComponentWithFeatures("desc");
const MotionEllipse = /*@__PURE__*/ createMotionComponentWithFeatures("ellipse");
const MotionG = /*@__PURE__*/ createMotionComponentWithFeatures("g");
const MotionImage = /*@__PURE__*/ createMotionComponentWithFeatures("image");
const MotionLine = /*@__PURE__*/ createMotionComponentWithFeatures("line");
const MotionFilter = /*@__PURE__*/ createMotionComponentWithFeatures("filter");
const MotionMarker = /*@__PURE__*/ createMotionComponentWithFeatures("marker");
const MotionMask = /*@__PURE__*/ createMotionComponentWithFeatures("mask");
const MotionMetadata = /*@__PURE__*/ createMotionComponentWithFeatures("metadata");
const MotionPath = /*@__PURE__*/ createMotionComponentWithFeatures("path");
const MotionPattern = /*@__PURE__*/ createMotionComponentWithFeatures("pattern");
const MotionPolygon = /*@__PURE__*/ createMotionComponentWithFeatures("polygon");
const MotionPolyline = /*@__PURE__*/ createMotionComponentWithFeatures("polyline");
const MotionRect = /*@__PURE__*/ createMotionComponentWithFeatures("rect");
const MotionStop = /*@__PURE__*/ createMotionComponentWithFeatures("stop");
const MotionSvg = /*@__PURE__*/ createMotionComponentWithFeatures("svg");
const MotionSymbol = /*@__PURE__*/ createMotionComponentWithFeatures("symbol");
const MotionText = /*@__PURE__*/ createMotionComponentWithFeatures("text");
const MotionTspan = /*@__PURE__*/ createMotionComponentWithFeatures("tspan");
const MotionUse = /*@__PURE__*/ createMotionComponentWithFeatures("use");
const MotionView = /*@__PURE__*/ createMotionComponentWithFeatures("view");
const MotionClipPath = /*@__PURE__*/ createMotionComponentWithFeatures("clipPath");
const MotionFeBlend = /*@__PURE__*/ createMotionComponentWithFeatures("feBlend");
const MotionFeColorMatrix =
/*@__PURE__*/ createMotionComponentWithFeatures("feColorMatrix");
const MotionFeComponentTransfer = /*@__PURE__*/ createMotionComponentWithFeatures("feComponentTransfer");
const MotionFeComposite =
/*@__PURE__*/ createMotionComponentWithFeatures("feComposite");
const MotionFeConvolveMatrix =
/*@__PURE__*/ createMotionComponentWithFeatures("feConvolveMatrix");
const MotionFeDiffuseLighting =
/*@__PURE__*/ createMotionComponentWithFeatures("feDiffuseLighting");
const MotionFeDisplacementMap =
/*@__PURE__*/ createMotionComponentWithFeatures("feDisplacementMap");
const MotionFeDistantLight =
/*@__PURE__*/ createMotionComponentWithFeatures("feDistantLight");
const MotionFeDropShadow =
/*@__PURE__*/ createMotionComponentWithFeatures("feDropShadow");
const MotionFeFlood = /*@__PURE__*/ createMotionComponentWithFeatures("feFlood");
const MotionFeFuncA = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncA");
const MotionFeFuncB = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncB");
const MotionFeFuncG = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncG");
const MotionFeFuncR = /*@__PURE__*/ createMotionComponentWithFeatures("feFuncR");
const MotionFeGaussianBlur =
/*@__PURE__*/ createMotionComponentWithFeatures("feGaussianBlur");
const MotionFeImage = /*@__PURE__*/ createMotionComponentWithFeatures("feImage");
const MotionFeMerge = /*@__PURE__*/ createMotionComponentWithFeatures("feMerge");
const MotionFeMergeNode =
/*@__PURE__*/ createMotionComponentWithFeatures("feMergeNode");
const MotionFeMorphology =
/*@__PURE__*/ createMotionComponentWithFeatures("feMorphology");
const MotionFeOffset = /*@__PURE__*/ createMotionComponentWithFeatures("feOffset");
const MotionFePointLight =
/*@__PURE__*/ createMotionComponentWithFeatures("fePointLight");
const MotionFeSpecularLighting =
/*@__PURE__*/ createMotionComponentWithFeatures("feSpecularLighting");
const MotionFeSpotLight =
/*@__PURE__*/ createMotionComponentWithFeatures("feSpotLight");
const MotionFeTile = /*@__PURE__*/ createMotionComponentWithFeatures("feTile");
const MotionFeTurbulence =
/*@__PURE__*/ createMotionComponentWithFeatures("feTurbulence");
const MotionForeignObject =
/*@__PURE__*/ createMotionComponentWithFeatures("foreignObject");
const MotionLinearGradient =
/*@__PURE__*/ createMotionComponentWithFeatures("linearGradient");
const MotionRadialGradient =
/*@__PURE__*/ createMotionComponentWithFeatures("radialGradient");
const MotionTextPath = /*@__PURE__*/ createMotionComponentWithFeatures("textPath");
export { MotionA, MotionAbbr, MotionAddress, MotionAnimate, MotionArea, MotionArticle, MotionAside, MotionAudio, MotionB, MotionBase, MotionBdi, MotionBdo, MotionBig, MotionBlockquote, MotionBody, MotionButton, MotionCanvas, MotionCaption, MotionCircle, MotionCite, MotionClipPath, MotionCode, MotionCol, MotionColgroup, MotionData, MotionDatalist, MotionDd, MotionDefs, MotionDel, MotionDesc, MotionDetails, MotionDfn, MotionDialog, MotionDiv, MotionDl, MotionDt, MotionEllipse, MotionEm, MotionEmbed, MotionFeBlend, MotionFeColorMatrix, MotionFeComponentTransfer, MotionFeComposite, MotionFeConvolveMatrix, MotionFeDiffuseLighting, MotionFeDisplacementMap, MotionFeDistantLight, MotionFeDropShadow, MotionFeFlood, MotionFeFuncA, MotionFeFuncB, MotionFeFuncG, MotionFeFuncR, MotionFeGaussianBlur, MotionFeImage, MotionFeMerge, MotionFeMergeNode, MotionFeMorphology, MotionFeOffset, MotionFePointLight, MotionFeSpecularLighting, MotionFeSpotLight, MotionFeTile, MotionFeTurbulence, MotionFieldset, MotionFigcaption, MotionFigure, MotionFilter, MotionFooter, MotionForeignObject, MotionForm, MotionG, MotionH1, MotionH2, MotionH3, MotionH4, MotionH5, MotionH6, MotionHead, MotionHeader, MotionHgroup, MotionHr, MotionHtml, MotionI, MotionIframe, MotionImage, MotionImg, MotionInput, MotionIns, MotionKbd, MotionKeygen, MotionLabel, MotionLegend, MotionLi, MotionLine, MotionLinearGradient, MotionLink, MotionMain, MotionMap, MotionMark, MotionMarker, MotionMask, MotionMenu, MotionMenuitem, MotionMetadata, MotionMeter, MotionNav, MotionObject, MotionOl, MotionOptgroup, MotionOption, MotionOutput, MotionP, MotionParam, MotionPath, MotionPattern, MotionPicture, MotionPolygon, MotionPolyline, MotionPre, MotionProgress, MotionQ, MotionRadialGradient, MotionRect, MotionRp, MotionRt, MotionRuby, MotionS, MotionSamp, MotionScript, MotionSection, MotionSelect, MotionSmall, MotionSource, MotionSpan, MotionStop, MotionStrong, MotionStyle, MotionSub, MotionSummary, MotionSup, MotionSvg, MotionSymbol, MotionTable, MotionTbody, MotionTd, MotionText, MotionTextPath, MotionTextarea, MotionTfoot, MotionTh, MotionThead, MotionTime, MotionTitle, MotionTr, MotionTrack, MotionTspan, MotionU, MotionUl, MotionUse, MotionVideo, MotionView, MotionWbr, MotionWebview };
//# sourceMappingURL=elements.mjs.map
@@ -0,0 +1,296 @@
let seroval = require("seroval");
//#region src/ssr/serializer/RawStream.ts
/**
* Marker class for ReadableStream<Uint8Array> that should be serialized
* with base64 encoding (SSR) or binary framing (server functions).
*
* Wrap your binary streams with this to get efficient serialization:
* ```ts
* // For binary data (files, images, etc.)
* return { data: new RawStream(file.stream()) }
*
* // For text-heavy data (RSC payloads, etc.)
* return { data: new RawStream(rscStream, { hint: 'text' }) }
* ```
*/
var RawStream = class {
constructor(stream, options) {
this.stream = stream;
this.hint = options?.hint ?? "binary";
}
};
const BufferCtor = globalThis.Buffer;
const hasNodeBuffer = !!BufferCtor && typeof BufferCtor.from === "function";
function uint8ArrayToBase64(bytes) {
if (bytes.length === 0) return "";
if (hasNodeBuffer) return BufferCtor.from(bytes).toString("base64");
const CHUNK_SIZE = 32768;
const chunks = [];
for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
const chunk = bytes.subarray(i, i + CHUNK_SIZE);
chunks.push(String.fromCharCode.apply(null, chunk));
}
return btoa(chunks.join(""));
}
function base64ToUint8Array(base64) {
if (base64.length === 0) return new Uint8Array(0);
if (hasNodeBuffer) {
const buf = BufferCtor.from(base64, "base64");
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
}
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
const RAW_STREAM_FACTORY_BINARY = Object.create(null);
const RAW_STREAM_FACTORY_TEXT = Object.create(null);
const RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY = (stream) => new ReadableStream({ start(controller) {
stream.on({
next(base64) {
try {
controller.enqueue(base64ToUint8Array(base64));
} catch {}
},
throw(error) {
controller.error(error);
},
return() {
try {
controller.close();
} catch {}
}
});
} });
const textEncoderForFactory = new TextEncoder();
const RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT = (stream) => {
return new ReadableStream({ start(controller) {
stream.on({
next(value) {
try {
if (typeof value === "string") controller.enqueue(textEncoderForFactory.encode(value));
else controller.enqueue(base64ToUint8Array(value.$b64));
} catch {}
},
throw(error) {
controller.error(error);
},
return() {
try {
controller.close();
} catch {}
}
});
} });
};
const FACTORY_BINARY = `(s=>new ReadableStream({start(c){s.on({next(b){try{const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}catch(_){}},throw(e){c.error(e)},return(){try{c.close()}catch(_){}}})}}))`;
const FACTORY_TEXT = `(s=>{const e=new TextEncoder();return new ReadableStream({start(c){s.on({next(v){try{if(typeof v==='string'){c.enqueue(e.encode(v))}else{const d=atob(v.$b64),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}}catch(_){}},throw(x){c.error(x)},return(){try{c.close()}catch(_){}}})}})})`;
function toBinaryStream(readable) {
const stream = (0, seroval.createStream)();
const reader = readable.getReader();
(async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
stream.return(void 0);
break;
}
stream.next(uint8ArrayToBase64(value));
}
} catch (error) {
stream.throw(error);
} finally {
reader.releaseLock();
}
})();
return stream;
}
function toTextStream(readable) {
const stream = (0, seroval.createStream)();
const reader = readable.getReader();
const decoder = new TextDecoder("utf-8", { fatal: true });
(async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
try {
const remaining = decoder.decode();
if (remaining.length > 0) stream.next(remaining);
} catch {}
stream.return(void 0);
break;
}
try {
const text = decoder.decode(value, { stream: true });
if (text.length > 0) stream.next(text);
} catch {
stream.next({ $b64: uint8ArrayToBase64(value) });
}
}
} catch (error) {
stream.throw(error);
} finally {
reader.releaseLock();
}
})();
return stream;
}
const RawStreamFactoryBinaryPlugin = /* @__PURE__ */ (0, seroval.createPlugin)({
tag: "tss/RawStreamFactory",
test(value) {
return value === RAW_STREAM_FACTORY_BINARY;
},
parse: {
sync(_value, _ctx, _data) {
return {};
},
async async(_value, _ctx, _data) {
return {};
},
stream(_value, _ctx, _data) {
return {};
}
},
serialize(_node, _ctx, _data) {
return FACTORY_BINARY;
},
deserialize(_node, _ctx, _data) {
return RAW_STREAM_FACTORY_BINARY;
}
});
const RawStreamFactoryTextPlugin = /* @__PURE__ */ (0, seroval.createPlugin)({
tag: "tss/RawStreamFactoryText",
test(value) {
return value === RAW_STREAM_FACTORY_TEXT;
},
parse: {
sync(_value, _ctx, _data) {
return {};
},
async async(_value, _ctx, _data) {
return {};
},
stream(_value, _ctx, _data) {
return {};
}
},
serialize(_node, _ctx, _data) {
return FACTORY_TEXT;
},
deserialize(_node, _ctx, _data) {
return RAW_STREAM_FACTORY_TEXT;
}
});
/**
* SSR Plugin - uses base64 or UTF-8+base64 encoding for chunks, delegates to seroval's stream mechanism.
* Used during SSR when serializing to JavaScript code for HTML injection.
*
* Supports two modes based on RawStream hint:
* - 'binary': Always base64 encode (default)
* - 'text': Try UTF-8 first, fallback to base64 for invalid UTF-8
*/
const RawStreamSSRPlugin = /* @__PURE__ */ (0, seroval.createPlugin)({
tag: "tss/RawStream",
extends: [RawStreamFactoryBinaryPlugin, RawStreamFactoryTextPlugin],
test(value) {
return value instanceof RawStream;
},
parse: {
sync(value, ctx, _data) {
const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
return {
hint: ctx.parse(value.hint),
factory: ctx.parse(factory),
stream: ctx.parse((0, seroval.createStream)())
};
},
async async(value, ctx, _data) {
const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
const encodedStream = value.hint === "text" ? toTextStream(value.stream) : toBinaryStream(value.stream);
return {
hint: await ctx.parse(value.hint),
factory: await ctx.parse(factory),
stream: await ctx.parse(encodedStream)
};
},
stream(value, ctx, _data) {
const factory = value.hint === "text" ? RAW_STREAM_FACTORY_TEXT : RAW_STREAM_FACTORY_BINARY;
const encodedStream = value.hint === "text" ? toTextStream(value.stream) : toBinaryStream(value.stream);
return {
hint: ctx.parse(value.hint),
factory: ctx.parse(factory),
stream: ctx.parse(encodedStream)
};
}
},
serialize(node, ctx, _data) {
return "(" + ctx.serialize(node.factory) + ")(" + ctx.serialize(node.stream) + ")";
},
deserialize(node, ctx, _data) {
const stream = ctx.deserialize(node.stream);
return ctx.deserialize(node.hint) === "text" ? RAW_STREAM_FACTORY_CONSTRUCTOR_TEXT(stream) : RAW_STREAM_FACTORY_CONSTRUCTOR_BINARY(stream);
}
});
/**
* Creates an RPC plugin instance that registers raw streams with a multiplexer.
* Used for server function responses where we want binary framing.
* Note: RPC always uses binary framing regardless of hint.
*
* @param onRawStream Callback invoked when a RawStream is encountered during serialization
*/
/* @__NO_SIDE_EFFECTS__ */
function createRawStreamRPCPlugin(onRawStream) {
let nextStreamId = 1;
return /* @__PURE__ */ (0, seroval.createPlugin)({
tag: "tss/RawStream",
test(value) {
return value instanceof RawStream;
},
parse: {
async async(value, ctx, _data) {
const streamId = nextStreamId++;
onRawStream(streamId, value.stream);
return { streamId: await ctx.parse(streamId) };
},
stream(value, ctx, _data) {
const streamId = nextStreamId++;
onRawStream(streamId, value.stream);
return { streamId: ctx.parse(streamId) };
}
},
serialize() {
throw new Error("RawStreamRPCPlugin.serialize should not be called. RPC uses JSON serialization, not JS code generation.");
},
deserialize() {
throw new Error("RawStreamRPCPlugin.deserialize should not be called. Use createRawStreamDeserializePlugin on client.");
}
});
}
/**
* Creates a deserialize-only plugin for client-side stream reconstruction.
* Used in serverFnFetcher to wire up streams from frame decoder.
*
* @param getOrCreateStream Function to get/create a stream by ID from frame decoder
*/
function createRawStreamDeserializePlugin(getOrCreateStream) {
return /* @__PURE__ */ (0, seroval.createPlugin)({
tag: "tss/RawStream",
test: () => false,
parse: {},
serialize() {
throw new Error("RawStreamDeserializePlugin.serialize should not be called. Client only deserializes.");
},
deserialize(node, ctx, _data) {
return getOrCreateStream(typeof ctx?.deserialize === "function" ? ctx.deserialize(node.streamId) : node.streamId);
}
});
}
//#endregion
exports.RawStream = RawStream;
exports.RawStreamSSRPlugin = RawStreamSSRPlugin;
exports.createRawStreamDeserializePlugin = createRawStreamDeserializePlugin;
exports.createRawStreamRPCPlugin = createRawStreamRPCPlugin;
//# sourceMappingURL=RawStream.cjs.map
@@ -0,0 +1,8 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_constants = require('../constants-BXAKTxRC.cjs');
//#region src/utils/response.ts
const RESPONSE_ALREADY_SENT = new Response(null, { headers: { [require_constants.X_ALREADY_SENT]: "true" } });
//#endregion
exports.RESPONSE_ALREADY_SENT = RESPONSE_ALREADY_SENT;
@@ -0,0 +1 @@
{"version":3,"file":"is-browser-color.mjs","sources":["../../../../../src/animation/waapi/utils/is-browser-color.ts"],"sourcesContent":["const browserColorFunctions =\n /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\\(/\n\nexport function hasBrowserOnlyColors(keyframes: any[]): boolean {\n for (let i = 0; i < keyframes.length; i++) {\n if (\n typeof keyframes[i] === \"string\" &&\n browserColorFunctions.test(keyframes[i])\n ) {\n return true\n }\n }\n return false\n}\n"],"names":[],"mappings":"AAAA,MAAM,qBAAqB,GACvB,uDAAuD;AAErD,SAAU,oBAAoB,CAAC,SAAgB,EAAA;AACjD,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACvC,QAAA,IACI,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,QAAQ;YAChC,qBAAqB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAC1C;AACE,YAAA,OAAO,IAAI;QACf;IACJ;AACA,IAAA,OAAO,KAAK;AAChB;;;;"}
@@ -0,0 +1,68 @@
import { digest } from '../lib/helpers.js';
import { encode as b64u } from '../util/base64url.js';
import { JOSENotSupported, JWKInvalid } from '../util/errors.js';
import { encode } from '../lib/buffer_utils.js';
import { isKeyLike } from '../lib/is_key_like.js';
import { isJWK } from '../lib/type_checks.js';
import { exportJWK } from '../key/export.js';
import { invalidKeyInput } from '../lib/invalid_key_input.js';
const check = (value, description) => {
if (typeof value !== 'string' || !value) {
throw new JWKInvalid(`${description} missing or invalid`);
}
};
export async function calculateJwkThumbprint(key, digestAlgorithm) {
let jwk;
if (isJWK(key)) {
jwk = key;
}
else if (isKeyLike(key)) {
jwk = await exportJWK(key);
}
else {
throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
}
digestAlgorithm ??= 'sha256';
if (digestAlgorithm !== 'sha256' &&
digestAlgorithm !== 'sha384' &&
digestAlgorithm !== 'sha512') {
throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
}
let components;
switch (jwk.kty) {
case 'AKP':
check(jwk.alg, '"alg" (Algorithm) Parameter');
check(jwk.pub, '"pub" (Public key) Parameter');
components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
break;
case 'EC':
check(jwk.crv, '"crv" (Curve) Parameter');
check(jwk.x, '"x" (X Coordinate) Parameter');
check(jwk.y, '"y" (Y Coordinate) Parameter');
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
break;
case 'OKP':
check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
check(jwk.x, '"x" (Public Key) Parameter');
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
break;
case 'RSA':
check(jwk.e, '"e" (Exponent) Parameter');
check(jwk.n, '"n" (Modulus) Parameter');
components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
break;
case 'oct':
check(jwk.k, '"k" (Key Value) Parameter');
components = { k: jwk.k, kty: jwk.kty };
break;
default:
throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
}
const data = encode(JSON.stringify(components));
return b64u(await digest(digestAlgorithm, data));
}
export async function calculateJwkThumbprintUri(key, digestAlgorithm) {
digestAlgorithm ??= 'sha256';
const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
}
@@ -0,0 +1,165 @@
/**
* @fileoverview Rule to enforce var declarations are only at the top of a function.
* @author Danny Fritz
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Require `var` declarations be placed at the top of their containing scope",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/vars-on-top",
},
schema: [],
messages: {
top: "All 'var' declarations must be at the top of the function scope.",
},
},
create(context) {
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Has AST suggesting a directive.
* @param {ASTNode} node any node
* @returns {boolean} whether the given node structurally represents a directive
*/
function looksLikeDirective(node) {
return (
node.type === "ExpressionStatement" &&
node.expression.type === "Literal" &&
typeof node.expression.value === "string"
);
}
/**
* Check to see if its a ES6 import declaration
* @param {ASTNode} node any node
* @returns {boolean} whether the given node represents a import declaration
*/
function looksLikeImport(node) {
return (
node.type === "ImportDeclaration" ||
node.type === "ImportSpecifier" ||
node.type === "ImportDefaultSpecifier" ||
node.type === "ImportNamespaceSpecifier"
);
}
/**
* Checks whether a given node is a variable declaration or not.
* @param {ASTNode} node any node
* @returns {boolean} `true` if the node is a variable declaration.
*/
function isVariableDeclaration(node) {
return (
node.type === "VariableDeclaration" ||
(node.type === "ExportNamedDeclaration" &&
node.declaration &&
node.declaration.type === "VariableDeclaration")
);
}
/**
* Checks whether this variable is on top of the block body
* @param {ASTNode} node The node to check
* @param {ASTNode[]} statements collection of ASTNodes for the parent node block
* @returns {boolean} True if var is on top otherwise false
*/
function isVarOnTop(node, statements) {
const l = statements.length;
let i = 0;
// Skip over directives and imports. Static blocks don't have either.
if (node.parent.type !== "StaticBlock") {
for (; i < l; ++i) {
if (
!looksLikeDirective(statements[i]) &&
!looksLikeImport(statements[i])
) {
break;
}
}
}
for (; i < l; ++i) {
if (!isVariableDeclaration(statements[i])) {
return false;
}
if (statements[i] === node) {
return true;
}
}
return false;
}
/**
* Checks whether variable is on top at the global level
* @param {ASTNode} node The node to check
* @param {ASTNode} parent Parent of the node
* @returns {void}
*/
function globalVarCheck(node, parent) {
if (!isVarOnTop(node, parent.body)) {
context.report({ node, messageId: "top" });
}
}
/**
* Checks whether variable is on top at functional block scope level
* @param {ASTNode} node The node to check
* @returns {void}
*/
function blockScopeVarCheck(node) {
const { parent } = node;
if (
parent.type === "BlockStatement" &&
/Function/u.test(parent.parent.type) &&
isVarOnTop(node, parent.body)
) {
return;
}
if (
parent.type === "StaticBlock" &&
isVarOnTop(node, parent.body)
) {
return;
}
context.report({ node, messageId: "top" });
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
"VariableDeclaration[kind='var']"(node) {
if (node.parent.type === "ExportNamedDeclaration") {
globalVarCheck(node.parent, node.parent.parent);
} else if (node.parent.type === "Program") {
globalVarCheck(node, node.parent);
} else {
blockScopeVarCheck(node);
}
},
};
},
};
@@ -0,0 +1,503 @@
'use strict';
var getSideChannel = require('side-channel');
var utils = require('./utils');
var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;
var getPrototypeOf = Object.getPrototypeOf;
var isPlainContainer = function isPlainContainer(value) {
if (!value || typeof value !== 'object') {
return false;
}
if (isArray(value)) {
return true;
}
var proto = getPrototypeOf(value);
return proto === Object.prototype || proto === null;
};
var emptyCopyOf = function emptyCopyOf(value) {
if (isArray(value)) {
var arr = [];
arr.length = value.length;
return arr;
}
return getPrototypeOf(value) === null ? { __proto__: null } : {};
};
// `merge` and `compact` modify the containers they are given, so copy the caller's arrays and plain objects first
var copyInput = function copyInput(input) {
var copies = getSideChannel();
var result = {};
var queue = [{ source: input, target: result }];
for (var i = 0; i < queue.length; ++i) {
var source = queue[i].source;
var target = queue[i].target;
var keys = Object.keys(source);
for (var j = 0; j < keys.length; ++j) {
var value = source[keys[j]];
if (isPlainContainer(value)) {
if (!copies.has(value)) {
var copy = emptyCopyOf(value);
copies.set(value, copy);
queue[queue.length] = { source: value, target: copy };
}
target[keys[j]] = copies.get(value);
} else {
target[keys[j]] = value;
}
}
}
return result;
};
var defaults = {
allowDots: false,
allowEmptyArrays: false,
allowPrototypes: false,
allowSparse: false,
arrayLimit: 20,
charset: 'utf-8',
charsetSentinel: false,
comma: false,
decodeDotInKeys: false,
decoder: utils.decode,
delimiter: '&',
depth: 5,
duplicates: 'combine',
ignoreQueryPrefix: false,
interpretNumericEntities: false,
parameterLimit: 1000,
parseArrays: true,
plainObjects: false,
strictDepth: false,
strictMerge: true,
strictNullHandling: false,
throwOnLimitExceeded: false
};
var interpretNumericEntities = function (str) {
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};
var parseArrayValue = function (val, options, currentArrayLength) {
if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
if (options.throwOnLimitExceeded) {
var commaCount = 0;
var commaIndex = val.indexOf(',');
while (commaIndex > -1) {
commaCount += 1;
if (commaCount >= options.arrayLimit) {
throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
}
commaIndex = val.indexOf(',', commaIndex + 1);
}
}
return val.split(',');
}
if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) {
throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
}
return val;
};
// This is what browsers will submit when the ✓ character occurs in an
// application/x-www-form-urlencoded body and the encoding of the page containing
// the form is iso-8859-1, or when the submitted form has an accept-charset
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
// the ✓ character, such as us-ascii.
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')
// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
var parseValues = function parseQueryStringValues(str, options) {
var obj = { __proto__: null };
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']');
var limit = options.parameterLimit === Infinity ? void undefined : options.parameterLimit;
var parts = cleanStr.split(
options.delimiter,
options.throwOnLimitExceeded && typeof limit !== 'undefined' ? limit + 1 : limit
);
if (options.throwOnLimitExceeded && typeof limit !== 'undefined' && parts.length > limit) {
throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.');
}
var skipIndex = -1; // Keep track of where the utf8 sentinel was found
var i;
var charset = options.charset;
if (options.charsetSentinel) {
for (i = 0; i < parts.length; ++i) {
if (parts[i].indexOf('utf8=') === 0) {
if (parts[i] === charsetSentinel) {
charset = 'utf-8';
} else if (parts[i] === isoSentinel) {
charset = 'iso-8859-1';
}
skipIndex = i;
i = parts.length; // The eslint settings do not allow break;
}
}
}
for (i = 0; i < parts.length; ++i) {
if (i === skipIndex) {
continue;
}
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
// `[]` belongs to the key, so look for it at the split point, not anywhere in the part
var isEmptyBracketKey = pos > 1 && part.slice(pos - 2, pos) === '[]';
var key;
var val;
if (pos === -1) {
key = options.decoder(part, defaults.decoder, charset, 'key');
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
if (key !== null) {
val = utils.maybeMap(
parseArrayValue(
part.slice(pos + 1),
options,
isArray(obj[key]) ? obj[key].length : 0
),
function (encodedVal) {
return options.decoder(encodedVal, defaults.decoder, charset, 'value');
}
);
}
}
if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
val = interpretNumericEntities(String(val));
}
if (isEmptyBracketKey) {
val = isArray(val) ? [val] : val;
}
if (options.comma && isArray(val) && val.length > options.arrayLimit) {
val = utils.combine([], val, options.arrayLimit, options.plainObjects, options.throwOnLimitExceeded);
}
if (key !== null) {
var existing = has.call(obj, key);
if (existing && (options.duplicates === 'combine' || isEmptyBracketKey)) {
obj[key] = utils.combine(
obj[key],
val,
options.arrayLimit,
options.plainObjects,
options.throwOnLimitExceeded
);
} else if (!existing || options.duplicates === 'last') {
obj[key] = val;
}
}
}
return obj;
};
var parseObject = function (chain, val, options, valuesParsed) {
var currentArrayLength = 0;
if (chain.length > 0 && chain[chain.length - 1] === '[]') {
var parentKey = chain.slice(0, -1).join('');
currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0;
}
var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength);
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]' && options.parseArrays) {
if (utils.isOverflow(leaf)) {
// leaf is already an overflow object, preserve it
obj = leaf;
} else {
obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null))
? []
: utils.combine(
[],
leaf,
options.arrayLimit,
options.plainObjects,
options.throwOnLimitExceeded
);
}
} else {
obj = options.plainObjects ? { __proto__: null } : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot;
var index = parseInt(decodedRoot, 10);
var isValidArrayIndex = !isNaN(index)
&& root !== decodedRoot
&& String(index) === decodedRoot
&& index >= 0
&& options.parseArrays;
if (!options.parseArrays && decodedRoot === '') {
obj = { 0: leaf };
} else if (isValidArrayIndex && index < options.arrayLimit) {
obj = [];
obj[index] = leaf;
} else if (isValidArrayIndex && options.throwOnLimitExceeded) {
throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.');
} else if (isValidArrayIndex) {
obj[index] = leaf;
utils.markOverflow(obj, index);
} else if (decodedRoot !== '__proto__') {
obj[decodedRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
// Behaves like `key.replace(/\.([^.[]+)/g, '[$1]')`, but only rewrites a dot
// that sits at bracket depth 0. A literal dot already inside a `[...]` segment
// is left untouched instead of corrupting the key (e.g. "outer[a.b]"). (#617)
var topLevelDotsToBrackets = function topLevelDotsToBrackets(key) {
var result = '';
var depth = 0;
for (var i = 0; i < key.length; i += 1) {
var cu = key.charCodeAt(i);
if (cu === 0x5B) { // '['
depth += 1;
result += '[';
} else if (cu === 0x5D) { // ']'
if (depth > 0) {
depth -= 1;
}
result += ']';
} else if (
cu === 0x2E // '.'
&& depth === 0
&& i + 1 < key.length
&& key.charCodeAt(i + 1) !== 0x2E // not another '.'
&& key.charCodeAt(i + 1) !== 0x5B // not '['
) {
var start = i + 1;
var j = start;
while (j < key.length && key.charCodeAt(j) !== 0x2E && key.charCodeAt(j) !== 0x5B) {
j += 1;
}
result += '[' + key.slice(start, j) + ']';
i = j - 1;
} else {
result += key.charAt(i);
}
}
return result;
};
// Split a key like "a[b][c[]]" into ['a', '[b]', '[c[]]'] while preserving
// qs parse semantics for depth/prototype guards.
var splitKeyIntoSegments = function splitKeyIntoSegments(originalKey, options) {
var key = options.allowDots ? topLevelDotsToBrackets(originalKey) : originalKey;
// depth <= 0 keeps the whole key as one segment
if (options.depth <= 0) {
if (!options.plainObjects && has.call(Object.prototype, key)) {
if (!options.allowPrototypes) {
return;
}
}
return [key];
}
var segments = [];
// parent before the first '[' (may be empty if key starts with '[')
var first = key.indexOf('[');
var parent = first >= 0 ? key.slice(0, first) : key;
if (parent) {
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
segments[segments.length] = parent;
}
var n = key.length;
var open = first;
var collected = 0;
while (open >= 0 && collected < options.depth) {
var level = 1;
var i = open + 1;
var close = -1;
// balance nested '[' and ']' inside this bracket group using a nesting level counter
while (i < n && close < 0) {
var cu = key.charCodeAt(i);
if (cu === 0x5B) { // '['
level += 1;
} else if (cu === 0x5D) { // ']'
level -= 1;
if (level === 0) {
close = i; // found matching close; loop will exit by condition
}
}
i += 1;
}
if (close < 0) {
// Unterminated group: wrap the raw remainder in one bracket pair so it stays
// a single literal segment (e.g. "[[]b" -> "[[]b]"); we do not infer missing ']'.
segments[segments.length] = '[' + key.slice(open) + ']';
return segments;
}
var seg = key.slice(open, close + 1);
// prototype guard for the content of this group
var content = seg.slice(1, -1);
if (!options.plainObjects && has.call(Object.prototype, content) && !options.allowPrototypes) {
return;
}
segments[segments.length] = seg;
collected += 1;
// find the next '[' after this balanced group
open = key.indexOf('[', close + 1);
}
if (open >= 0) {
if (options.strictDepth === true) {
throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true');
}
segments[segments.length] = '[' + key.slice(open) + ']';
}
return segments;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
if (!givenKey) {
return;
}
var keys = splitKeyIntoSegments(givenKey, options);
if (!keys) {
return;
}
return parseObject(keys, val, options, valuesParsed);
};
var normalizeParseOptions = function normalizeParseOptions(opts) {
if (!opts) {
return defaults;
}
if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
}
if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') {
throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided');
}
if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
}
if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') {
throw new TypeError('`throwOnLimitExceeded` option must be a boolean');
}
var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates;
if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') {
throw new TypeError('The duplicates option must be either combine, first, or last');
}
var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
return {
allowDots: allowDots,
allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys,
decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
// eslint-disable-next-line no-implicit-coercion, no-extra-parens
depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
duplicates: duplicates,
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
parseArrays: opts.parseArrays !== false,
plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth,
strictMerge: typeof opts.strictMerge === 'boolean' ? !!opts.strictMerge : defaults.strictMerge,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,
throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false
};
};
module.exports = function (str, opts) {
var options = normalizeParseOptions(opts);
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? { __proto__: null } : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : copyInput(str);
var obj = options.plainObjects ? { __proto__: null } : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
obj = utils.merge(obj, newObj, options);
}
if (options.allowSparse === true) {
return obj;
}
return utils.compact(obj);
};
@@ -0,0 +1,900 @@
export default `flf2a$ 4 3 10 0 10 0 1920
Mini by Glenn Chappell 4/93
Includes ISO Latin-1
figlet release 2.1 -- 12 Aug 1994
Permission is hereby given to modify this font, as long as the
modifier's name is placed on a comment line.
Modified by Paul Burton <solution@earthlink.net> 12/96 to include new parameter
supported by FIGlet and FIGWin. May also be slightly modified for better use
of new full-width/kern/smush alternatives, but default output is NOT changed.
$$@
$$@
$$@
$$@@
@
|$@
o$@
@@
@
||$@
@
@@
@
-|-|-$@
-|-|-$@
@@
_$@
(|$ @
_|)$@
@@
@
O/$@
/O$@
@@
@
()$ @
(_X$@
@@
@
/$@
@
@@
@
/$@
|$ @
\\$@@
@
\\$ @
|$@
/$ @@
@
\\|/$@
/|\\$@
@@
@
_|_$@
|$ @
@@
@
@
o$@
/$@@
@
__$@
@
@@
@
@
o$@
@@
@
/$@
/$ @
@@
_$ @
/ \\$@
\\_/$@
@@
@
/|$@
|$@
@@
_$ @
)$@
/_$@
@@
_$ @
_)$@
_)$@
@@
@
|_|_$@
|$ @
@@
_$ @
|_$ @
_)$@
@@
_$ @
|_$ @
|_)$@
@@
__$@
/$@
/$ @
@@
_$ @
(_)$@
(_)$@
@@
_$ @
(_|$@
|$@
@@
@
o$@
o$@
@@
@
o$@
o$@
/$@@
@
/$@
\\$@
@@
@
--$@
--$@
@@
@
\\$@
/$@
@@
_$ @
)$@
o$ @
@@
__$ @
/ \\$@
| (|/$@
\\__$ @@
@
/\\$ @
/--\\$@
@@
_$ @
|_)$@
|_)$@
@@
_$@
/$ @
\\_$@
@@
_$ @
| \\$@
|_/$@
@@
_$@
|_$@
|_$@
@@
_$@
|_$@
|$ @
@@
__$@
/__$@
\\_|$@
@@
@
|_|$@
| |$@
@@
___$@
|$ @
_|_$@
@@
@
|$@
\\_|$@
@@
@
|/$@
|\\$@
@@
@
|$ @
|_$@
@@
@
|\\/|$@
| |$@
@@
@
|\\ |$@
| \\|$@
@@
_$ @
/ \\$@
\\_/$@
@@
_$ @
|_)$@
|$ @
@@
_$ @
/ \\$@
\\_X$@
@@
_$ @
|_)$@
| \\$@
@@
__$@
(_$ @
__)$@
@@
___$@
|$ @
|$ @
@@
@
| |$@
|_|$@
@@
@
\\ /$@
\\/$ @
@@
@
\\ /$@
\\/\\/$ @
@@
@
\\/$@
/\\$@
@@
@
\\_/$@
|$ @
@@
__$@
/$@
/_$@
@@
_$@
|$ @
|_$@
@@
@
\\$ @
\\$@
@@
_$ @
|$@
_|$@
@@
/\\$@
@
@
@@
@
@
@
__$@@
@
\\$@
@
@@
@
_.$@
(_|$@
@@
@
|_$ @
|_)$@
@@
@
_$@
(_$@
@@
@
_|$@
(_|$@
@@
@
_$ @
(/_$@
@@
_$@
_|_$@
|$ @
@@
@
_$ @
(_|$@
_|$@@
@
|_$ @
| |$@
@@
@
o$@
|$@
@@
@
o$@
|$@
_|$@@
@
|$ @
|<$@
@@
@
|$@
|$@
@@
@
._ _$ @
| | |$@
@@
@
._$ @
| |$@
@@
@
_$ @
(_)$@
@@
@
._$ @
|_)$@
|$ @@
@
_.$@
(_|$@
|$@@
@
._$@
|$ @
@@
@
_$@
_>$@
@@
@
_|_$@
|_$@
@@
@
@
|_|$@
@@
@
@
\\/$@
@@
@
@
\\/\\/$@
@@
@
@
><$@
@@
@
@
\\/$@
/$ @@
@
_$ @
/_$@
@@
,-$@
_|$ @
|$ @
\`-$@@
|$@
|$@
|$@
|$@@
-.$ @
|_$@
|$ @
-'$ @@
/\\/$@
@
@
@@
o o$@
/\\$ @
/--\\$@
@@
o_o$@
/ \\$@
\\_/$@
@@
o o$@
| |$@
|_|$@
@@
o o$@
_.$@
(_|$@
@@
o o$@
_$ @
(_)$@
@@
o o$@
@
|_|$@
@@
_$ @
| )$@
| )$@
|$ @@
160 NO-BREAK SPACE
$$@
$$@
$$@
$$@@
161 INVERTED EXCLAMATION MARK
@
o$@
|$@
@@
162 CENT SIGN
@
|_$@
(__$@
|$ @@
163 POUND SIGN
_$ @
_/_\`$ @
|___$@
@@
164 CURRENCY SIGN
@
\`o'$@
' \`$@
@@
165 YEN SIGN
@
_\\_/_$@
--|--$@
@@
166 BROKEN BAR
|$@
|$@
|$@
|$@@
167 SECTION SIGN
_$@
($ @
()$@
_)$@@
168 DIAERESIS
o o$@
@
@
@@
169 COPYRIGHT SIGN
_$ @
|C|$@
\`-'$@
@@
170 FEMININE ORDINAL INDICATOR
_.$@
(_|$@
---$@
@@
171 LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
@
//$@
\\\\$@
@@
172 NOT SIGN
@
__$ @
|$@
@@
173 SOFT HYPHEN
@
_$@
@
@@
174 REGISTERED SIGN
_$ @
|R|$@
\`-'$@
@@
175 MACRON
__$@
@
@
@@
176 DEGREE SIGN
O$@
@
@
@@
177 PLUS-MINUS SIGN
@
_|_$@
_|_$@
@@
178 SUPERSCRIPT TWO
2$@
@
@
@@
179 SUPERSCRIPT THREE
3$@
@
@
@@
180 ACUTE ACCENT
/$@
@
@
@@
181 MICRO SIGN
@
@
|_|$@
|$ @@
182 PILCROW SIGN
__$ @
(| |$@
| |$@
@@
183 MIDDLE DOT
@
o$@
@
@@
184 CEDILLA
@
@
@
S$@@
185 SUPERSCRIPT ONE
1$@
@
@
@@
186 MASCULINE ORDINAL INDICATOR
_$ @
(_)$@
---$@
@@
187 RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
@
\\\\$@
//$@
@@
188 VULGAR FRACTION ONE QUARTER
@
1/$@
/4$@
@@
189 VULGAR FRACTION ONE HALF
@
1/$@
/2$@
@@
190 VULGAR FRACTION THREE QUARTERS
@
3/$@
/4$@
@@
191 INVERTED QUESTION MARK
@
o$@
(_$@
@@
192 LATIN CAPITAL LETTER A WITH GRAVE
\\$ @
/\\$ @
/--\\$@
@@
193 LATIN CAPITAL LETTER A WITH ACUTE
/$ @
/\\$ @
/--\\$@
@@
194 LATIN CAPITAL LETTER A WITH CIRCUMFLEX
/\\$ @
/\\$ @
/--\\$@
@@
195 LATIN CAPITAL LETTER A WITH TILDE
/\\/$@
/\\$ @
/--\\$@
@@
196 LATIN CAPITAL LETTER A WITH DIAERESIS
o o$@
/\\$ @
/--\\$@
@@
197 LATIN CAPITAL LETTER A WITH RING ABOVE
O$ @
/ \\$ @
/---\\$@
@@
198 LATIN CAPITAL LETTER AE
_$@
/|_$@
/-|_$@
@@
199 LATIN CAPITAL LETTER C WITH CEDILLA
_$@
/$ @
\\_$@
S$@@
200 LATIN CAPITAL LETTER E WITH GRAVE
\\_$@
|_$@
|_$@
@@
201 LATIN CAPITAL LETTER E WITH ACUTE
_/$@
|_$ @
|_$ @
@@
202 LATIN CAPITAL LETTER E WITH CIRCUMFLEX
/\\$@
|_$ @
|_$ @
@@
203 LATIN CAPITAL LETTER E WITH DIAERESIS
o_o$@
|_$ @
|_$ @
@@
204 LATIN CAPITAL LETTER I WITH GRAVE
\\__$@
|$ @
_|_$@
@@
205 LATIN CAPITAL LETTER I WITH ACUTE
__/$@
|$ @
_|_$@
@@
206 LATIN CAPITAL LETTER I WITH CIRCUMFLEX
/\\$@
___$@
_|_$@
@@
207 LATIN CAPITAL LETTER I WITH DIAERESIS
o_o$@
|$ @
_|_$@
@@
208 LATIN CAPITAL LETTER ETH
_$ @
_|_\\$@
|_/$@
@@
209 LATIN CAPITAL LETTER N WITH TILDE
/\\/$@
|\\ |$@
| \\|$@
@@
210 LATIN CAPITAL LETTER O WITH GRAVE
\\$ @
/ \\$@
\\_/$@
@@
211 LATIN CAPITAL LETTER O WITH ACUTE
/$ @
/ \\$@
\\_/$@
@@
212 LATIN CAPITAL LETTER O WITH CIRCUMFLEX
/\\$@
/ \\$@
\\_/$@
@@
213 LATIN CAPITAL LETTER O WITH TILDE
/\\/$@
/ \\$@
\\_/$@
@@
214 LATIN CAPITAL LETTER O WITH DIAERESIS
o_o$@
/ \\$@
\\_/$@
@@
215 MULTIPLICATION SIGN
@
@
X$@
@@
216 LATIN CAPITAL LETTER O WITH STROKE
__$ @
/ /\\$@
\\/_/$@
@@
217 LATIN CAPITAL LETTER U WITH GRAVE
\\$ @
| |$@
|_|$@
@@
218 LATIN CAPITAL LETTER U WITH ACUTE
/$ @
| |$@
|_|$@
@@
219 LATIN CAPITAL LETTER U WITH CIRCUMFLEX
/\\$@
| |$@
|_|$@
@@
220 LATIN CAPITAL LETTER U WITH DIAERESIS
o o$@
| |$@
|_|$@
@@
221 LATIN CAPITAL LETTER Y WITH ACUTE
/$ @
\\_/$@
|$ @
@@
222 LATIN CAPITAL LETTER THORN
|_$ @
|_)$@
|$ @
@@
223 LATIN SMALL LETTER SHARP S
_$ @
| )$@
| )$@
|$ @@
224 LATIN SMALL LETTER A WITH GRAVE
\\$ @
_.$@
(_|$@
@@
225 LATIN SMALL LETTER A WITH ACUTE
/$ @
_.$@
(_|$@
@@
226 LATIN SMALL LETTER A WITH CIRCUMFLEX
/\\$@
_.$@
(_|$@
@@
227 LATIN SMALL LETTER A WITH TILDE
/\\/$@
_.$@
(_|$@
@@
228 LATIN SMALL LETTER A WITH DIAERESIS
o o$@
_.$@
(_|$@
@@
229 LATIN SMALL LETTER A WITH RING ABOVE
O$ @
_.$@
(_|$@
@@
230 LATIN SMALL LETTER AE
@
___$ @
(_|/_$@
@@
231 LATIN SMALL LETTER C WITH CEDILLA
@
_$@
(_$@
S$@@
232 LATIN SMALL LETTER E WITH GRAVE
\\$ @
_$ @
(/_$@
@@
233 LATIN SMALL LETTER E WITH ACUTE
/$ @
_$ @
(/_$@
@@
234 LATIN SMALL LETTER E WITH CIRCUMFLEX
/\\$@
_$ @
(/_$@
@@
235 LATIN SMALL LETTER E WITH DIAERESIS
o o$@
_$ @
(/_$@
@@
236 LATIN SMALL LETTER I WITH GRAVE
\\$@
@
|$@
@@
237 LATIN SMALL LETTER I WITH ACUTE
/$@
@
|$@
@@
238 LATIN SMALL LETTER I WITH CIRCUMFLEX
/\\$@
@
|$ @
@@
239 LATIN SMALL LETTER I WITH DIAERESIS
o o$@
@
|$ @
@@
240 LATIN SMALL LETTER ETH
X$ @
\\$ @
(_|$@
@@
241 LATIN SMALL LETTER N WITH TILDE
/\\/$@
._$ @
| |$@
@@
242 LATIN SMALL LETTER O WITH GRAVE
\\$ @
_$ @
(_)$@
@@
243 LATIN SMALL LETTER O WITH ACUTE
/$ @
_$ @
(_)$@
@@
244 LATIN SMALL LETTER O WITH CIRCUMFLEX
/\\$@
_$ @
(_)$@
@@
245 LATIN SMALL LETTER O WITH TILDE
/\\/$@
_$ @
(_)$@
@@
246 LATIN SMALL LETTER O WITH DIAERESIS
o o$@
_$ @
(_)$@
@@
247 DIVISION SIGN
o$ @
---$@
o$ @
@@
248 LATIN SMALL LETTER O WITH STROKE
@
_$ @
(/)$@
@@
249 LATIN SMALL LETTER U WITH GRAVE
\\$ @
@
|_|$@
@@
250 LATIN SMALL LETTER U WITH ACUTE
/$ @
@
|_|$@
@@
251 LATIN SMALL LETTER U WITH CIRCUMFLEX
/\\$@
@
|_|$@
@@
252 LATIN SMALL LETTER U WITH DIAERESIS
o o$@
@
|_|$@
@@
253 LATIN SMALL LETTER Y WITH ACUTE
/$@
@
\\/$@
/$ @@
254 LATIN SMALL LETTER THORN
@
|_$ @
|_)$@
|$ @@
255 LATIN SMALL LETTER Y WITH DIAERESIS
oo$@
@
\\/$@
/$ @@
`
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_J"},C:{"1":"_QO","2":"_TK"},D:{"1":"_GN _SG","2":"_6E","33":"N _rK"},E:{"1":"_wF","2":"_u","33":"_fC _zB _NE"},F:{"1":"_bG _vB","2":"_T","33":"_cH"},G:{"1":"_JE","2":"_1","33":"_SD _hR"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_F"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"_C"}},B:2,C:"Web Audio API",D:true};
@@ -0,0 +1 @@
{"version":3,"file":"scoring.mjs","sources":["../../../src/matcher/separator/scoring.ts"],"sourcesContent":[null],"names":["SEPERATOR_CHAR_COUNT"],"mappings":";;AAEA,uBAAe,MAAK;AAClB,EAAA,OAAOA,oBAAoB;AAC7B,CAAC;;;;"}
@@ -0,0 +1,4 @@
let urlAlphabet =
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
module.exports = { urlAlphabet }
@@ -0,0 +1,371 @@
'use strict'
const Agent = require('../dispatcher/agent')
const MockAgent = require('./mock-agent')
const { SnapshotRecorder } = require('./snapshot-recorder')
const { InvalidArgumentError, UndiciError } = require('../core/errors')
const util = require('../core/util')
const { validateSnapshotMode } = require('./snapshot-utils')
const kSnapshotRecorder = Symbol('kSnapshotRecorder')
const kSnapshotMode = Symbol('kSnapshotMode')
const kSnapshotPath = Symbol('kSnapshotPath')
const kSnapshotLoaded = Symbol('kSnapshotLoaded')
const kRealAgent = Symbol('kRealAgent')
// Static flag to ensure warning is only emitted once per process
let warningEmitted = false
class SnapshotAgent extends MockAgent {
constructor (opts = {}) {
// Emit experimental warning only once
if (!warningEmitted) {
process.emitWarning(
'SnapshotAgent is experimental and subject to change',
'ExperimentalWarning'
)
warningEmitted = true
}
const {
mode = 'record',
snapshotPath = null,
...mockAgentOpts
} = opts
super(mockAgentOpts)
validateSnapshotMode(mode)
// Validate snapshotPath is provided when required
if ((mode === 'playback' || mode === 'update') && !snapshotPath) {
throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`)
}
this[kSnapshotMode] = mode
this[kSnapshotPath] = snapshotPath
this[kSnapshotRecorder] = new SnapshotRecorder({
snapshotPath: this[kSnapshotPath],
mode: this[kSnapshotMode],
maxSnapshots: opts.maxSnapshots,
autoFlush: opts.autoFlush,
flushInterval: opts.flushInterval,
matchHeaders: opts.matchHeaders,
ignoreHeaders: opts.ignoreHeaders,
excludeHeaders: opts.excludeHeaders,
matchBody: opts.matchBody,
normalizeBody: opts.normalizeBody,
matchQuery: opts.matchQuery,
normalizeQuery: opts.normalizeQuery,
caseSensitive: opts.caseSensitive,
shouldRecord: opts.shouldRecord,
shouldPlayback: opts.shouldPlayback,
excludeUrls: opts.excludeUrls
})
this[kSnapshotLoaded] = false
// For recording/update mode, we need a real agent to make actual requests
// For playback mode, we need a real agent if there are excluded URLs
if (this[kSnapshotMode] === 'record' || this[kSnapshotMode] === 'update' ||
(this[kSnapshotMode] === 'playback' && opts.excludeUrls && opts.excludeUrls.length > 0)) {
this[kRealAgent] = new Agent(opts)
}
// Auto-load snapshots in playback/update mode
if ((this[kSnapshotMode] === 'playback' || this[kSnapshotMode] === 'update') && this[kSnapshotPath]) {
this.loadSnapshots().catch(() => {
// Ignore load errors - file might not exist yet
})
}
}
dispatch (opts, handler) {
const mode = this[kSnapshotMode]
// Check if URL should be excluded (pass through without mocking/recording)
if (this[kSnapshotRecorder].isUrlExcluded(opts)) {
// Real agent is guaranteed by constructor when excludeUrls is configured
return this[kRealAgent].dispatch(opts, handler)
}
if (mode === 'playback' || mode === 'update') {
// Ensure snapshots are loaded
if (!this[kSnapshotLoaded]) {
// Need to load asynchronously, delegate to async version
return this.#asyncDispatch(opts, handler)
}
// Try to find existing snapshot (synchronous)
const snapshot = this[kSnapshotRecorder].findSnapshot(opts)
if (snapshot) {
// Use recorded response (synchronous)
return this.#replaySnapshot(snapshot, handler)
} else if (mode === 'update') {
// Make real request and record it (async required)
return this.#recordAndReplay(opts, handler)
} else {
// Playback mode but no snapshot found
const error = new UndiciError(`No snapshot found for ${opts.method || 'GET'} ${opts.path}`)
if (handler.onResponseError) {
handler.onResponseError(null, error)
return
}
throw error
}
} else if (mode === 'record') {
// Record mode - make real request and save response (async required)
return this.#recordAndReplay(opts, handler)
}
}
/**
* Async version of dispatch for when we need to load snapshots first
*/
async #asyncDispatch (opts, handler) {
await this.loadSnapshots()
return this.dispatch(opts, handler)
}
/**
* Records a real request and replays the response
*/
#recordAndReplay (opts, handler) {
const responseData = {
statusCode: null,
headers: {},
trailers: {},
body: []
}
const self = this // Capture 'this' context for use within nested handler callbacks
const recordingHandler = {
onRequestStart (controller, context) {
return handler.onRequestStart(controller, { ...context, history: this.history })
},
onRequestUpgrade (controller, statusCode, headers, socket) {
return handler.onRequestUpgrade(controller, statusCode, headers, socket)
},
onResponseStart (controller, statusCode, headers, statusMessage) {
responseData.statusCode = statusCode
responseData.headers = headers
return handler.onResponseStart(controller, statusCode, headers, statusMessage)
},
onResponseData (controller, chunk) {
responseData.body.push(chunk)
return handler.onResponseData(controller, chunk)
},
onResponseEnd (controller, trailers) {
responseData.trailers = trailers
// Record the interaction using captured 'self' context (fire and forget)
const responseBody = Buffer.concat(responseData.body)
self[kSnapshotRecorder].record(opts, {
statusCode: responseData.statusCode,
headers: responseData.headers,
body: responseBody,
trailers: responseData.trailers
})
.then(() => handler.onResponseEnd(controller, trailers))
.catch((error) => handler.onResponseError(controller, error))
},
onResponseError (controller, error) {
return handler.onResponseError(controller, error)
}
}
// Use composed agent if available (includes interceptors), otherwise use real agent
const agent = this[kRealAgent]
return agent.dispatch(opts, recordingHandler)
}
/**
* Replays a recorded response
*
* @param {Object} snapshot - The recorded snapshot to replay.
* @param {Object} handler - The handler to call with the response data.
* @returns {void}
*/
#replaySnapshot (snapshot, handler) {
try {
const { response } = snapshot
const rawHeaders = response.headers ? util.toRawHeaders(response.headers) : []
const rawTrailers = response.trailers ? util.toRawHeaders(response.trailers) : []
const controller = {
rawHeaders,
rawTrailers,
pause () { },
resume () { },
abort (reason) {
this.aborted = true
this.reason = reason
},
aborted: false,
paused: false
}
handler.onRequestStart(controller)
handler.onResponseStart(controller, response.statusCode, response.headers, response.statusMessage)
// Body is always stored as base64 string
const body = Buffer.from(response.body, 'base64')
handler.onResponseData(controller, body)
handler.onResponseEnd(controller, response.trailers)
} catch (error) {
handler.onResponseError?.(null, error)
}
}
/**
* Loads snapshots from file
*
* @param {string} [filePath] - Optional file path to load snapshots from.
* @returns {Promise<void>} - Resolves when snapshots are loaded.
*/
async loadSnapshots (filePath) {
await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath])
this[kSnapshotLoaded] = true
// In playback mode, set up MockAgent interceptors for all snapshots
if (this[kSnapshotMode] === 'playback') {
this.#setupMockInterceptors()
}
}
/**
* Saves snapshots to file
*
* @param {string} [filePath] - Optional file path to save snapshots to.
* @returns {Promise<void>} - Resolves when snapshots are saved.
*/
async saveSnapshots (filePath) {
return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath])
}
/**
* Sets up MockAgent interceptors based on recorded snapshots.
*
* This method creates MockAgent interceptors for each recorded snapshot,
* allowing the SnapshotAgent to fall back to MockAgent's standard intercept
* mechanism in playback mode. Each interceptor is configured to persist
* (remain active for multiple requests) and responds with the recorded
* response data.
*
* Called automatically when loading snapshots in playback mode.
*
* @returns {void}
*/
#setupMockInterceptors () {
for (const snapshot of this[kSnapshotRecorder].getSnapshots()) {
const { request, responses, response } = snapshot
const url = new URL(request.url)
const mockPool = this.get(url.origin)
// Handle both new format (responses array) and legacy format (response object)
const responseData = responses ? responses[0] : response
if (!responseData) continue
mockPool.intercept({
path: url.pathname + url.search,
method: request.method,
headers: request.headers,
body: request.body
}).reply(responseData.statusCode, responseData.body, {
headers: responseData.headers,
trailers: responseData.trailers
}).persist()
}
}
/**
* Gets the snapshot recorder
* @return {SnapshotRecorder} - The snapshot recorder instance
*/
getRecorder () {
return this[kSnapshotRecorder]
}
/**
* Gets the current mode
* @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode
*/
getMode () {
return this[kSnapshotMode]
}
/**
* Clears all snapshots
* @returns {void}
*/
clearSnapshots () {
this[kSnapshotRecorder].clear()
}
/**
* Resets call counts for all snapshots (useful for test cleanup)
* @returns {void}
*/
resetCallCounts () {
this[kSnapshotRecorder].resetCallCounts()
}
/**
* Deletes a specific snapshot by request options
* @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot
* @return {Promise<boolean>} - Returns true if the snapshot was deleted, false if not found
*/
deleteSnapshot (requestOpts) {
return this[kSnapshotRecorder].deleteSnapshot(requestOpts)
}
/**
* Gets information about a specific snapshot
* @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found
*/
getSnapshotInfo (requestOpts) {
return this[kSnapshotRecorder].getSnapshotInfo(requestOpts)
}
/**
* Replaces all snapshots with new data (full replacement)
* @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record<string, import('./snapshot-recorder').SnapshotEntry>} snapshotData - New snapshot data to replace existing snapshots
* @returns {void}
*/
replaceSnapshots (snapshotData) {
this[kSnapshotRecorder].replaceSnapshots(snapshotData)
}
/**
* Closes the agent, saving snapshots and cleaning up resources.
*
* @returns {Promise<void>}
*/
async close () {
// In playback mode the recorder must not persist to disk. findSnapshot()
// mutates each matched snapshot's callCount, so saving on close would
// rewrite the snapshot file even though nothing new was recorded. Only
// record/update modes should write snapshots; playback just cleans up.
if (this[kSnapshotMode] === 'playback') {
this[kSnapshotRecorder].destroy()
} else {
await this[kSnapshotRecorder].close()
}
await this[kRealAgent]?.close()
await super.close()
}
}
module.exports = SnapshotAgent
@@ -0,0 +1,667 @@
/**
* Argon2 KDF from RFC 9106. Can be used to create a key from password and salt.
* We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness:
* * argon uses uint64, but JS doesn't have fast uint64array
* * uint64 multiplication is 1/3 of time
* * `P` function would be very nice with u64, because most of value will be in registers,
* hovewer with u32 it will require 32 registers, which is too much.
* * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down
* @module
*/
import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.ts';
import { blake2b } from './blake2.ts';
import {
anumber,
clean,
kdfInputToBytes,
nextTick,
swap32IfBE,
swap8IfBE,
u32,
u8,
type KDFInput,
type TArg,
type TRet,
} from './utils.ts';
// RFC 9106 §3.1 type `y`: 0 = Argon2d, 1 = Argon2i, 2 = Argon2id. The numeric values are the
// spec-bound part here; the object keys are internal labels.
const AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 } as const;
type Types = (typeof AT)[keyof typeof AT];
// RFC 9106 sync points constant `SL = 4`, fixed by the design rather than exposed as a tuning knob.
const ARGON2_SYNC_POINTS = 4;
// Preserve Argon2's `LE32(len(X)) || X` encoding for omitted
// optional fields by emitting empty bytes.
const abytesOrZero = (buf?: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> => {
if (buf === undefined) return Uint8Array.of();
return kdfInputToBytes(buf, errorTitle);
};
// Unsigned `u32 * u32 = { h, l }`, returned as split 64-bit halves.
function mul(a: number, b: number) {
// Split into 16-bit limbs so each partial product stays exact under `Math.imul`.
const aL = a & 0xffff;
const aH = a >>> 16;
const bL = b & 0xffff;
const bH = b >>> 16;
const ll = Math.imul(aL, bL);
const hl = Math.imul(aH, bL);
const lh = Math.imul(aL, bH);
const hh = Math.imul(aH, bH);
const carry = (ll >>> 16) + (hl & 0xffff) + lh;
const high = (hh + (hl >>> 16) + (carry >>> 16)) | 0;
const low = (carry << 16) | (ll & 0xffff);
return { h: high, l: low };
}
function mul2(a: number, b: number) {
// Double the split 64-bit product; carry from `l` is folded back into `h` via `l >>> 31`.
const { h, l } = mul(a, b);
return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff };
}
// BlaMka permutation for Argon2
// `A + B + 2 * trunc(A) * trunc(B)`, where `trunc(...)` means the low 32-bit halves.
function blamka(Ah: number, Al: number, Bh: number, Bl: number) {
const { h: Ch, l: Cl } = mul2(Al, Bl);
// A + B + (2 * A * B)
const Rll = add3L(Al, Bl, Cl);
return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 };
}
// Temporary block buffer.
// 1024-byte block: 256 u32 = 128 interleaved low/high halves = RFC's
// 8x8 matrix of 16-byte registers.
const A2_BUF = new Uint32Array(256);
// Quarter-round over 64-bit word indices into `A2_BUF`; each index maps to adjacent low/high u32s.
function G(a: number, b: number, c: number, d: number) {
let Al = A2_BUF[2*a], Ah = A2_BUF[2*a + 1]; // prettier-ignore
let Bl = A2_BUF[2*b], Bh = A2_BUF[2*b + 1]; // prettier-ignore
let Cl = A2_BUF[2*c], Ch = A2_BUF[2*c + 1]; // prettier-ignore
let Dl = A2_BUF[2*d], Dh = A2_BUF[2*d + 1]; // prettier-ignore
// RFC 9106 Figure 19 GB rotates by 32, 24, 16, and 63 bits after each XOR step.
({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) });
({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl));
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl));
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
((A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah));
((A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh));
((A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch));
((A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh));
}
// Argon2 permutation over 16 register indices into `A2_BUF`, not the register values themselves.
// RFC 9106 Figure 17: these arguments are the 16 `v0..v15` 64-bit word
// indices inside eight 16-byte inputs, not copied word values.
// prettier-ignore
function P(
v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number,
v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number,
) {
// RFC 9106 Figure 18: first apply GB across rows, then across columns of the 8x8 register matrix.
G(v00, v04, v08, v12);
G(v01, v05, v09, v13);
G(v02, v06, v10, v14);
G(v03, v07, v11, v15);
G(v00, v05, v10, v15);
G(v01, v06, v11, v12);
G(v02, v07, v08, v13);
G(v03, v04, v09, v14);
}
function block(x: TArg<Uint32Array>, xPos: number, yPos: number, outPos: number, needXor: boolean) {
for (let i = 0; i < 256; i++) A2_BUF[i] = x[xPos + i] ^ x[yPos + i];
// rows (8 consecutive 16-register groups)
for (let i = 0; i < 128; i += 16) {
// prettier-ignore
P(
i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7,
i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15
);
}
// columns (8 strided 16-register groups)
for (let i = 0; i < 16; i += 2) {
// prettier-ignore
P(
i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49,
i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113
);
}
// RFC 9106 step 6: passes after the first XOR the old destination block into the new G(X, Y).
if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
else for (let i = 0; i < 256; i++) x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i];
clean(A2_BUF);
}
// Variable-Length Hash Function H'
// Returns bytes, not words; 1024-byte block callers explicitly reinterpret with `u32(...)`.
function Hp(A: TArg<Uint32Array>, dkLen: number): TRet<Uint8Array> {
const A8 = u8(A);
const T = new Uint32Array(1);
const T8 = u8(T);
// Argon2 H' prefixes dkLen as LE32; native Uint32Array writes would serialize as BE on s390x.
T[0] = swap8IfBE(dkLen);
// Fast path
if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest();
const out = new Uint8Array(dkLen);
let V = blake2b.create({}).update(T8).update(A8).digest();
let pos = 0;
// RFC 9106 Figure 8: each intermediate `V_i` contributes only `W_i`, its first 32 bytes; only
// `V_{r+1}` is emitted in full at the remaining length.
out.set(V.subarray(0, 32));
pos += 32;
// Rest blocks
for (; dkLen - pos > 64; pos += 32) {
const Vh = blake2b.create({}).update(V);
Vh.digestInto(V);
Vh.destroy();
out.set(V.subarray(0, 32), pos);
}
// Last block
out.set(blake2b(V, { dkLen: dkLen - pos }), pos);
clean(V, T);
// H' is byte-oriented; returning `u32(out)` would silently drop dkLen % 4 tail bytes.
return out as TRet<Uint8Array>;
}
// Used only inside process block!
function indexAlpha(
r: number,
s: number,
laneLen: number,
segmentLen: number,
index: number,
randL: number,
sameLane: boolean = false
) {
// RFC 9106 §3.4.2 Figures 12-13: map `J1` / `J2` into the current lane's reference area `W`.
let area: number;
if (r === 0) {
if (s === 0) area = index - 1;
else if (sameLane) area = s * segmentLen + index - 1;
else area = s * segmentLen + (index == 0 ? -1 : 0);
} else if (sameLane) area = laneLen - segmentLen + index - 1;
else area = laneLen - segmentLen + (index == 0 ? -1 : 0);
const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0;
// RFC 9106 Figure 13: `mul(randL, randL).h` is `floor(J_1^2 / 2^32)`, and the outer high-half
// multiply computes `floor(|W| * x / 2^32)` without floating-point math.
const rel = area - 1 - mul(area, mul(randL, randL).h).h;
return (startPos + rel) % laneLen;
}
/** Argon2 cost, output, and optional secret/personalization inputs. */
export type ArgonOpts = {
/** Time cost measured in iterations. */
t: number;
/** Memory cost in kibibytes. */
m: number;
/** Parallelization parameter. */
p: number;
/** Argon2 version number. Defaults to `0x13`. */
version?: number;
/** Optional secret key mixed into initialization. */
key?: KDFInput;
/** Optional personalization string or bytes. */
personalization?: KDFInput;
/** Desired output length in bytes. RFC 9106 §3.1 requires `T` in the 4..(2^32 - 1) range. */
dkLen?: number;
/** Max scheduler block time in milliseconds for the async variants. */
asyncTick?: number;
/** Maximum temporary memory budget in bytes. */
maxmem?: number;
/**
* Optional progress callback invoked during long-running derivations.
* param progress - completion fraction in the `0..1` range
*/
onProgress?: (progress: number) => void;
};
// Exclusive `2^32` sentinel used by `isU32(...)`, not the inclusive maximum u32 value.
const maxUint32 = Math.pow(2, 32);
// Validate safe JS integers in `[0, 2^32 - 1]`.
function isU32(num: number) {
return Number.isSafeInteger(num) && num >= 0 && num < maxUint32;
}
function argon2Opts(opts: TArg<ArgonOpts>) {
const merged: any = {
version: 0x13,
dkLen: 32,
maxmem: maxUint32 - 1,
asyncTick: 10,
};
// Unknown keys are copied through unchanged here and later ignored unless
// destructuring consumes them.
for (let [k, v] of Object.entries(opts)) if (v !== undefined) merged[k] = v;
const { dkLen, p, m, t, version, onProgress, asyncTick } = merged;
// RFC 9106 §3.1: tag length `T` MUST be an integer number of bytes from 4 to 2^32-1.
if (!isU32(dkLen) || dkLen < 4) throw new Error('"dkLen" must be 4..');
if (!isU32(p) || p < 1 || p >= Math.pow(2, 24)) throw new Error('"p" must be 1..2^24');
if (!isU32(m)) throw new Error('"m" must be 0..2^32');
if (!isU32(t) || t < 1) throw new Error('"t" (iterations) must be 1..2^32');
if (onProgress !== undefined && typeof onProgress !== 'function')
throw new Error('"progressCb" must be a function');
anumber(asyncTick, 'asyncTick');
/*
Memory size m MUST be an integer number of kibibytes from 8*p
to 2^(32)-1. The actual number of blocks is m', which is m
rounded down to the nearest multiple of 4*p.
*/
if (!isU32(m) || m < 8 * p) throw new Error('"m" (memory) must be at least 8*p bytes');
// Accept legacy `0x10` for compatibility even though RFC 9106 profiles standardize `0x13`.
if (version !== 0x10 && version !== 0x13)
throw new Error('"version" must be 0x10 or 0x13, got ' + version);
return merged;
}
function argon2Init(
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
type: Types,
opts: TArg<ArgonOpts>
) {
password = kdfInputToBytes(password, 'password');
salt = kdfInputToBytes(salt, 'salt');
if (!isU32(password.length)) throw new Error('"password" must be less of length 1..4Gb');
// RFC 9106 §3.1 only requires S <= 2^32-1 bytes and says 16 bytes is RECOMMENDED for password
// hashing; this library intentionally takes the stricter common >=8-byte salt path.
if (!isU32(salt.length) || salt.length < 8) throw new Error('"salt" must be of length 8..4Gb');
if (!Object.values(AT).includes(type)) throw new Error('"type" was invalid');
let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } =
argon2Opts(opts);
// Validation
key = abytesOrZero(key, 'key');
personalization = abytesOrZero(personalization, 'personalization');
// H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) ||
// LE32(v) || LE32(y) || LE32(length(P)) || P ||
// LE32(length(S)) || S || LE32(length(K)) || K ||
// LE32(length(X)) || X)
const h = blake2b.create();
const BUF = new Uint32Array(1);
const BUF8 = u8(BUF);
for (let item of [p, dkLen, m, t, version, type]) {
// RFC 9106 H0 encodes these scalars as LE32, so normalize the host word before exposing bytes.
BUF[0] = swap8IfBE(item);
h.update(BUF8);
}
for (let i of [password, salt, key, personalization]) {
BUF[0] = swap8IfBE(i.length); // BUF is u32 array, this is valid once normalized to LE bytes
h.update(BUF8).update(i);
}
// Reserve two extra LE32 words after the 64-byte `H_0` so Figures 3-4 can append
// `LE32(0 or 1) || LE32(i)` in place for the lane-starting blocks.
const H0 = new Uint32Array(18);
const H0_8 = u8(H0);
h.digestInto(H0_8);
// 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing
// Params
const lanes = p;
// m' = 4 * p * floor (m / 4p)
const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p));
//q = m' / p columns
const laneLen = Math.floor(mP / p);
const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS);
// `maxmem` is documented in bytes; compare against the actual 1024-byte block allocation.
const memUsed = mP * 1024;
if (!isU32(maxmem)) throw new Error('"maxmem" expected <2**32, got ' + maxmem);
if (memUsed > maxmem)
throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ', maxmem=' + maxmem);
const B = new Uint32Array(memUsed / 4);
// Fill first blocks
for (let l = 0; l < p; l++) {
const i = 256 * laneLen * l;
// B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i))
H0[17] = swap8IfBE(l);
H0[16] = swap8IfBE(0);
B.set(swap32IfBE(u32(Hp(H0, 1024))), i);
// B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i))
H0[16] = swap8IfBE(1);
B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256);
}
let perBlock = () => {};
if (onProgress) {
// The first segment of the first pass skips two preinitialized blocks per lane.
const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p;
// Invoke callback if progress changes from 10.01 to 10.02
// Allows to draw smooth progress bar on up to 8K screen
const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1);
let blockCnt = 0;
perBlock = () => {
blockCnt++;
if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock))
onProgress(blockCnt / totalBlock);
};
}
clean(BUF, H0);
return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick };
}
function argon2Output(
B: TArg<Uint32Array>,
p: number,
laneLen: number,
dkLen: number
): TRet<Uint8Array> {
const B_final = new Uint32Array(256);
for (let l = 0; l < p; l++)
for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j];
// RFC 9106 steps 7-8 feed the byte string `C` into `H'^T(C)`, so normalize the xor'ed words
// back to spec byte order before `Hp(...)` reinterprets them as bytes.
const res = Hp(swap32IfBE(B_final), dkLen);
// Wipe both the xor scratch and the full working matrix once final digest bytes exist.
// JS cleanup is still only best-effort, but this local buffer is no longer needed here.
clean(B, B_final);
return res;
}
function processBlock(
B: TArg<Uint32Array>,
address: TArg<Uint32Array>,
l: number,
r: number,
s: number,
index: number,
laneLen: number,
segmentLen: number,
lanes: number,
offset: number,
prev: number,
dataIndependent: boolean,
needXor: boolean
) {
if (offset % laneLen) prev = offset - 1;
let randL, randH;
if (dataIndependent) {
let i128 = index % 128;
// RFC 9106 §3.4.1.2: each 1024-byte address block yields 128 `(J1, J2)` pairs, so regenerate
// it whenever the segment index crosses a multiple of 128.
if (i128 === 0) {
address[256 + 12]++;
block(address, 256, 2 * 256, 0, false);
block(address, 0, 2 * 256, 0, false);
}
randL = address[2 * i128];
randH = address[2 * i128 + 1];
} else {
const T = 256 * prev;
randL = B[T];
randH = B[T + 1];
}
// Address-block path selects `J1` / `J2`, then maps them to the reference
// lane/block per RFC 9106 §3.4.
const refLane = r === 0 && s === 0 ? l : randH % lanes;
const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l);
const refBlock = laneLen * refLane + refPos;
// B[i][j] = G(B[i][j-1], B[l][z])
block(B, 256 * prev, 256 * refBlock, offset * 256, needXor);
}
function argon2(
type: Types,
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): TRet<Uint8Array> {
const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(
password,
salt,
type,
opts
);
// Pre-loop setup
// [address, input, zero_block] format so we can pass single U32 to block function
const address = new Uint32Array(3 * 256);
address[256 + 6] = mP;
address[256 + 8] = t;
address[256 + 10] = type;
for (let r = 0; r < t; r++) {
// RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy
// `0x10` keeps the older overwrite behavior used by the v16 test vectors.
const needXor = r !== 0 && version === 0x13;
address[256 + 0] = r;
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
address[256 + 4] = s;
// RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only
// in pass 0, slices 0 and 1; Argon2i uses it in every segment.
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
for (let l = 0; l < p; l++) {
address[256 + 2] = l;
address[256 + 12] = 0;
let startPos = 0;
if (r === 0 && s === 0) {
startPos = 2;
if (dataIndependent) {
address[256 + 12]++;
block(address, 256, 2 * 256, 0, false);
block(address, 0, 2 * 256, 0, false);
}
}
// current block postion
let offset = l * laneLen + s * segmentLen + startPos;
// previous block position
let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
perBlock();
processBlock(
B,
address,
l,
r,
s,
index,
laneLen,
segmentLen,
lanes,
offset,
prev,
dataIndependent,
needXor
);
}
}
}
}
clean(address);
return argon2Output(B, p, laneLen, dkLen);
}
/**
* Argon2d GPU-resistant version.
* @param password - password or input key material
* @param salt - unique salt value
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
* @returns Derived key bytes.
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
* @example
* Derive a key with Argon2d.
* ```ts
* argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
* ```
*/
export const argon2d = (
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): TRet<Uint8Array> => argon2(AT.Argond2d, password, salt, opts);
/**
* Argon2i side-channel-resistant version.
* @param password - password or input key material
* @param salt - unique salt value
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
* @returns Derived key bytes.
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
* @example
* Derive a key with Argon2i.
* ```ts
* argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
* ```
*/
export const argon2i = (
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): TRet<Uint8Array> => argon2(AT.Argon2i, password, salt, opts);
/**
* Argon2id, combining i+d, the most popular version from RFC 9106.
* @param password - password or input key material
* @param salt - unique salt value
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
* @returns Derived key bytes.
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
* @example
* Derive a key with Argon2id.
* ```ts
* argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
* ```
*/
export const argon2id = (
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): TRet<Uint8Array> => argon2(AT.Argon2id, password, salt, opts);
async function argon2Async(
type: Types,
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): Promise<TRet<Uint8Array>> {
const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick } =
argon2Init(password, salt, type, opts);
// Pre-loop setup
// [address, input, zero_block] format so we can pass single U32 to block function
const address = new Uint32Array(3 * 256);
address[256 + 6] = mP;
address[256 + 8] = t;
address[256 + 10] = type;
let ts = Date.now();
for (let r = 0; r < t; r++) {
// RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy
// `0x10` keeps the older overwrite behavior used by the v16 test vectors.
const needXor = r !== 0 && version === 0x13;
address[256 + 0] = r;
for (let s = 0; s < ARGON2_SYNC_POINTS; s++) {
address[256 + 4] = s;
// RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only
// in pass 0, slices 0 and 1; Argon2i uses it in every segment.
const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2);
for (let l = 0; l < p; l++) {
address[256 + 2] = l;
address[256 + 12] = 0;
let startPos = 0;
if (r === 0 && s === 0) {
startPos = 2;
if (dataIndependent) {
address[256 + 12]++;
block(address, 256, 2 * 256, 0, false);
block(address, 0, 2 * 256, 0, false);
}
}
// current block postion
let offset = l * laneLen + s * segmentLen + startPos;
// previous block position
let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1;
for (let index = startPos; index < segmentLen; index++, offset++, prev++) {
perBlock();
processBlock(
B,
address,
l,
r,
s,
index,
laneLen,
segmentLen,
lanes,
offset,
prev,
dataIndependent,
needXor
);
// Date.now() is not monotonic. If the clock goes backwards,
// still yield control.
const diff = Date.now() - ts;
if (!(diff >= 0 && diff < asyncTick)) {
await nextTick();
ts += diff;
}
}
}
}
}
clean(address);
return argon2Output(B, p, laneLen, dkLen);
}
/**
* Argon2d async GPU-resistant version.
* @param password - password or input key material
* @param salt - unique salt value
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
* @returns Promise resolving to derived key bytes.
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
* @example
* Derive a key with Argon2d asynchronously.
* ```ts
* await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
* ```
*/
export const argon2dAsync = (
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): Promise<TRet<Uint8Array>> => argon2Async(AT.Argond2d, password, salt, opts);
/**
* Argon2i async side-channel-resistant version.
* @param password - password or input key material
* @param salt - unique salt value
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
* @returns Promise resolving to derived key bytes.
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
* @example
* Derive a key with Argon2i asynchronously.
* ```ts
* await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
* ```
*/
export const argon2iAsync = (
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): Promise<TRet<Uint8Array>> => argon2Async(AT.Argon2i, password, salt, opts);
/**
* Argon2id async, combining i+d, the most popular version from RFC 9106.
* @param password - password or input key material
* @param salt - unique salt value
* @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}.
* @returns Promise resolving to derived key bytes.
* @throws If the Argon2 input or cost parameters are invalid. {@link Error}
* @example
* Derive a key with Argon2id asynchronously.
* ```ts
* await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 });
* ```
*/
export const argon2idAsync = (
password: TArg<KDFInput>,
salt: TArg<KDFInput>,
opts: TArg<ArgonOpts>
): Promise<TRet<Uint8Array>> => argon2Async(AT.Argon2id, password, salt, opts);
@@ -0,0 +1 @@
{"version":3,"file":"circle-percent.js","sources":["../../../src/icons/circle-percent.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name CirclePercent\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIgLz4KICA8cGF0aCBkPSJtMTUgOS02IDYiIC8+CiAgPHBhdGggZD0iTTkgOWguMDEiIC8+CiAgPHBhdGggZD0iTTE1IDE1aC4wMSIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/circle-percent\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 CirclePercent = createLucideIcon('CirclePercent', [\n ['circle', { cx: '12', cy: '12', r: '10', key: '1mglay' }],\n ['path', { d: 'm15 9-6 6', key: '1uzhvr' }],\n ['path', { d: 'M9 9h.01', key: '1q5me6' }],\n ['path', { d: 'M15 15h.01', key: 'lqbp3k' }],\n]);\n\nexport default CirclePercent;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAgB,iBAAiB,eAAiB,CAAA,CAAA,CAAA;AAAA,CACtD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CAAA,CACzD,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,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,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;AAC7C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"citrus.js","sources":["../../../src/icons/citrus.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Citrus\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjEuNjYgMTcuNjdhMS4wOCAxLjA4IDAgMCAxLS4wNCAxLjZBMTIgMTIgMCAwIDEgNC43MyAyLjM4YTEuMSAxLjEgMCAwIDEgMS42MS0uMDR6IiAvPgogIDxwYXRoIGQ9Ik0xOS42NSAxNS42NkE4IDggMCAwIDEgOC4zNSA0LjM0IiAvPgogIDxwYXRoIGQ9Im0xNCAxMC01LjUgNS41IiAvPgogIDxwYXRoIGQ9Ik0xNCAxNy44NVYxMEg2LjE1IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/citrus\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 Citrus = createLucideIcon('Citrus', [\n [\n 'path',\n {\n d: 'M21.66 17.67a1.08 1.08 0 0 1-.04 1.6A12 12 0 0 1 4.73 2.38a1.1 1.1 0 0 1 1.61-.04z',\n key: '4ite01',\n },\n ],\n ['path', { d: 'M19.65 15.66A8 8 0 0 1 8.35 4.34', key: '1gxipu' }],\n ['path', { d: 'm14 10-5.5 5.5', key: '92pfem' }],\n ['path', { d: 'M14 17.85V10H6.15', key: 'xqmtsk' }],\n]);\n\nexport default Citrus;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAS,iBAAiB,QAAU,CAAA,CAAA,CAAA;AAAA,CACxC,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;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,CAAA;AAAA,CAAA,CACA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAoC,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,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACjE,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAkB,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,CAC/C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAqB,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;AACpD,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,618 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
const validation_error_1 = require("./runtime/validation_error");
const ref_error_1 = require("./compile/ref_error");
const rules_1 = require("./compile/rules");
const compile_1 = require("./compile");
const codegen_2 = require("./compile/codegen");
const resolve_1 = require("./compile/resolve");
const dataType_1 = require("./compile/validate/dataType");
const util_1 = require("./compile/util");
const $dataRefSchema = require("./refs/data.json");
const uri_1 = require("./runtime/uri");
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
"validate",
"serialize",
"parse",
"wrapper",
"root",
"schema",
"keyword",
"pattern",
"formats",
"validate$data",
"func",
"obj",
"Error",
]);
const removedOptions = {
errorDataPath: "",
format: "`validateFormats: false` can be used instead.",
nullable: '"nullable" keyword is supported by default.',
jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
sourceCode: "Use option `code: {source: true}`",
strictDefaults: "It is default now, see option `strict`.",
strictKeywords: "It is default now, see option `strict`.",
uniqueItems: '"uniqueItems" keyword is always validated.',
unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
cache: "Map is used as cache, schema object as key.",
serialize: "Map is used as cache, schema object as key.",
ajvErrors: "It is default now.",
};
const deprecatedOptions = {
ignoreKeywordsWithRef: "",
jsPropertySyntax: "",
unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
const s = o.strict;
const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
return {
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
uriResolver: uriResolver,
};
}
class Ajv {
constructor(opts = {}) {
this.schemas = {};
this.refs = {};
this.formats = Object.create(null);
this._compilations = new Set();
this._loading = {};
this._cache = new Map();
opts = this.opts = { ...opts, ...requiredOptions(opts) };
const { es5, lines } = this.opts.code;
this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
this.logger = getLogger(opts.logger);
const formatOpt = opts.validateFormats;
opts.validateFormats = false;
this.RULES = (0, rules_1.getRules)();
checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
this._metaOpts = getMetaSchemaOptions.call(this);
if (opts.formats)
addInitialFormats.call(this);
this._addVocabularies();
this._addDefaultMetaSchema();
if (opts.keywords)
addInitialKeywords.call(this, opts.keywords);
if (typeof opts.meta == "object")
this.addMetaSchema(opts.meta);
addInitialSchemas.call(this);
opts.validateFormats = formatOpt;
}
_addVocabularies() {
this.addKeyword("$async");
}
_addDefaultMetaSchema() {
const { $data, meta, schemaId } = this.opts;
let _dataRefSchema = $dataRefSchema;
if (schemaId === "id") {
_dataRefSchema = { ...$dataRefSchema };
_dataRefSchema.id = _dataRefSchema.$id;
delete _dataRefSchema.$id;
}
if (meta && $data)
this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
}
defaultMeta() {
const { meta, schemaId } = this.opts;
return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
}
validate(schemaKeyRef, // key, ref or schema object
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
data // to be validated
) {
let v;
if (typeof schemaKeyRef == "string") {
v = this.getSchema(schemaKeyRef);
if (!v)
throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
}
else {
v = this.compile(schemaKeyRef);
}
const valid = v(data);
if (!("$async" in v))
this.errors = v.errors;
return valid;
}
compile(schema, _meta) {
const sch = this._addSchema(schema, _meta);
return (sch.validate || this._compileSchemaEnv(sch));
}
compileAsync(schema, meta) {
if (typeof this.opts.loadSchema != "function") {
throw new Error("options.loadSchema should be a function");
}
const { loadSchema } = this.opts;
return runCompileAsync.call(this, schema, meta);
async function runCompileAsync(_schema, _meta) {
await loadMetaSchema.call(this, _schema.$schema);
const sch = this._addSchema(_schema, _meta);
return sch.validate || _compileAsync.call(this, sch);
}
async function loadMetaSchema($ref) {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, { $ref }, true);
}
}
async function _compileAsync(sch) {
try {
return this._compileSchemaEnv(sch);
}
catch (e) {
if (!(e instanceof ref_error_1.default))
throw e;
checkLoaded.call(this, e);
await loadMissingSchema.call(this, e.missingSchema);
return _compileAsync.call(this, sch);
}
}
function checkLoaded({ missingSchema: ref, missingRef }) {
if (this.refs[ref]) {
throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
}
}
async function loadMissingSchema(ref) {
const _schema = await _loadSchema.call(this, ref);
if (!this.refs[ref])
await loadMetaSchema.call(this, _schema.$schema);
if (!this.refs[ref])
this.addSchema(_schema, ref, meta);
}
async function _loadSchema(ref) {
const p = this._loading[ref];
if (p)
return p;
try {
return await (this._loading[ref] = loadSchema(ref));
}
finally {
delete this._loading[ref];
}
}
}
// Adds schema to the instance
addSchema(schema, // If array is passed, `key` will be ignored
key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
_meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
_validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
) {
if (Array.isArray(schema)) {
for (const sch of schema)
this.addSchema(sch, undefined, _meta, _validateSchema);
return this;
}
let id;
if (typeof schema === "object") {
const { schemaId } = this.opts;
id = schema[schemaId];
if (id !== undefined && typeof id != "string") {
throw new Error(`schema ${schemaId} must be string`);
}
}
key = (0, resolve_1.normalizeId)(key || id);
this._checkUnique(key);
this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
return this;
}
// Add schema that will be used to validate other schemas
// options in META_IGNORE_OPTIONS are alway set to false
addMetaSchema(schema, key, // schema key
_validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
) {
this.addSchema(schema, key, true, _validateSchema);
return this;
}
// Validate schema against its meta-schema
validateSchema(schema, throwOrLogError) {
if (typeof schema == "boolean")
return true;
let $schema;
$schema = schema.$schema;
if ($schema !== undefined && typeof $schema != "string") {
throw new Error("$schema must be a string");
}
$schema = $schema || this.opts.defaultMeta || this.defaultMeta();
if (!$schema) {
this.logger.warn("meta-schema not available");
this.errors = null;
return true;
}
const valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
const message = "schema is invalid: " + this.errorsText();
if (this.opts.validateSchema === "log")
this.logger.error(message);
else
throw new Error(message);
}
return valid;
}
// Get compiled schema by `key` or `ref`.
// (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
getSchema(keyRef) {
let sch;
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
keyRef = sch;
if (sch === undefined) {
const { schemaId } = this.opts;
const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
sch = compile_1.resolveSchema.call(this, root, keyRef);
if (!sch)
return;
this.refs[keyRef] = sch;
}
return (sch.validate || this._compileSchemaEnv(sch));
}
// Remove cached schema(s).
// If no parameter is passed all schemas but meta-schemas are removed.
// If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
// Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
this._removeAllSchemas(this.schemas, schemaKeyRef);
this._removeAllSchemas(this.refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case "undefined":
this._removeAllSchemas(this.schemas);
this._removeAllSchemas(this.refs);
this._cache.clear();
return this;
case "string": {
const sch = getSchEnv.call(this, schemaKeyRef);
if (typeof sch == "object")
this._cache.delete(sch.schema);
delete this.schemas[schemaKeyRef];
delete this.refs[schemaKeyRef];
return this;
}
case "object": {
const cacheKey = schemaKeyRef;
this._cache.delete(cacheKey);
let id = schemaKeyRef[this.opts.schemaId];
if (id) {
id = (0, resolve_1.normalizeId)(id);
delete this.schemas[id];
delete this.refs[id];
}
return this;
}
default:
throw new Error("ajv.removeSchema: invalid parameter");
}
}
// add "vocabulary" - a collection of keywords
addVocabulary(definitions) {
for (const def of definitions)
this.addKeyword(def);
return this;
}
addKeyword(kwdOrDef, def // deprecated
) {
let keyword;
if (typeof kwdOrDef == "string") {
keyword = kwdOrDef;
if (typeof def == "object") {
this.logger.warn("these parameters are deprecated, see docs for addKeyword");
def.keyword = keyword;
}
}
else if (typeof kwdOrDef == "object" && def === undefined) {
def = kwdOrDef;
keyword = def.keyword;
if (Array.isArray(keyword) && !keyword.length) {
throw new Error("addKeywords: keyword must be string or non-empty array");
}
}
else {
throw new Error("invalid addKeywords parameters");
}
checkKeyword.call(this, keyword, def);
if (!def) {
(0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
return this;
}
keywordMetaschema.call(this, def);
const definition = {
...def,
type: (0, dataType_1.getJSONTypes)(def.type),
schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
};
(0, util_1.eachItem)(keyword, definition.type.length === 0
? (k) => addRule.call(this, k, definition)
: (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
return this;
}
getKeyword(keyword) {
const rule = this.RULES.all[keyword];
return typeof rule == "object" ? rule.definition : !!rule;
}
// Remove keyword
removeKeyword(keyword) {
// TODO return type should be Ajv
const { RULES } = this;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
for (const group of RULES.rules) {
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
if (i >= 0)
group.rules.splice(i, 1);
}
return this;
}
// Add format
addFormat(name, format) {
if (typeof format == "string")
format = new RegExp(format);
this.formats[name] = format;
return this;
}
errorsText(errors = this.errors, // optional array of validation errors
{ separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
) {
if (!errors || errors.length === 0)
return "No errors";
return errors
.map((e) => `${dataVar}${e.instancePath} ${e.message}`)
.reduce((text, msg) => text + separator + msg);
}
$dataMetaSchema(metaSchema, keywordsJsonPointers) {
const rules = this.RULES.all;
metaSchema = JSON.parse(JSON.stringify(metaSchema));
for (const jsonPointer of keywordsJsonPointers) {
const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
let keywords = metaSchema;
for (const seg of segments)
keywords = keywords[seg];
for (const key in rules) {
const rule = rules[key];
if (typeof rule != "object")
continue;
const { $data } = rule.definition;
const schema = keywords[key];
if ($data && schema)
keywords[key] = schemaOrData(schema);
}
}
return metaSchema;
}
_removeAllSchemas(schemas, regex) {
for (const keyRef in schemas) {
const sch = schemas[keyRef];
if (!regex || regex.test(keyRef)) {
if (typeof sch == "string") {
delete schemas[keyRef];
}
else if (sch && !sch.meta) {
this._cache.delete(sch.schema);
delete schemas[keyRef];
}
}
}
}
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
let id;
const { schemaId } = this.opts;
if (typeof schema == "object") {
id = schema[schemaId];
}
else {
if (this.opts.jtd)
throw new Error("schema must be object");
else if (typeof schema != "boolean")
throw new Error("schema must be object or boolean");
}
let sch = this._cache.get(schema);
if (sch !== undefined)
return sch;
baseId = (0, resolve_1.normalizeId)(id || baseId);
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
this._cache.set(sch.schema, sch);
if (addSchema && !baseId.startsWith("#")) {
// TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
if (baseId)
this._checkUnique(baseId);
this.refs[baseId] = sch;
}
if (validateSchema)
this.validateSchema(schema, true);
return sch;
}
_checkUnique(id) {
if (this.schemas[id] || this.refs[id]) {
throw new Error(`schema with key or id "${id}" already exists`);
}
}
_compileSchemaEnv(sch) {
if (sch.meta)
this._compileMetaSchema(sch);
else
compile_1.compileSchema.call(this, sch);
/* istanbul ignore if */
if (!sch.validate)
throw new Error("ajv implementation error");
return sch.validate;
}
_compileMetaSchema(sch) {
const currentOpts = this.opts;
this.opts = this._metaOpts;
try {
compile_1.compileSchema.call(this, sch);
}
finally {
this.opts = currentOpts;
}
}
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
for (const key in checkOpts) {
const opt = key;
if (opt in options)
this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
}
}
function getSchEnv(keyRef) {
keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
const optsSchemas = this.opts.schemas;
if (!optsSchemas)
return;
if (Array.isArray(optsSchemas))
this.addSchema(optsSchemas);
else
for (const key in optsSchemas)
this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
for (const name in this.opts.formats) {
const format = this.opts.formats[name];
if (format)
this.addFormat(name, format);
}
}
function addInitialKeywords(defs) {
if (Array.isArray(defs)) {
this.addVocabulary(defs);
return;
}
this.logger.warn("keywords option as map is deprecated, pass array");
for (const keyword in defs) {
const def = defs[keyword];
if (!def.keyword)
def.keyword = keyword;
this.addKeyword(def);
}
}
function getMetaSchemaOptions() {
const metaOpts = { ...this.opts };
for (const opt of META_IGNORE_OPTIONS)
delete metaOpts[opt];
return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
if (logger === false)
return noLogs;
if (logger === undefined)
return console;
if (logger.log && logger.warn && logger.error)
return logger;
throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
const { RULES } = this;
(0, util_1.eachItem)(keyword, (kwd) => {
if (RULES.keywords[kwd])
throw new Error(`Keyword ${kwd} is already defined`);
if (!KEYWORD_NAME.test(kwd))
throw new Error(`Keyword ${kwd} has invalid name`);
});
if (!def)
return;
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function');
}
}
function addRule(keyword, definition, dataType) {
var _a;
const post = definition === null || definition === void 0 ? void 0 : definition.post;
if (dataType && post)
throw new Error('keyword with "post" flag cannot have "type"');
const { RULES } = this;
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.rules.push(ruleGroup);
}
RULES.keywords[keyword] = true;
if (!definition)
return;
const rule = {
keyword,
definition: {
...definition,
type: (0, dataType_1.getJSONTypes)(definition.type),
schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
},
};
if (definition.before)
addBeforeRule.call(this, ruleGroup, rule, definition.before);
else
ruleGroup.rules.push(rule);
RULES.all[keyword] = rule;
(_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule);
}
else {
ruleGroup.rules.push(rule);
this.logger.warn(`rule ${before} is not defined`);
}
}
function keywordMetaschema(def) {
let { metaSchema } = def;
if (metaSchema === undefined)
return;
if (def.$data && this.opts.$data)
metaSchema = schemaOrData(metaSchema);
def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
$ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map
@@ -0,0 +1,157 @@
"use strict";
var _utils = require("./utils.js");
const defineType = (0, _utils.defineAliasedType)("JSX");
defineType("JSXAttribute", {
visitor: ["name", "value"],
aliases: ["Immutable"],
fields: {
name: {
validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXNamespacedName")
},
value: {
optional: true,
validate: (0, _utils.assertNodeType)("JSXElement", "JSXFragment", "StringLiteral", "JSXExpressionContainer")
}
}
});
defineType("JSXClosingElement", {
visitor: ["name"],
aliases: ["Immutable"],
fields: {
name: {
validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName")
}
}
});
defineType("JSXElement", {
builder: ["openingElement", "closingElement", "children", "selfClosing"],
visitor: ["openingElement", "children", "closingElement"],
aliases: ["Immutable", "Expression"],
fields: Object.assign({
openingElement: {
validate: (0, _utils.assertNodeType)("JSXOpeningElement")
},
closingElement: {
optional: true,
validate: (0, _utils.assertNodeType)("JSXClosingElement")
},
children: (0, _utils.validateArrayOfType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment")
}, {
selfClosing: {
validate: (0, _utils.assertValueType)("boolean"),
optional: true
}
})
});
defineType("JSXEmptyExpression", {});
defineType("JSXExpressionContainer", {
visitor: ["expression"],
aliases: ["Immutable"],
fields: {
expression: {
validate: (0, _utils.assertNodeType)("Expression", "JSXEmptyExpression")
}
}
});
defineType("JSXSpreadChild", {
visitor: ["expression"],
aliases: ["Immutable"],
fields: {
expression: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
defineType("JSXIdentifier", {
builder: ["name"],
fields: {
name: {
validate: (0, _utils.assertValueType)("string")
}
}
});
defineType("JSXMemberExpression", {
visitor: ["object", "property"],
fields: {
object: {
validate: (0, _utils.assertNodeType)("JSXMemberExpression", "JSXIdentifier")
},
property: {
validate: (0, _utils.assertNodeType)("JSXIdentifier")
}
}
});
defineType("JSXNamespacedName", {
visitor: ["namespace", "name"],
fields: {
namespace: {
validate: (0, _utils.assertNodeType)("JSXIdentifier")
},
name: {
validate: (0, _utils.assertNodeType)("JSXIdentifier")
}
}
});
defineType("JSXOpeningElement", {
builder: ["name", "attributes", "selfClosing"],
visitor: ["name", "typeParameters", "typeArguments", "attributes"],
aliases: ["Immutable"],
fields: Object.assign({
name: {
validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression", "JSXNamespacedName")
},
selfClosing: {
default: false
},
attributes: (0, _utils.validateArrayOfType)("JSXAttribute", "JSXSpreadAttribute"),
typeArguments: {
validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"),
optional: true
}
}, {
typeParameters: {
validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"),
optional: true
}
})
});
defineType("JSXSpreadAttribute", {
visitor: ["argument"],
fields: {
argument: {
validate: (0, _utils.assertNodeType)("Expression")
}
}
});
defineType("JSXText", {
aliases: ["Immutable"],
builder: ["value"],
fields: {
value: {
validate: (0, _utils.assertValueType)("string")
}
}
});
defineType("JSXFragment", {
builder: ["openingFragment", "closingFragment", "children"],
visitor: ["openingFragment", "children", "closingFragment"],
aliases: ["Immutable", "Expression"],
fields: {
openingFragment: {
validate: (0, _utils.assertNodeType)("JSXOpeningFragment")
},
closingFragment: {
validate: (0, _utils.assertNodeType)("JSXClosingFragment")
},
children: (0, _utils.validateArrayOfType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment")
}
});
defineType("JSXOpeningFragment", {
aliases: ["Immutable"]
});
defineType("JSXClosingFragment", {
aliases: ["Immutable"]
});
//# sourceMappingURL=jsx.js.map
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"2":"_J"},C:{"2":"_S"},D:{"2":"_Q"},E:{"2":"_R"},F:{"2":"_c"},G:{"2":"_M"},H:{"2":"1D"},I:{"2":"_P"},J:{"2":"_B"},K:{"2":"_N"},L:{"2":"I"},M:{"2":"YC"},N:{"2":"_A"},O:{"2":"bC"},P:{"2":"_F"},Q:{"2":"JE"},R:{"2":"KE"},S:{"2":"_C"}},B:5,C:"Media Queries: scripting media feature",D:false};
@@ -0,0 +1,178 @@
'use strict'
const test = require('tape')
const fastURI = require('..')
test('parse preserves reserved path escapes as data', (t) => {
const components = fastURI.parse('http://example.com/a%2Fb/public/%2e%2e/admin')
t.equal(components.path, '/a%2Fb/public/%2E%2E/admin')
t.end()
})
test('normalize preserves percent-encoded path separators and dot segments', (t) => {
t.equal(
fastURI.normalize('http://example.com/public/%2e%2e/admin'),
'http://example.com/public/%2E%2E/admin'
)
t.equal(
fastURI.normalize('http://example.com/a%2Fb'),
'http://example.com/a%2Fb'
)
t.end()
})
test('equal does not treat reserved path escapes as live path syntax', (t) => {
t.equal(
fastURI.equal('http://example.com/public/%2e%2e/admin', 'http://example.com/admin', {}),
false
)
t.equal(
fastURI.equal('http://example.com/a%2Fb', 'http://example.com/a/b', {}),
false
)
t.end()
})
test('serialize preserves literal RFC 3986 reserved path characters', (t) => {
// GHSA-7mh8-fcmq-x23c: literal reserved path chars must not be rewritten to
// percent escapes by the escape()-style safe set.
const cases = [
'http://example.com/a;b',
'http://example.com/a=b',
'http://example.com/a&b',
'http://example.com/a$b',
'http://example.com/a:b',
'http://example.com/a@b'
]
t.plan(cases.length)
cases.forEach((uri) => {
t.equal(fastURI.serialize(fastURI.parse(uri)), uri, uri)
})
t.end()
})
test('serialize preserves existing reserved path escapes as data', (t) => {
// GHSA-7mh8-fcmq-x23c: an existing %3A escape must stay %3A instead of being
// rewritten into a live colon.
const cases = [
'http://example.com/a%3Ab',
'http://example.com/a%3Bb',
'http://example.com/a%3D%3D'
]
t.plan(cases.length)
cases.forEach((uri) => {
t.equal(fastURI.serialize(fastURI.parse(uri)), uri, uri)
})
t.end()
})
test('serialize keeps path-noscheme colon escaping', (t) => {
// Without a scheme a literal colon would be reparsed as a scheme separator,
// so it must stay percent-escaped while an existing %3A is preserved.
t.equal(fastURI.serialize({ path: 'foo:bar' }), 'foo%3Abar')
t.equal(fastURI.serialize({ path: 'a%3Ab' }), 'a%3Ab')
t.end()
})
test('hostname normalization never decodes an escape more than once', (t) => {
const encodedLocalhost = 'http://%256c%256f%2563%2561%256c%2568%256f%2573%2574/'
const encodedLoopback = '//127%252e0%252e0%252e1/private'
const encodedMetadataAddress = '//169%252E254%252E169%252E254/latest/meta-data/'
t.equal(fastURI.normalize(encodedLocalhost), encodedLocalhost, 'nested hostname letters remain encoded')
t.equal(fastURI.normalize(encodedLoopback), encodedLoopback, 'nested IPv4 dots remain encoded')
t.equal(
fastURI.resolve('https://safe.example/', encodedLoopback),
'https://127%252e0%252e0%252e1/private',
'resolve does not turn nested dots into a loopback address'
)
t.equal(
fastURI.resolve('https://allowed.com/api/v1/', encodedMetadataAddress),
'https://169%252e254%252e169%252e254/latest/meta-data/',
'resolve does not turn nested dots into a metadata address'
)
t.equal(
fastURI.normalize('http://allowed.com%255Cevil.com/'),
'http://allowed.com%255Cevil.com/',
'normalize does not activate a nested backslash'
)
t.equal(
fastURI.serialize({ scheme: 'http', host: '%256cocalhost', path: '/' }),
'http://%256cocalhost/',
'component serialization preserves an encoded percent sign'
)
t.equal(
fastURI.equal(encodedLocalhost, 'http://localhost/', {}),
false,
'nested escapes do not compare equal to their twice-decoded target'
)
t.end()
})
test('hostname normalization decodes only current unreserved escapes', (t) => {
t.equal(fastURI.normalize('x://%6cocalhost/'), 'x://localhost/', 'a current unreserved escape is decoded')
t.equal(fastURI.normalize('x://%256cocalhost/'), 'x://%256cocalhost/', 'an encoded percent is preserved')
t.equal(fastURI.normalize('x://host%2540evil/'), 'x://host%2540evil/', 'a nested authority delimiter stays inert')
t.equal(fastURI.normalize('x://%2525/'), 'x://%2525/', 'nested encoded percent signs stay encoded')
t.end()
})
test('scheme-relative hostname normalization folds decoded ASCII case', (t) => {
const encodedHost = '//%41.com'
const normalizedHost = fastURI.normalize(encodedHost)
const encodedMetadata = '//%4Detadata.internal/private'
const literalMetadata = '//metadata.internal/private'
t.equal(fastURI.parse(encodedHost).host, 'a.com', 'parse folds an encoded uppercase host letter')
t.equal(normalizedHost, '//a.com', 'normalize emits a lowercase host')
t.equal(fastURI.normalize(normalizedHost), normalizedHost, 'host normalization is idempotent')
t.equal(fastURI.equal(encodedHost, '//a.com'), true, 'encoded and literal host spellings compare equal')
t.equal(fastURI.equal(encodedMetadata, literalMetadata), true, 'encoded metadata host compares equal')
t.equal(
fastURI.resolve('x://trusted.example/', encodedMetadata),
fastURI.resolve('x://trusted.example/', literalMetadata),
'encoded and literal metadata hosts resolve identically'
)
t.equal(
fastURI.normalize('//example.com%2fpath'),
'//example.com%2Fpath',
'reserved host escapes remain encoded with uppercase hex'
)
t.equal(fastURI.normalize('//%2541.com'), '//%2541.com', 'nested host escapes are not decoded twice')
t.equal(fastURI.equal('//User@%41.com/path', '//user@a.com/path'), false, 'userinfo remains case-sensitive')
t.equal(fastURI.equal('//%41.com/Path', '//a.com/path'), false, 'path remains case-sensitive')
t.equal(fastURI.equal('//%41.com/?Token=Value', '//a.com/?token=value'), false, 'query remains case-sensitive')
t.end()
})
test('host normalization applies to schemes that skip path normalization', (t) => {
const encodedHost = 'mailto://%41.com'
const literalHost = 'mailto://a.com'
t.equal(fastURI.parse(encodedHost).host, fastURI.parse(literalHost).host, 'parse results have consistent hosts')
t.equal(fastURI.normalize(encodedHost), fastURI.normalize(literalHost), 'normalize results are consistent')
t.equal(fastURI.equal(encodedHost, literalHost), true, 'encoded and literal hosts compare equal')
t.end()
})
test('host conversion failures are not treated as comparable URLs', (t) => {
const malformedHost = 'http://trusted.test%2540evil.test/'
t.equal(fastURI.normalize(malformedHost), malformedHost, 'normalization preserves the failing input')
t.equal(fastURI.equal(malformedHost, malformedHost, {}), false, 'equal rejects a failed host conversion')
t.throws(
() => fastURI.resolve(malformedHost, 'child', { domainHost: true }),
/Host's domain name can not be converted to ASCII/,
'resolve propagates a host conversion failure'
)
t.end()
})
@@ -0,0 +1,4 @@
// @ts-ignore TS6133
import { test } from "vitest";
test("masking test", () => {});
@@ -0,0 +1 @@
{"version":3,"file":"not-found.cjs","names":[],"sources":["../../src/not-found.tsx"],"sourcesContent":["import * as React from 'react'\nimport { isNotFound } from '@tanstack/router-core'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { useStore } from '@tanstack/react-store'\nimport { CatchBoundary } from './CatchBoundary'\nimport { useRouter } from './useRouter'\nimport type { ErrorInfo } from 'react'\nimport type { NotFoundError } from '@tanstack/router-core'\n\nexport function CatchNotFound(props: {\n fallback?: (error: NotFoundError) => React.ReactElement\n onCatch?: (error: Error, errorInfo: ErrorInfo) => void\n children: React.ReactNode\n}) {\n const router = useRouter()\n\n if (isServer ?? router.isServer) {\n const pathname = router.stores.location.get().pathname\n const status = router.stores.status.get()\n const resetKey = `not-found-${pathname}-${status}`\n\n return (\n <CatchBoundary\n getResetKey={() => resetKey}\n onCatch={(error, errorInfo) => {\n if (isNotFound(error)) {\n props.onCatch?.(error, errorInfo)\n } else {\n throw error\n }\n }}\n errorComponent={({ error }) => {\n if (isNotFound(error)) {\n return props.fallback?.(error)\n } else {\n throw error\n }\n }}\n >\n {props.children}\n </CatchBoundary>\n )\n }\n\n // TODO: Some way for the user to programmatically reset the not-found boundary?\n // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static\n const pathname = useStore(\n router.stores.location,\n (location) => location.pathname,\n )\n // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static\n const status = useStore(router.stores.status, (status) => status)\n const resetKey = `not-found-${pathname}-${status}`\n\n return (\n <CatchBoundary\n getResetKey={() => resetKey}\n onCatch={(error, errorInfo) => {\n if (isNotFound(error)) {\n props.onCatch?.(error, errorInfo)\n } else {\n throw error\n }\n }}\n errorComponent={({ error }) => {\n if (isNotFound(error)) {\n return props.fallback?.(error)\n } else {\n throw error\n }\n }}\n >\n {props.children}\n </CatchBoundary>\n )\n}\n\nexport function DefaultGlobalNotFound() {\n return <p>Not Found</p>\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,cAAc,OAI3B;CACD,MAAM,SAAS,kBAAA,WAAW;AAE1B,KAAI,+BAAA,YAAY,OAAO,UAAU;EAG/B,MAAM,WAAW,aAFA,OAAO,OAAO,SAAS,KAAK,CAAC,SAEP,GADxB,OAAO,OAAO,OAAO,KAAK;AAGzC,SACE,iBAAA,GAAA,kBAAA,KAAC,sBAAA,eAAD;GACE,mBAAmB;GACnB,UAAU,OAAO,cAAc;AAC7B,SAAA,GAAA,sBAAA,YAAe,MAAM,CACnB,OAAM,UAAU,OAAO,UAAU;QAEjC,OAAM;;GAGV,iBAAiB,EAAE,YAAY;AAC7B,SAAA,GAAA,sBAAA,YAAe,MAAM,CACnB,QAAO,MAAM,WAAW,MAAM;QAE9B,OAAM;;aAIT,MAAM;GACO,CAAA;;CAYpB,MAAM,WAAW,cAAA,GAAA,sBAAA,UALf,OAAO,OAAO,WACb,aAAa,SAAS,SACxB,CAGsC,IAAA,GAAA,sBAAA,UADf,OAAO,OAAO,SAAS,WAAW,OAAO;AAGjE,QACE,iBAAA,GAAA,kBAAA,KAAC,sBAAA,eAAD;EACE,mBAAmB;EACnB,UAAU,OAAO,cAAc;AAC7B,QAAA,GAAA,sBAAA,YAAe,MAAM,CACnB,OAAM,UAAU,OAAO,UAAU;OAEjC,OAAM;;EAGV,iBAAiB,EAAE,YAAY;AAC7B,QAAA,GAAA,sBAAA,YAAe,MAAM,CACnB,QAAO,MAAM,WAAW,MAAM;OAE9B,OAAM;;YAIT,MAAM;EACO,CAAA;;AAIpB,SAAgB,wBAAwB;AACtC,QAAO,iBAAA,GAAA,kBAAA,KAAC,KAAD,EAAA,UAAG,aAAa,CAAA"}
@@ -0,0 +1 @@
module.exports={C:{"56":0.00466,"110":0.00466,"120":0.0931,"121":0.19551,"136":0.00466,"140":0.02328,"147":0.00466,"150":0.00931,"152":0.00931,"153":0.02793,"154":0.19086,"155":0.57722,"156":0.59584,"157":0.02328,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 111 112 113 114 115 116 117 118 119 122 123 124 125 126 127 128 129 130 131 132 133 134 135 137 138 139 141 142 143 144 145 146 148 149 151 158 159 160 3.5 3.6"},D:{"63":0.00466,"75":0.00466,"76":0.00931,"77":0.00466,"91":0.05121,"92":0.00466,"93":0.00931,"101":0.01397,"103":0.23741,"104":0.1862,"105":0.18155,"106":0.19086,"107":0.15362,"108":0.17689,"109":0.25603,"110":0.1862,"111":0.16758,"112":0.17224,"114":0.00466,"116":0.38637,"117":0.16758,"118":0.31654,"119":0.21413,"120":0.3724,"122":0.09776,"123":0.00931,"124":0.16758,"125":0.00466,"126":0.03259,"128":0.01862,"129":0.10707,"130":0.00931,"131":0.36309,"132":0.00466,"133":0.45619,"134":0.0931,"135":0.07914,"136":0.11172,"137":0.0931,"138":0.28861,"139":0.08379,"140":0.11172,"141":0.12569,"142":0.42361,"143":0.01397,"144":0.1862,"145":0.15827,"146":0.05586,"147":0.02328,"148":0.50274,"149":0.64705,"150":3.94744,"151":5.66048,"152":8.85381,"153":4.98551,"154":1.15444,"155":0.07448,"156":0.02328,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 64 65 66 67 68 69 70 71 72 73 74 78 79 80 81 83 84 85 86 87 88 89 90 94 95 96 97 98 99 100 102 113 115 121 127 157"},F:{"101":0.00931,"102":0.00466,"127":0.00466,"134":0.21413,"135":0.5074,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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 60 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 131 132 133 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"18":0.00466,"92":0.00931,"109":0.01397,"114":0.01397,"119":0.23741,"120":0.07448,"127":0.03724,"130":0.01397,"135":0.00466,"140":0.00466,"143":0.02328,"144":0.00466,"145":0.01397,"147":0.00931,"148":0.01862,"149":0.02793,"150":0.07448,"151":0.40033,"152":2.69525,"153":2.25768,"154":0.39102,_:"12 13 14 15 16 17 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 112 113 115 116 117 118 121 122 123 124 125 126 128 129 131 132 133 134 136 137 138 139 141 142 146"},E:{"27":0.12569,_:"4 5 6 7 8 9 10 11 12 13 14 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 13.1 15.1 15.2-15.3 15.4 15.5 16.0 16.1 16.3 16.4 16.5 17.0 17.2 17.3 18.2 26.1 27.1 TP","14.1":0.00931,"15.6":0.04655,"16.2":0.00466,"16.6":0.02328,"17.1":0.08845,"17.4":0.00931,"17.5":0.00931,"17.6":0.08845,"18.0":0.00466,"18.1":0.00931,"18.3":0.01397,"18.4":0.00466,"18.5-18.7":0.01862,"26.0":0.01397,"26.2":0.00931,"26.3":0.00931,"26.4":0.02793,"26.5":0.61446,"26.6":0.42361,"27.2":0.00466},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00167,"5.0-5.1":0.00167,"6.0-6.1":0,"7.0-7.1":0.00334,"8.1-8.4":0,"9.0-9.2":0,"9.3":0,"10.0-10.2":0,"10.3":0.01671,"11.0-11.2":0.00167,"11.3-11.4":0.00334,"12.0-12.1":0,"12.2-12.5":0.04343,"13.0-13.1":0,"13.2":0.00835,"13.3":0,"13.4-13.7":0.00167,"14.0-14.4":0.00668,"14.5-14.8":0.01002,"15.0-15.1":0.01002,"15.2-15.3":0.00668,"15.4":0.00835,"15.5":0.01002,"15.6-15.8":0.21717,"16.0":0.01671,"16.1":0.03007,"16.2":0.01671,"16.3":0.03675,"16.4":0.00835,"16.5":0.01336,"16.6-16.7":0.30237,"17.0":0.01169,"17.1":0.01671,"17.2":0.01671,"17.3":0.02506,"17.4":0.03508,"17.5":0.06849,"17.6-17.7":0.17708,"18.0":0.03675,"18.1":0.0735,"18.2":0.10023,"18.3":0.17374,"18.4":0.10858,"18.5-18.7":2.24353,"26.0":0.10858,"26.1":0.11026,"26.2":0.28733,"26.3":0.31072,"26.4":0.22719,"26.5":1.52186,"26.6":9.39007,"27.0":0.72,"27.1":0,"27.2":0.01838},P:{"22":0.00894,"24":0.00894,"25":0.01789,"26":0.01789,"27":0.01789,"28":0.04472,"29":0.1431,"30":2.59376,_:"4 20 21 23 5.0-5.4 6.2-6.4 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0","7.2-7.4":0.12522,"8.2":0.00894},I:{"0":0.00534,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0,"4.4":0,"4.4.3-4.4.4":0},K:{"0":0.1336,_:"10 11 12 11.1 11.5 12.1"},A:{_:"6 7 8 9 10 11 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},L:{"0":35.47119},R:{_:"0"},M:{"0":0.41683},Q:{_:"14.9"},O:{"0":0.01069},H:{all:0}};
@@ -0,0 +1 @@
{"version":3,"file":"style-set.mjs","sources":["../../../../src/render/dom/style-set.ts"],"sourcesContent":["import { AnyResolvedKeyframe } from \"../../animation/types\"\nimport { isCSSVar } from \"./is-css-var\"\n\nexport function setStyle(\n element: HTMLElement | SVGElement,\n name: string,\n value: AnyResolvedKeyframe\n) {\n isCSSVar(name)\n ? element.style.setProperty(name, value as string)\n : (element.style[name as any] = value as string)\n}\n"],"names":[],"mappings":";;SAGgB,QAAQ,CACpB,OAAiC,EACjC,IAAY,EACZ,KAA0B,EAAA;IAE1B,QAAQ,CAAC,IAAI;UACP,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,KAAe;WAC9C,OAAO,CAAC,KAAK,CAAC,IAAW,CAAC,GAAG,KAAe,CAAC;AACxD;;;;"}
@@ -0,0 +1,445 @@
import { expect, test } from "vitest";
import * as z from "../../index.js";
import { compile, compileFn } from "../compile.js";
// Generative differential: random schemas over the compiled node types, a valid value for each, single corruptions of that value, and the assertion that the interpreter and the compiled schema agree on the verdict, the output, the issues and how often user callbacks ran. A fixture suite covers the compositions somebody wrote down; this covers the ones nobody did. Seeds are fixed, so a failure names the seed and the schema it built.
function mulberry32(seed: number): () => number {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
interface Gen {
schema: z.ZodType;
desc: string;
valid: () => unknown;
// one corruption of a valid value; not always rejected (a loose object absorbs an extra key), and both sides must agree either way
corrupt: (v: unknown) => unknown;
// this node itself has no fast emitter and compiles through the runtime
island: boolean;
}
interface Ctx {
rand: () => number;
// runs per generated callback, so the two-run bound holds for each one rather than for the sum
calls: Map<number, number>;
nextCallback: number;
}
function count(c: Ctx, id: number): void {
c.calls.set(id, (c.calls.get(id) ?? 0) + 1);
}
const pick = <T>(c: Ctx, xs: readonly T[]): T => xs[Math.floor(c.rand() * xs.length)]!;
const int = (c: Ctx, lo: number, hi: number): number => lo + Math.floor(c.rand() * (hi - lo + 1));
const JUNK = [42, "x", null, undefined, true, [], {}, -0, Number.NaN] as const;
function leaf(c: Ctx): Gen {
switch (int(c, 0, 7)) {
case 0: {
const min = int(c, 0, 3);
return {
schema: z.string().min(min),
desc: `string.min(${min})`,
valid: () => "x".repeat(min + int(c, 0, 2)),
corrupt: () => (c.rand() < 0.5 ? 42 : "x".repeat(Math.max(0, min - 1))),
island: false,
};
}
case 1:
return {
schema: z.email(),
desc: "email",
valid: () => "a@b.co",
corrupt: () => (c.rand() < 0.5 ? "nope" : 1),
island: false,
};
case 2: {
const lo = int(c, -5, 0);
const hi = int(c, 1, 5);
return {
schema: z.number().int().min(lo).max(hi),
desc: `int[${lo},${hi}]`,
valid: () => int(c, lo, hi),
corrupt: () => pick(c, [hi + 1, lo - 1, 1.5, "1"]),
island: false,
};
}
case 3:
return {
schema: z.boolean(),
desc: "boolean",
valid: () => c.rand() < 0.5,
corrupt: () => pick(c, ["true", 0, null]),
island: false,
};
case 4: {
const lit = pick(c, ["a", 1, true] as const);
return {
schema: z.literal(lit),
desc: `literal(${JSON.stringify(lit)})`,
valid: () => lit,
corrupt: () => pick(c, ["b", 2, false]),
island: false,
};
}
case 5:
return {
schema: z.enum(["a", "b", "c"]),
desc: "enum",
valid: () => pick(c, ["a", "b", "c"]),
corrupt: () => pick(c, ["d", 2, null]),
island: false,
};
case 6: {
const id = c.nextCallback++;
return {
schema: z.number().superRefine((v, ctx) => {
count(c, id);
if (v < 0) ctx.addIssue({ code: "custom", message: "negative" });
}),
desc: "number.superRefine",
valid: () => int(c, 0, 9),
corrupt: () => pick(c, [-1, "x"]),
island: false,
};
}
default: {
const id = c.nextCallback++;
return {
schema: z.string().transform((s) => {
count(c, id);
return s.length;
}),
desc: "string.transform",
valid: () => "y".repeat(int(c, 0, 3)),
corrupt: () => 42,
island: false,
};
}
}
}
function wrap(c: Ctx, inner: Gen): Gen {
switch (int(c, 0, 4)) {
case 0:
return {
...inner,
schema: inner.schema.optional(),
desc: `${inner.desc}.optional`,
valid: () => (c.rand() < 0.3 ? undefined : inner.valid()),
island: false,
};
case 1:
return {
...inner,
schema: inner.schema.nullable(),
desc: `${inner.desc}.nullable`,
valid: () => (c.rand() < 0.3 ? null : inner.valid()),
island: false,
};
case 2: {
const dflt = inner.valid();
return {
...inner,
schema: inner.schema.default(dflt as never),
desc: `${inner.desc}.default`,
valid: () => (c.rand() < 0.3 ? undefined : inner.valid()),
island: false,
};
}
case 3:
return { ...inner, schema: inner.schema.readonly(), desc: `${inner.desc}.readonly`, island: false };
default:
return {
...inner,
schema: inner.schema.optional().nonoptional(),
desc: `${inner.desc}.optional.nonoptional`,
corrupt: (v) => (c.rand() < 0.5 ? undefined : inner.corrupt(v)),
island: false,
};
}
}
function container(c: Ctx, depth: number): Gen {
const child = () => gen(c, depth - 1);
switch (int(c, 0, 8)) {
case 0:
case 1: {
const n = int(c, 1, 4);
const entries = Array.from({ length: n }, (_, i) => [`k${i}`, child(), c.rand() < 0.3] as const);
const shape = Object.fromEntries(entries.map(([k, g, opt]) => [k, opt ? g.schema.optional() : g.schema]));
const mode = pick(c, ["plain", "strict", "loose", "catchall"] as const);
const schema =
mode === "strict"
? z.strictObject(shape)
: mode === "loose"
? z.looseObject(shape)
: mode === "catchall"
? z.object(shape).catchall(z.number())
: z.object(shape);
const valid = () => {
const o: Record<string, unknown> = {};
for (const [k, g, opt] of entries) if (!opt || c.rand() < 0.6) o[k] = g.valid();
if (mode === "catchall" && c.rand() < 0.5) o.extra = 1;
return o;
};
return {
schema,
desc: `${mode}{${entries.map(([k, g, opt]) => `${k}${opt ? "?" : ""}:${g.desc}`).join(",")}}`,
valid,
corrupt: (v) => {
if (typeof v !== "object" || v === null) return v;
const o = { ...(v as Record<string, unknown>) };
const [k, g, opt] = pick(c, entries);
switch (int(c, 0, 3)) {
case 0:
o[k] = g.corrupt(k in o ? o[k] : g.valid());
break;
case 1:
if (opt) o[k] = g.corrupt(g.valid());
else delete o[k];
break;
case 2:
o.extra = "e";
break;
default:
return 42;
}
return o;
},
island: false,
};
}
case 2: {
const g = child();
const min = int(c, 0, 2);
return {
schema: z.array(g.schema).min(min),
desc: `array(${g.desc}).min(${min})`,
valid: () => Array.from({ length: min + int(c, 0, 2) }, () => g.valid()),
corrupt: (v) => {
if (!Array.isArray(v)) return v;
const a = [...v];
if (a.length && c.rand() < 0.6) a[int(c, 0, a.length - 1)] = g.corrupt(a[0]);
else if (min > 0) a.length = min - 1;
else return 42;
return a;
},
island: false,
};
}
case 3: {
const items = Array.from({ length: int(c, 1, 3) }, child);
const rest = c.rand() < 0.4 ? child() : null;
const schema = rest
? z.tuple(items.map((g) => g.schema) as [z.ZodType, ...z.ZodType[]], rest.schema)
: z.tuple(items.map((g) => g.schema) as [z.ZodType, ...z.ZodType[]]);
return {
schema,
desc: `tuple(${items.map((g) => g.desc).join(",")}${rest ? `,...${rest.desc}` : ""})`,
valid: () => [
...items.map((g) => g.valid()),
...(rest ? Array.from({ length: int(c, 0, 2) }, () => rest.valid()) : []),
],
corrupt: (v) => {
if (!Array.isArray(v)) return v;
const a = [...v];
const i = int(c, 0, items.length - 1);
if (c.rand() < 0.6) a[i] = items[i]!.corrupt(a[i]);
else if (c.rand() < 0.5) a.push("extra");
else a.length = i;
return a;
},
island: false,
};
}
case 4: {
const g = child();
const enumKeys = c.rand() < 0.4;
const schema = enumKeys ? z.record(z.enum(["a", "b"]), g.schema) : z.record(z.string(), g.schema);
return {
schema,
desc: `record(${enumKeys ? "enum" : "string"},${g.desc})`,
valid: () =>
enumKeys
? { a: g.valid(), b: g.valid() }
: Object.fromEntries(Array.from({ length: int(c, 0, 3) }, (_, i) => [`r${i}`, g.valid()])),
corrupt: (v) => {
if (typeof v !== "object" || v === null) return v;
const o = { ...(v as Record<string, unknown>) };
const keys = Object.keys(o);
if (keys.length && c.rand() < 0.6) o[pick(c, keys)] = g.corrupt(o[keys[0]!]);
else if (enumKeys) o.z = g.valid();
else return 42;
return o;
},
island: false,
};
}
case 5: {
const options = Array.from({ length: int(c, 2, 3) }, child);
return {
schema: z.union(options.map((g) => g.schema) as [z.ZodType, z.ZodType, ...z.ZodType[]]),
desc: `union(${options.map((g) => g.desc).join("|")})`,
valid: () => pick(c, options).valid(),
corrupt: (v) => pick(c, options).corrupt(v),
island: false,
};
}
case 6: {
const branches = Array.from({ length: int(c, 2, 3) }, (_, i) => [i, child()] as const);
return {
schema: z.discriminatedUnion(
"t",
branches.map(([i, g]) => z.object({ t: z.literal(`b${i}`), v: g.schema })) as [
z.ZodObject<{ t: z.ZodLiteral<string>; v: z.ZodType }>,
...z.ZodObject<{ t: z.ZodLiteral<string>; v: z.ZodType }>[],
]
),
desc: `dunion(${branches.map(([, g]) => g.desc).join("|")})`,
valid: () => {
const [i, g] = pick(c, branches);
return { t: `b${i}`, v: g.valid() };
},
corrupt: (v) => {
if (typeof v !== "object" || v === null) return v;
const o = { ...(v as { t: string; v: unknown }) };
const branch = branches.find(([i]) => `b${i}` === o.t);
if (branch && c.rand() < 0.6) o.v = branch[1].corrupt(o.v);
else o.t = "nope";
return o;
},
island: false,
};
}
case 7: {
const min = int(c, 1, 3);
return {
schema: z.string().pipe(z.string().min(min)),
desc: `string.pipe(min(${min}))`,
valid: () => "p".repeat(min + int(c, 0, 1)),
corrupt: () => (c.rand() < 0.5 ? "p".repeat(min - 1) : 7),
island: false,
};
}
default: {
// map and set: the compiled result still has to agree
const g = child();
if (c.rand() < 0.5) {
return {
schema: z.map(z.string(), g.schema),
desc: `map(string,${g.desc})`,
valid: () => new Map(Array.from({ length: int(c, 0, 2) }, (_, i) => [`m${i}`, g.valid()])),
corrupt: (v) => {
if (!(v instanceof Map)) return v;
const m = new Map(v);
if (m.size && c.rand() < 0.7) m.set("m0", g.corrupt(m.get("m0")));
else return [];
return m;
},
island: true,
};
}
return {
schema: z.set(g.schema),
desc: `set(${g.desc})`,
valid: () => new Set(Array.from({ length: int(c, 0, 2) }, () => g.valid())),
corrupt: (v) => {
if (!(v instanceof Set)) return v;
const s = new Set(v);
if (c.rand() < 0.7) s.add(g.corrupt(g.valid()));
else return {};
return s;
},
island: true,
};
}
}
}
function gen(c: Ctx, depth: number): Gen {
if (depth === 0) return leaf(c);
const r = c.rand();
if (r < 0.25) return leaf(c);
if (r < 0.4) return wrap(c, gen(c, depth - 1));
return container(c, depth);
}
function attempt<T>(fn: () => T): { value?: T; threw?: string } {
try {
return { value: fn() };
} catch (err) {
return { threw: (err as Error)?.constructor?.name || "Error" };
}
}
function describe(value: unknown): string {
return JSON.stringify(value, (_k, v) =>
v instanceof Map ? { $map: [...v] } : v instanceof Set ? { $set: [...v] } : v === undefined ? "$undefined" : v
);
}
// own-key order and undefined-valued-vs-absent keys, which toStrictEqual does not see
function shape(value: unknown): unknown {
if (Array.isArray(value)) return value.map(shape);
if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
return Reflect.ownKeys(value).map((k) => [k, shape((value as Record<PropertyKey, unknown>)[k])]);
}
return value;
}
const SEEDS = 400;
test("random schemas parse identically through the interpreter and the compiler", () => {
// every failing seed is collected, so one run names all of them
const failures: string[] = [];
for (let seed = 1; seed <= SEEDS; seed++) {
try {
checkSeed(seed);
} catch (err) {
failures.push((err as Error).message.split("\n")[0]!);
}
}
expect(failures).toEqual([]);
});
function checkSeed(seed: number): void {
{
const c: Ctx = { rand: mulberry32(seed), calls: new Map(), nextCallback: 0 };
const g = gen(c, 3);
const compiled = compile(g.schema);
const inputs = [g.valid(), g.corrupt(g.valid()), g.corrupt(g.corrupt(g.valid())), pick(c, JUNK)];
for (const input of inputs) {
const label = `seed ${seed} ${g.desc} input ${describe(input)}`;
c.calls.clear();
const a = attempt(() => g.schema.safeParse(input));
const runtimeCalls = new Map(c.calls);
c.calls.clear();
const b = attempt(() => compiled.safeParse(input));
const compiledCalls = new Map(c.calls);
expect(b.threw, `${label}: throw`).toBe(a.threw);
if (a.threw) continue;
expect(b.value!.success, `${label}: verdict`).toBe(a.value!.success);
if (a.value!.success) {
expect(b.value!.data, `${label}: data`).toStrictEqual(a.value!.data);
expect(shape(b.value!.data), `${label}: key order`).toEqual(shape(a.value!.data));
} else {
expect(b.value!.error!.issues, `${label}: issues`).toEqual(a.value!.error!.issues);
}
// every callback the interpreter reaches, the compiled schema reaches too; the fast pass runs it at most once and the runtime re-parse at most once more
for (const id of new Set([...compiledCalls.keys(), ...runtimeCalls.keys()])) {
const n = compiledCalls.get(id) ?? 0;
const r = runtimeCalls.get(id) ?? 0;
expect(n, `${label}: callback ${id} ran ${n} vs ${r}`).toBeGreaterThanOrEqual(r);
expect(n, `${label}: callback ${id} ran ${n} vs ${r}`).toBeLessThanOrEqual(2 * r);
}
}
expect(() => compileFn(g.schema), `${g.desc}: compile refused`).not.toThrow();
}
}
@@ -0,0 +1 @@
{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"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 truncated
@@ -0,0 +1,46 @@
This software is dual-licensed under the ISC and MIT licenses.
You may use this software under EITHER of the following licenses.
----------
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.
----------
Copyright Isaac Z. Schlueter and Contributors
All rights reserved.
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,222 @@
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
import {
abytes,
aexists,
aoutput,
clean,
createView,
type Hash,
type TArg,
type TRet,
} from './utils.ts';
/**
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
* Returns bits from `b` when `a` is set, otherwise from `c`.
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
* set the same bit.
* @param a - selector word
* @param b - word chosen when selector bit is set
* @param c - word chosen when selector bit is clear
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit choice primitive.
* ```ts
* Chi(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export function Chi(a: number, b: number, c: number): number {
return (a & b) ^ (~a & c);
}
/**
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
* Returns bits shared by at least two inputs.
* @param a - first input word
* @param b - second input word
* @param c - third input word
* @returns Mixed 32-bit word.
* @example
* Combine three words with the shared 32-bit majority primitive.
* ```ts
* Maj(0xffffffff, 0x12345678, 0x87654321);
* ```
*/
export function Maj(a: number, b: number, c: number): number {
return (a & b) ^ (a & c) ^ (b & c);
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
* strings with partial-byte tails.
* @param blockLen - internal block size in bytes
* @param outputLen - digest size in bytes
* @param padOffset - trailing length field size in bytes
* @param isLE - whether length and state words are encoded in little-endian
* @example
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
* ```ts
* import { _SHA1 } from '@noble/hashes/legacy.js';
* const hash = new _SHA1();
* hash.update(new Uint8Array([97, 98, 99]));
* hash.digest();
* ```
*/
export abstract class HashMD<T extends HashMD<T>> implements Hash<T> {
// Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input
// when it can process whole blocks without buffering first.
protected abstract process(buf: DataView, offset: number): void;
protected abstract get(): number[];
protected abstract set(...args: number[]): void;
abstract destroy(): void;
protected abstract roundClean(): void;
readonly blockLen: number;
readonly outputLen: number;
readonly canXOF = false;
readonly padOffset: number;
readonly isLE: boolean;
// For partial updates less than block size
protected buffer: Uint8Array;
protected view: DataView;
protected finished = false;
protected length = 0;
protected pos = 0;
protected destroyed = false;
constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data: TArg<Uint8Array>): this {
aexists(this);
abytes(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
// Fast path only when there is no buffered partial block: `take === blockLen` implies
// `this.pos === 0`, so we can process full blocks directly from the input view.
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out: TArg<Uint8Array>): void {
aexists(this);
aoutput(out, this);
this.finished = true;
// Padding
// We can avoid allocation of buffer for padding completely if it
// was previously not allocated here. But it won't change performance.
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
// append the bit '1' to the message
buffer[pos++] = 0b10000000;
clean(this.buffer.subarray(pos));
// we have less than padOffset left in buffer, so we cannot put length in
// current block, need process it and pad again
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
// Pad until full block byte with zeros
for (let i = pos; i < blockLen; i++) buffer[i] = 0;
// `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
// the padding fill above, and JS will overflow before user input can make that half non-zero.
// So we only need to write the low 64 bits here.
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
// NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');
const outLen = len / 4;
const state = this.get();
if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
}
digest(): TRet<Uint8Array> {
const { buffer, outputLen } = this;
this.digestInto(buffer);
// Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
// fresh bytes to the caller.
const res = buffer.slice(0, outputLen);
this.destroy();
return res as TRet<Uint8Array>;
}
_cloneInto(to?: T): T {
to ||= new (this.constructor as any)() as T;
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
// Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
// later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
if (length % blockLen) to.buffer.set(buffer);
return to as unknown as any;
}
clone(): T {
return this._cloneInto();
}
}
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
* it as read-only because constructors copy words from it by index. */
export const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
* treat it as read-only because constructors copy words from it by index. */
export const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
]);
/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
* through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
* because constructors copy halves from it by index. */
export const SHA384_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([
0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
]);
/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
* big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
* eight prime numbers. Exported as a shared table; callers must treat it as read-only because
* constructors copy halves from it by index. */
export const SHA512_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([
0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
]);
@@ -0,0 +1,3 @@
import { NavigateOptions } from './link.js';
import { RegisteredRouter } from './router.js';
export type UseNavigateResult<TDefaultFrom extends string> = <TRouter extends RegisteredRouter, TTo extends string | undefined, TFrom extends string = TDefaultFrom, TMaskFrom extends string = TFrom, TMaskTo extends string = ''>({ from, ...rest }: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>) => Promise<void>;
@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.needsPrecedingSemicolon = needsPrecedingSemicolon;
const utils_1 = require("@typescript-eslint/utils");
const ast_utils_1 = require("@typescript-eslint/utils/ast-utils");
// The following is adapted from `eslint`'s source code.
// https://github.com/eslint/eslint/blob/3a4eaf921543b1cd5d1df4ea9dec02fab396af2a/lib/rules/utils/ast-utils.js#L1043-L1132
// Could be export { isStartOfExpressionStatement } from 'eslint/lib/rules/utils/ast-utils'
const BREAK_OR_CONTINUE = new Set([
utils_1.AST_NODE_TYPES.BreakStatement,
utils_1.AST_NODE_TYPES.ContinueStatement,
]);
// Declaration types that must contain a string Literal node at the end.
const DECLARATIONS = new Set([
utils_1.AST_NODE_TYPES.ExportAllDeclaration,
utils_1.AST_NODE_TYPES.ExportNamedDeclaration,
utils_1.AST_NODE_TYPES.ImportDeclaration,
]);
const IDENTIFIER_OR_KEYWORD = new Set([
utils_1.AST_NODE_TYPES.Identifier,
utils_1.AST_TOKEN_TYPES.Keyword,
]);
// Keywords that can immediately precede an ExpressionStatement node, mapped to the their node types.
const NODE_TYPES_BY_KEYWORD = {
__proto__: null,
break: utils_1.AST_NODE_TYPES.BreakStatement,
continue: utils_1.AST_NODE_TYPES.ContinueStatement,
debugger: utils_1.AST_NODE_TYPES.DebuggerStatement,
do: utils_1.AST_NODE_TYPES.DoWhileStatement,
else: utils_1.AST_NODE_TYPES.IfStatement,
return: utils_1.AST_NODE_TYPES.ReturnStatement,
yield: utils_1.AST_NODE_TYPES.YieldExpression,
};
/*
* Before an opening parenthesis, postfix `++` and `--` always trigger ASI;
* the tokens `:`, `;`, `{` and `=>` don't expect a semicolon, as that would count as an empty statement.
*/
const PUNCTUATORS = new Set(['--', ';', ':', '{', '++', '=>']);
/*
* Statements that can contain an `ExpressionStatement` after a closing parenthesis.
* DoWhileStatement is an exception in that it always triggers ASI after the closing parenthesis.
*/
const STATEMENTS = new Set([
utils_1.AST_NODE_TYPES.DoWhileStatement,
utils_1.AST_NODE_TYPES.ForInStatement,
utils_1.AST_NODE_TYPES.ForOfStatement,
utils_1.AST_NODE_TYPES.ForStatement,
utils_1.AST_NODE_TYPES.IfStatement,
utils_1.AST_NODE_TYPES.WhileStatement,
utils_1.AST_NODE_TYPES.WithStatement,
]);
/**
* Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon.
* This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at
* the start of the body of an `ArrowFunctionExpression`.
* @param sourceCode The source code object.
* @param node A node at the position where an opening parenthesis or bracket will be inserted.
* @returns Whether a semicolon is required before the opening parenthesis or bracket.
*/
function needsPrecedingSemicolon(sourceCode, node) {
const prevToken = sourceCode.getTokenBefore(node);
if (!prevToken ||
(prevToken.type === utils_1.AST_TOKEN_TYPES.Punctuator &&
PUNCTUATORS.has(prevToken.value))) {
return false;
}
const prevNode = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
if (!prevNode) {
return false;
}
if ((0, ast_utils_1.isClosingParenToken)(prevToken)) {
return !STATEMENTS.has(prevNode.type);
}
if ((0, ast_utils_1.isClosingBraceToken)(prevToken)) {
return ((prevNode.type === utils_1.AST_NODE_TYPES.BlockStatement &&
prevNode.parent.type === utils_1.AST_NODE_TYPES.FunctionExpression &&
prevNode.parent.parent.type !== utils_1.AST_NODE_TYPES.MethodDefinition) ||
(prevNode.type === utils_1.AST_NODE_TYPES.ClassBody &&
prevNode.parent.type === utils_1.AST_NODE_TYPES.ClassExpression) ||
prevNode.type === utils_1.AST_NODE_TYPES.ObjectExpression);
}
if (!prevNode.parent) {
return false;
}
if (IDENTIFIER_OR_KEYWORD.has(prevToken.type)) {
if (BREAK_OR_CONTINUE.has(prevNode.parent.type)) {
return false;
}
const keyword = prevToken.value;
const nodeType = NODE_TYPES_BY_KEYWORD[keyword];
return prevNode.type !== nodeType;
}
if (prevToken.type === utils_1.AST_TOKEN_TYPES.String) {
return !DECLARATIONS.has(prevNode.parent.type);
}
return true;
}
@@ -0,0 +1,3 @@
export * from '@tanstack/store';
export { useStore } from './useStore.js';
export declare function shallow<T>(objA: T, objB: T): boolean;
@@ -0,0 +1,81 @@
/**
* @fileoverview Universal module importer
*/
//-----------------------------------------------------------------------------
// Imports
//-----------------------------------------------------------------------------
const { createRequire } = require("module");
const { pathToFileURL } = require("url");
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
const SLASHES = new Set(["/", "\\"]);
/**
* Normalizes directories to have a trailing slash.
* Resolve is pretty finicky -- if the directory name doesn't have
* a trailing slash then it tries to look in the parent directory.
* i.e., if the directory is "/usr/nzakas/foo" it will start the
* search in /usr/nzakas. However, if the directory is "/user/nzakas/foo/",
* then it will start the search in /user/nzakas/foo.
* @param {string} directory The directory to check.
* @returns {string} The normalized directory.
*/
function normalizeDirectory(directory) {
if (!SLASHES.has(directory[directory.length-1])) {
return directory + "/";
}
return directory;
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Class for importing both CommonJS and ESM modules in Node.js.
*/
exports.ModuleImporter = class ModuleImporter {
/**
* Creates a new instance.
* @param {string} [cwd] The current working directory to resolve from.
*/
constructor(cwd = process.cwd()) {
/**
* The base directory from which paths should be resolved.
* @type {string}
*/
this.cwd = normalizeDirectory(cwd);
}
/**
* Resolves a module based on its name or location.
* @param {string} specifier Either an npm package name or
* relative file path.
* @returns {string|undefined} The location of the import.
* @throws {Error} If specifier cannot be located.
*/
resolve(specifier) {
const require = createRequire(this.cwd);
return require.resolve(specifier);
}
/**
* Imports a module based on its name or location.
* @param {string} specifier Either an npm package name or
* relative file path.
* @returns {Promise<object>} The module's object.
*/
import(specifier) {
const location = this.resolve(specifier);
return import(pathToFileURL(location).href);
}
}
@@ -0,0 +1,22 @@
/**
* @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 BookOpen = createLucideIcon("BookOpen", [
["path", { d: "M12 7v14", key: "1akyts" }],
[
"path",
{
d: "M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",
key: "ruj8y"
}
]
]);
export { BookOpen as default };
//# sourceMappingURL=book-open.js.map
@@ -0,0 +1,311 @@
const COOKIE_MAX_AGE_LIMIT = 3456e4;
function endIndex(str, min, len) {
const index = str.indexOf(";", min);
return index === -1 ? len : index;
}
function eqIndex(str, min, max) {
const index = str.indexOf("=", min);
return index < max ? index : -1;
}
function valueSlice(str, min, max) {
if (min === max) return "";
let start = min;
let end = max;
do {
const code = str.charCodeAt(start);
if (code !== 32 && code !== 9) break;
} while (++start < end);
while (end > start) {
const code = str.charCodeAt(end - 1);
if (code !== 32 && code !== 9) break;
end--;
}
return str.slice(start, end);
}
const NullObject = /* @__PURE__ */ (() => {
const C = function() {};
C.prototype = Object.create(null);
return C;
})();
function parse(str, options) {
const obj = new NullObject();
const len = str.length;
if (len < 2) return obj;
const dec = options?.decode || decode;
const allowMultiple = options?.allowMultiple || false;
let index = 0;
do {
const eqIdx = eqIndex(str, index, len);
if (eqIdx === -1) break;
const endIdx = endIndex(str, index, len);
if (eqIdx > endIdx) {
index = str.lastIndexOf(";", eqIdx - 1) + 1;
continue;
}
const key = valueSlice(str, index, eqIdx);
if (options?.filter && !options.filter(key)) {
index = endIdx + 1;
continue;
}
const val = dec(valueSlice(str, eqIdx + 1, endIdx));
if (allowMultiple) {
const existing = obj[key];
if (existing === void 0) obj[key] = val;
else if (Array.isArray(existing)) existing.push(val);
else obj[key] = [existing, val];
} else if (obj[key] === void 0) obj[key] = val;
index = endIdx + 1;
} while (index < len);
return obj;
}
function decode(str) {
if (!str.includes("%")) return str;
try {
return decodeURIComponent(str);
} catch {
return str;
}
}
const cookieNameRegExp = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/;
const cookieValueRegExp = /^[\u0021-\u003A\u003C-\u007E]*$/;
const domainValueRegExp = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
const pathValueRegExp = /^[\u0020-\u003A\u003C-\u007E]*$/;
const __toString = Object.prototype.toString;
function stringifyCookie(cookie, options) {
const enc = options?.encode || encodeURIComponent;
const keys = Object.keys(cookie);
let str = "";
for (const [i, name] of keys.entries()) {
const val = cookie[name];
if (val === void 0) continue;
if (!cookieNameRegExp.test(name)) throw new TypeError(`cookie name is invalid: ${name}`);
const value = enc(val);
if (!cookieValueRegExp.test(value)) throw new TypeError(`cookie val is invalid: ${val}`);
if (i > 0) str += "; ";
str += name + "=" + value;
}
return str;
}
function serialize(_a0, _a1, _a2) {
const isObj = typeof _a0 === "object" && _a0 !== null;
const options = isObj ? _a1 : _a2;
const stringify = options?.stringify || JSON.stringify;
const cookie = isObj ? _a0 : {
..._a2,
name: _a0,
value: _a1 == void 0 ? "" : typeof _a1 === "string" ? _a1 : stringify(_a1)
};
const enc = options?.encode || encodeURIComponent;
if (!cookieNameRegExp.test(cookie.name)) throw new TypeError(`argument name is invalid: ${cookie.name}`);
const value = cookie.value ? enc(cookie.value) : "";
if (!cookieValueRegExp.test(value)) throw new TypeError(`argument val is invalid: ${cookie.value}`);
if (!cookie.secure) {
if (cookie.partitioned) throw new TypeError(`Partitioned cookies must have the Secure attribute`);
if (cookie.sameSite && String(cookie.sameSite).toLowerCase() === "none") throw new TypeError(`SameSite=None cookies must have the Secure attribute`);
if (cookie.name.length > 9 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95) {
const nameLower = cookie.name.toLowerCase();
if (nameLower.startsWith("__secure-") || nameLower.startsWith("__host-")) throw new TypeError(`${cookie.name} cookies must have the Secure attribute`);
}
}
if (cookie.name.length > 7 && cookie.name.charCodeAt(0) === 95 && cookie.name.charCodeAt(1) === 95 && cookie.name.toLowerCase().startsWith("__host-")) {
if (cookie.path !== "/") throw new TypeError(`__Host- cookies must have Path=/`);
if (cookie.domain) throw new TypeError(`__Host- cookies must not have a Domain attribute`);
}
let str = cookie.name + "=" + value;
if (cookie.maxAge !== void 0) {
if (!Number.isInteger(cookie.maxAge)) throw new TypeError(`option maxAge is invalid: ${cookie.maxAge}`);
str += "; Max-Age=" + Math.max(0, Math.min(cookie.maxAge, COOKIE_MAX_AGE_LIMIT));
}
if (cookie.domain) {
if (!domainValueRegExp.test(cookie.domain)) throw new TypeError(`option domain is invalid: ${cookie.domain}`);
str += "; Domain=" + cookie.domain;
}
if (cookie.path) {
if (!pathValueRegExp.test(cookie.path)) throw new TypeError(`option path is invalid: ${cookie.path}`);
str += "; Path=" + cookie.path;
}
if (cookie.expires) {
if (!isDate(cookie.expires) || !Number.isFinite(cookie.expires.valueOf())) throw new TypeError(`option expires is invalid: ${cookie.expires}`);
str += "; Expires=" + cookie.expires.toUTCString();
}
if (cookie.httpOnly) str += "; HttpOnly";
if (cookie.secure) str += "; Secure";
if (cookie.partitioned) str += "; Partitioned";
if (cookie.priority) switch (typeof cookie.priority === "string" ? cookie.priority.toLowerCase() : void 0) {
case "low":
str += "; Priority=Low";
break;
case "medium":
str += "; Priority=Medium";
break;
case "high":
str += "; Priority=High";
break;
default: throw new TypeError(`option priority is invalid: ${cookie.priority}`);
}
if (cookie.sameSite) switch (typeof cookie.sameSite === "string" ? cookie.sameSite.toLowerCase() : cookie.sameSite) {
case true:
case "strict":
str += "; SameSite=Strict";
break;
case "lax":
str += "; SameSite=Lax";
break;
case "none":
str += "; SameSite=None";
break;
default: throw new TypeError(`option sameSite is invalid: ${cookie.sameSite}`);
}
return str;
}
function isDate(val) {
return __toString.call(val) === "[object Date]";
}
const maxAgeRegExp = /^-?\d+$/;
const _nullProto = /* @__PURE__ */ Object.getPrototypeOf({});
function parseSetCookie(str, options) {
const len = str.length;
let _endIdx = len;
let eqIdx = -1;
for (let i = 0; i < len; i++) {
const c = str.charCodeAt(i);
if (c === 59) {
_endIdx = i;
break;
}
if (c === 61 && eqIdx === -1) eqIdx = i;
}
if (eqIdx >= _endIdx) eqIdx = -1;
const name = eqIdx === -1 ? "" : _trim(str, 0, eqIdx);
if (name && name in _nullProto) return void 0;
let value = eqIdx === -1 ? _trim(str, 0, _endIdx) : _trim(str, eqIdx + 1, _endIdx);
if (!name && !value) return void 0;
if (name.length + value.length > 4096) return void 0;
if (options?.decode !== false) value = _decode(value, options?.decode);
const setCookie = {
name,
value
};
let index = _endIdx + 1;
while (index < len) {
let endIdx = len;
let attrEqIdx = -1;
for (let i = index; i < len; i++) {
const c = str.charCodeAt(i);
if (c === 59) {
endIdx = i;
break;
}
if (c === 61 && attrEqIdx === -1) attrEqIdx = i;
}
if (attrEqIdx >= endIdx) attrEqIdx = -1;
const attr = attrEqIdx === -1 ? _trim(str, index, endIdx) : _trim(str, index, attrEqIdx);
const val = attrEqIdx === -1 ? void 0 : _trim(str, attrEqIdx + 1, endIdx);
if (val === void 0 || val.length <= 1024) switch (attr.toLowerCase()) {
case "httponly":
setCookie.httpOnly = true;
break;
case "secure":
setCookie.secure = true;
break;
case "partitioned":
setCookie.partitioned = true;
break;
case "domain":
if (val) setCookie.domain = (val.charCodeAt(0) === 46 ? val.slice(1) : val).toLowerCase();
break;
case "path":
setCookie.path = val;
break;
case "max-age":
if (val && maxAgeRegExp.test(val)) setCookie.maxAge = Math.min(Number(val), COOKIE_MAX_AGE_LIMIT);
break;
case "expires": {
if (!val) break;
const date = new Date(val);
if (Number.isFinite(date.valueOf())) {
const maxDate = new Date(Date.now() + COOKIE_MAX_AGE_LIMIT * 1e3);
setCookie.expires = date > maxDate ? maxDate : date;
}
break;
}
case "priority": {
if (!val) break;
const priority = val.toLowerCase();
if (priority === "low" || priority === "medium" || priority === "high") setCookie.priority = priority;
break;
}
case "samesite": {
if (!val) break;
const sameSite = val.toLowerCase();
if (sameSite === "lax" || sameSite === "strict" || sameSite === "none") setCookie.sameSite = sameSite;
else setCookie.sameSite = "lax";
break;
}
default: {
const attrLower = attr.toLowerCase();
if (attrLower && !(attrLower in _nullProto)) setCookie[attrLower] = val;
}
}
index = endIdx + 1;
}
return setCookie;
}
function _trim(str, start, end) {
if (start === end) return "";
let s = start;
let e = end;
while (s < e && (str.charCodeAt(s) === 32 || str.charCodeAt(s) === 9)) s++;
while (e > s && (str.charCodeAt(e - 1) === 32 || str.charCodeAt(e - 1) === 9)) e--;
return str.slice(s, e);
}
function _decode(value, decode) {
if (!decode && !value.includes("%")) return value;
try {
return (decode || decodeURIComponent)(value);
} catch {
return value;
}
}
function splitSetCookieString(cookiesString) {
if (Array.isArray(cookiesString)) return cookiesString.flatMap((c) => splitSetCookieString(c));
if (typeof cookiesString !== "string") return [];
const cookiesStrings = [];
let pos = 0;
let start;
let ch;
let lastComma;
let nextStart;
let cookiesSeparatorFound;
const skipWhitespace = () => {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) pos += 1;
return pos < cookiesString.length;
};
const notSpecialChar = () => {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
};
while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) pos += 1;
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
cookiesSeparatorFound = true;
pos = nextStart;
cookiesStrings.push(cookiesString.slice(start, lastComma));
start = pos;
} else pos = lastComma + 1;
} else pos += 1;
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.slice(start));
}
return cookiesStrings;
}
export { parse, parse as parseCookie, parseSetCookie, serialize, serialize as serializeCookie, splitSetCookieString, stringifyCookie };
@@ -0,0 +1,101 @@
import {createCheckers} from "ts-interface-checker";
import OptionsGenTypes from "./Options-gen-types";
const {Options: OptionsChecker} = createCheckers(OptionsGenTypes);
export function validateOptions(options) {
OptionsChecker.strictCheck(options);
}
@@ -0,0 +1,144 @@
/**
* @fileoverview Rule to check for "block scoped" variables by binding context
* @author Matt DuVall <http://www.mattduvall.com>
*/
"use strict";
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/** @typedef {import("eslint-scope").Definition} Definition */
/** @typedef {import("eslint-scope").Reference} Reference */
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Enforce the use of variables within the scope they are defined",
recommended: false,
url: "https://eslint.org/docs/latest/rules/block-scoped-var",
},
schema: [],
messages: {
outOfScope:
"'{{name}}' declared on line {{definitionLine}} column {{definitionColumn}} is used outside of binding context.",
},
},
create(context) {
let stack = [];
const sourceCode = context.sourceCode;
/**
* Makes a block scope.
* @param {ASTNode} node A node of a scope.
* @returns {void}
*/
function enterScope(node) {
stack.push(node.range);
}
/**
* Pops the last block scope.
* @returns {void}
*/
function exitScope() {
stack.pop();
}
/**
* Reports a given reference.
* @param {Reference} reference A reference to report.
* @param {Definition} definition A definition for which to report reference.
* @returns {void}
*/
function report(reference, definition) {
const identifier = reference.identifier;
const definitionPosition = definition.name.loc.start;
context.report({
node: identifier,
messageId: "outOfScope",
data: {
name: identifier.name,
definitionLine: definitionPosition.line,
definitionColumn: definitionPosition.column + 1,
},
});
}
/**
* Finds and reports references which are outside of valid scopes.
* @param {ASTNode} node A node to get variables.
* @returns {void}
*/
function checkForVariables(node) {
if (node.kind !== "var") {
return;
}
// Defines a predicate to check whether or not a given reference is outside of valid scope.
const scopeRange = stack.at(-1);
/**
* Check if a reference is out of scope
* @param {ASTNode} reference node to examine
* @returns {boolean} True is its outside the scope
* @private
*/
function isOutsideOfScope(reference) {
const idRange = reference.identifier.range;
return idRange[0] < scopeRange[0] || idRange[1] > scopeRange[1];
}
// Gets declared variables, and checks its references.
const variables = sourceCode.getDeclaredVariables(node);
for (let i = 0; i < variables.length; ++i) {
// Reports.
variables[i].references.filter(isOutsideOfScope).forEach(ref =>
report(
ref,
variables[i].defs.find(def => def.parent === node),
),
);
}
}
return {
Program(node) {
stack = [node.range];
},
// Manages scopes.
BlockStatement: enterScope,
"BlockStatement:exit": exitScope,
ForStatement: enterScope,
"ForStatement:exit": exitScope,
ForInStatement: enterScope,
"ForInStatement:exit": exitScope,
ForOfStatement: enterScope,
"ForOfStatement:exit": exitScope,
SwitchStatement: enterScope,
"SwitchStatement:exit": exitScope,
CatchClause: enterScope,
"CatchClause:exit": exitScope,
StaticBlock: enterScope,
"StaticBlock:exit": exitScope,
// Finds and reports references which are outside of valid scope.
VariableDeclaration: checkForVariables,
};
},
};
@@ -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 UserSearch = createLucideIcon("UserSearch", [
["circle", { cx: "10", cy: "7", r: "4", key: "e45bow" }],
["path", { d: "M10.3 15H7a4 4 0 0 0-4 4v2", key: "3bnktk" }],
["circle", { cx: "17", cy: "17", r: "3", key: "18b49y" }],
["path", { d: "m21 21-1.9-1.9", key: "1g2n9r" }]
]);
export { UserSearch as default };
//# sourceMappingURL=user-search.js.map
@@ -0,0 +1,18 @@
#!/usr/bin/env node
const Module = require("module");
const {resolve} = require("path");
/*
* Simple wrapper around node that first registers Sucrase with default settings.
*
* This is meant for simple use cases, and doesn't support custom Node/V8 args,
* executing a code snippet, a REPL, or other things that you might find in
* node, babel-node, or ts-node. For more advanced use cases, you can use
* `node -r sucrase/register` or register a require hook programmatically from
* your own code.
*/
require("../register");
process.argv.splice(1, 1);
process.argv[1] = resolve(process.argv[1]);
Module.runMain();
@@ -0,0 +1 @@
{"version":3,"file":"index.mjs","sources":["../../../../../src/value/types/color/index.ts"],"sourcesContent":["import { HSLA, RGBA } from \"../types\"\nimport { hex } from \"./hex\"\nimport { hsla } from \"./hsla\"\nimport { rgba } from \"./rgba\"\n\nexport const color = {\n test: (v: any) => rgba.test(v) || hex.test(v) || hsla.test(v),\n parse: (v: any): RGBA | HSLA => {\n if (rgba.test(v)) {\n return rgba.parse(v)\n } else if (hsla.test(v)) {\n return hsla.parse(v)\n } else {\n return hex.parse(v)\n }\n },\n transform: (v: HSLA | RGBA | string) => {\n return typeof v === \"string\"\n ? v\n : v.hasOwnProperty(\"red\")\n ? rgba.transform(v as RGBA)\n : hsla.transform(v as HSLA)\n },\n getAnimatableNone: (v: string) => {\n const parsed = color.parse(v)\n parsed.alpha = 0\n return color.transform(parsed)\n },\n}\n"],"names":[],"mappings":";;;;AAKO,MAAM,KAAK,GAAG;IACjB,IAAI,EAAE,CAAC,CAAM,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAC7D,IAAA,KAAK,EAAE,CAAC,CAAM,KAAiB;AAC3B,QAAA,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;AACd,YAAA,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QACxB;AAAO,aAAA,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;AACrB,YAAA,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;QACxB;aAAO;AACH,YAAA,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;QACvB;IACJ,CAAC;AACD,IAAA,SAAS,EAAE,CAAC,CAAuB,KAAI;QACnC,OAAO,OAAO,CAAC,KAAK;AAChB,cAAE;AACF,cAAE,CAAC,CAAC,cAAc,CAAC,KAAK;AACxB,kBAAE,IAAI,CAAC,SAAS,CAAC,CAAS;AAC1B,kBAAE,IAAI,CAAC,SAAS,CAAC,CAAS,CAAC;IACnC,CAAC;AACD,IAAA,iBAAiB,EAAE,CAAC,CAAS,KAAI;QAC7B,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AAC7B,QAAA,MAAM,CAAC,KAAK,GAAG,CAAC;AAChB,QAAA,OAAO,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;IAClC,CAAC;;;;;"}
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_K","2":"_I"},C:{"2":"_yJ","129":"_AM"},D:{"1":"_RL","2":"_MO"},E:{"1":"_YQ","2":"_gG _oE"},F:{"1":"_SI","2":"_HM"},G:{"1":"_gL","2":"_AF _oE"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_U","2":"J"},Q:{"1":"JE"},R:{"1":"KE"},S:{"2":"_C"}},B:5,C:"Auxclick",D:true};
@@ -0,0 +1,13 @@
import { useRouter } from "./useRouter.js";
import { useStore } from "@tanstack/react-store";
import { isServer } from "@tanstack/router-core/isServer";
//#region src/useCanGoBack.ts
function useCanGoBack() {
const router = useRouter();
if (isServer ?? router.isServer) return router.stores.location.get().state.__TSR_index !== 0;
return useStore(router.stores.location, (location) => location.state.__TSR_index !== 0);
}
//#endregion
export { useCanGoBack };
//# sourceMappingURL=useCanGoBack.js.map
@@ -0,0 +1,374 @@
import { expect, test } from "vitest";
import * as z from "zod/v4";
test("continuability", () => {
/**
* | $ZodGUID
| $ZodUUID
| $ZodEmail
| $ZodURL
| $ZodEmoji
| $ZodNanoID
| $ZodCUID
| $ZodCUID2
| $ZodULID
| $ZodXID
| $ZodKSUID
| $ZodISODateTime
| $ZodISODate
| $ZodISOTime
| $ZodISODuration
| $ZodIPv4
| $ZodIPv6
| $ZodCIDRv4
| $ZodCIDRv6
| $ZodBase64
| $ZodBase64URL
| $ZodE164
| $ZodJWT;
*/
expect(
z
.email()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "email",
"message": "Invalid email address",
"origin": "string",
"path": [],
"pattern": "/^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.uuid()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "uuid",
"message": "Invalid UUID",
"origin": "string",
"path": [],
"pattern": "/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.url()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "url",
"message": "Invalid URL",
"path": [],
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.jwt()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "jwt",
"message": "Invalid JWT",
"path": [],
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.cidrv4()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "cidrv4",
"message": "Invalid IPv4 range",
"origin": "string",
"path": [],
"pattern": "/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.cidrv6()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "cidrv6",
"message": "Invalid IPv6 range",
"path": [],
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.ipv4()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "ipv4",
"message": "Invalid IPv4 address",
"origin": "string",
"path": [],
"pattern": "/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.ipv6()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "ipv6",
"message": "Invalid IPv6 address",
"path": [],
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.mac()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "mac",
"message": "Invalid MAC address",
"origin": "string",
"path": [],
"pattern": "/^(?:[0-9A-F]{2}:){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}:){5}[0-9a-f]{2}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.emoji()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "emoji",
"message": "Invalid emoji",
"origin": "string",
"path": [],
"pattern": "/^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$/u",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.nanoid()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "nanoid",
"message": "Invalid nanoid",
"origin": "string",
"path": [],
"pattern": "/^[a-zA-Z0-9_-]{21}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.cuid()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "cuid",
"message": "Invalid cuid",
"origin": "string",
"path": [],
"pattern": "/^[cC][0-9a-z]{6,}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.cuid2()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "cuid2",
"message": "Invalid cuid2",
"origin": "string",
"path": [],
"pattern": "/^[0-9a-z]+$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.ulid()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "ulid",
"message": "Invalid ULID",
"origin": "string",
"path": [],
"pattern": "/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.xid()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "xid",
"message": "Invalid XID",
"origin": "string",
"path": [],
"pattern": "/^[0-9a-vA-V]{20}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
expect(
z
.ksuid()
.refine(() => false)
.safeParse("invalid_value").error!.issues
).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "ksuid",
"message": "Invalid KSUID",
"origin": "string",
"path": [],
"pattern": "/^[A-Za-z0-9]{27}$/",
},
{
"code": "custom",
"message": "Invalid input",
"path": [],
},
]
`);
});
@@ -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 FileQuestion = createLucideIcon("FileQuestion", [
["path", { d: "M12 17h.01", key: "p32p05" }],
["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z", key: "1mlx9k" }],
["path", { d: "M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3", key: "mhlwft" }]
]);
export { FileQuestion as default };
//# sourceMappingURL=file-question.js.map
@@ -0,0 +1,189 @@
flf2a$ 1 1 30 -1 40
Morse by Glenn Chappell <ggc@uiuc.edu> 10/95
Based on info from "Morse Code and the Phonetic Alphabets"
URL: http://www.soton.ac.uk/~scp93ch/refer/alphabet.html
Includes some ISO Latin-1 characters
Permission is hereby given to modify this font, as long as the
modifier's name is placed on a comment line.
Use of this font allows figlet to convert ASCII to International Morse
Code.
The following substitutions have been made, i.e., if figlet receives a
character on the left as input, it will print the Morse Code for the
character on the right:
! -> .
; -> :
[]{} -> ()
German s-z -> ss
Latin-1 "prime" -> '
# -> <Delete last word>
* -> Ch
Except as noted above, characters not available in Morse Code will print
as "?".
Inter-word spaces have been enlarged to improve readability. To conform
to the standards for automatic transmission of Morse Code, use smushmode
zero ("figlet -f morse -m0"); wait the duration of a dot for each blank
in the output, as well as between any two output characters (dots,
dashes or blanks).
Explanation of first line:
flf2 - "magic number" for file identification
a - should always be `a', for now
$ - the "hardblank" -- prints as a blank, but can't be smushed
1 - height of a character
1 - height of a character, not including descenders
30 - max line length (excluding comment lines) + a fudge factor
-1 - default smushmode for this font
40 - number of comment lines
$@
.-.-.-$@
.-..-.$@
........$@
?$#
?$#
?$#
.----.$@
-.--.-$@
-.--.-$@
----$@
?$#
--..--$@
-....-$@
.-.-.-$@
-..-.$@
-----$@
.----$@
..---$@
...--$@
....-$@
.....$@
-....$@
--...$@
---..$@
----.$@
---...$@
---...$@
?$#
?$#
?$#
..--..$@
?$#
.-$@
-...$@
-.-.$@
-..$@
.$@
..-.$@
--.$@
....$@
..$@
.---$@
-.-$@
.-..$@
--$@
-.$@
---$@
.--.$@
--.-$@
.-.$@
...$@
-$@
..-$@
...-$@
.--$@
-..-$@
-.--$@
--..$@
-.--.-$@
?$#
-.--.-$@
?$#
?$#
?$#
.-$@
-...$@
-.-.$@
-..$@
.$@
..-.$@
--.$@
....$@
..$@
.---$@
-.-$@
.-..$@
--$@
-.$@
---$@
.--.$@
--.-$@
.-.$@
...$@
-$@
..-$@
...-$@
.--$@
-..-$@
-.--$@
--..$@
-.--.-$@
?$#
-.--.-$@
?$#
.-.-$@
---.$@
..--$@
.-.-$@
---.$@
..--$@
...$...$@
0
?$#
160
$@
171
.-..-.$@
180
.----.$@
187
.-..-.$@
188
.----$-..-.$....-$@
189
.----$-..-.$..---$@
190
...--$-..-.$....-$@
193
.--.-$@
196
.-.-$@
197
.--.-$@
201
..-..$@
209
--.--$@
214
---.$@
220
..--$@
223
...$...$@
225
.--.-$@
228
.-.-$@
229
.--.-$@
233
..-..$@
241
--.--$@
246
---.$@
252
..--$@
@@ -0,0 +1,12 @@
'use strict';
var s;
if (process.env.NODE_ENV === 'production') {
s = require('./cjs/react-dom-server.edge.production.js');
} else {
s = require('./cjs/react-dom-server.edge.development.js');
}
exports.version = s.version;
exports.prerender = s.prerender;
exports.resumeAndPrerender = s.resumeAndPrerender;
@@ -0,0 +1,78 @@
/*!
* escape-html
* Copyright(c) 2012-2013 TJ Holowaychuk
* Copyright(c) 2015 Andreas Lubbe
* Copyright(c) 2015 Tiancheng "Timothy" Gu
* MIT Licensed
*/
'use strict';
/**
* Module variables.
* @private
*/
var matchHtmlRegExp = /["'&<>]/;
/**
* Module exports.
* @public
*/
module.exports = escapeHtml;
/**
* Escape special characters in the given string of html.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
function escapeHtml(string) {
var str = '' + string;
var match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
var escape;
var html = '';
var index = 0;
var lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '&quot;';
break;
case 38: // &
escape = '&amp;';
break;
case 39: // '
escape = '&#39;';
break;
case 60: // <
escape = '&lt;';
break;
case 62: // >
escape = '&gt;';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index
? html + str.substring(lastIndex, index)
: html;
}
@@ -0,0 +1,71 @@
#!/usr/bin/env node
const spawn = require('child_process').spawnSync;
const path = require('path');
const filesToCheck = ['*.h', '*.cc'];
const FORMAT_START = process.env.FORMAT_START || 'main';
function main (args) {
let fix = false;
while (args.length > 0) {
switch (args[0]) {
case '-f':
case '--fix':
fix = true;
break;
default:
}
args.shift();
}
const clangFormatPath = path.dirname(require.resolve('clang-format'));
const binary = process.platform === 'win32'
? 'node_modules\\.bin\\clang-format.cmd'
: 'node_modules/.bin/clang-format';
const options = ['--binary=' + binary, '--style=file'];
if (fix) {
options.push(FORMAT_START);
} else {
options.push('--diff', FORMAT_START);
}
const gitClangFormatPath = path.join(clangFormatPath, 'bin/git-clang-format');
const result = spawn(
'python',
[gitClangFormatPath, ...options, '--', ...filesToCheck],
{ encoding: 'utf-8' }
);
if (result.stderr) {
console.error('Error running git-clang-format:', result.stderr);
return 2;
}
const clangFormatOutput = result.stdout.trim();
// Bail fast if in fix mode.
if (fix) {
console.log(clangFormatOutput);
return 0;
}
// Detect if there is any complains from clang-format
if (
clangFormatOutput !== '' &&
clangFormatOutput !== 'no modified files to format' &&
clangFormatOutput !== 'clang-format did not modify any files'
) {
console.error(clangFormatOutput);
const fixCmd = 'npm run lint:fix';
console.error(`
ERROR: please run "${fixCmd}" to format changes in your commit
Note that when running the command locally, please keep your local
main branch and working branch up to date with nodejs/node-addon-api
to exclude un-related complains.
Or you can run "env FORMAT_START=upstream/main ${fixCmd}".`);
return 1;
}
}
if (require.main === module) {
process.exitCode = main(process.argv.slice(2));
}
@@ -0,0 +1 @@
{"version":3,"file":"a-large-small.js","sources":["../../../src/icons/a-large-small.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ALargeSmall\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMjEgMTRoLTUiIC8+CiAgPHBhdGggZD0iTTE2IDE2di0zLjVhMi41IDIuNSAwIDAgMSA1IDBWMTYiIC8+CiAgPHBhdGggZD0iTTQuNSAxM2g2IiAvPgogIDxwYXRoIGQ9Im0zIDE2IDQuNS05IDQuNSA5IiAvPgo8L3N2Zz4=) - https://lucide.dev/icons/a-large-small\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 ALargeSmall = createLucideIcon('ALargeSmall', [\n ['path', { d: 'M21 14h-5', key: '1vh23k' }],\n ['path', { d: 'M16 16v-3.5a2.5 2.5 0 0 1 5 0V16', key: '1wh10o' }],\n ['path', { d: 'M4.5 13h6', key: 'dfilno' }],\n ['path', { d: 'm3 16 4.5-9 4.5 9', key: '2dxa0e' }],\n]);\n\nexport default ALargeSmall;\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,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,CAAoC,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,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACjE,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,CAAqB,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;AACpD,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"Feedback.mjs","sources":["../src/Feedback.ts"],"sourcesContent":[null],"names":["defaultFeedback","warning","suggestions","Feedback","constructor","options","matchers","setDefaultSuggestions","bruteforce","bruteforceMatcher","date","dateMatcher","dictionary","dictionaryMatcher","regex","regexMatcher","repeat","repeatMatcher","sequence","sequenceMatcher","spatial","spatialMatcher","separator","separatorMatcher","wordSequence","wordSequenceMatcher","Object","entries","forEach","key","matcher","feedback","push","translations","useWords","noNeed","getFeedback","score","length","extraFeedback","anotherWord","longestMatch","getLongestMatch","getMatchFeedback","undefined","unshift","i","match","token","isSoleMatch","pattern"],"mappings":"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"}
@@ -0,0 +1 @@
{"version":3,"file":"matching.mjs","sources":["../../../src/matcher/wordSequence/matching.ts"],"sourcesContent":[null],"names":["MatchWordSequence","MatcherBaseClass","constructor","options","dictionary","DictionaryMatcher","dictionaryL33t","DictionaryL33tMatcher","dictionaryReverse","DictionaryReverseMatcher","match","matchOptions","password","dictionaryMatches","dictionaryL33tMatches","dictionaryReverseMatches","filteredDictionaryMatches","filterDictionaryMatches","wordMatches","convertToWordMatches","findWordSequences","matches","sort","a","b","i","j","reversed","l33t","rank","reduce","acc","last","length","push","map","word","matchedWord","dictionaryName","sequences","sortedMatches","startIdx","sequencesFromStart","findSequencesFromStart","startMatch","currentSequence","currentEnd","nextIdx","nextMatch","isValidWordSequence","createWordSequenceMatch","lastWord","textBetween","slice","separators","isSimpleConcat","hasValidSeparator","some","sep","isCamelCase","toUpperCase","toLowerCase","sequence","firstMatch","lastMatch","words","ranks","ascending","every","dictionaryNames","getMostCommon","pattern","token","wordCount","array","counts","Map","maxCount","mostCommon","forEach","item","count","get","set"],"mappings":"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 truncated
@@ -0,0 +1 @@
{"version":3,"file":"feedback.mjs","sources":["../../../src/matcher/repeat/feedback.ts"],"sourcesContent":[null],"names":["options","match","warning","translations","warnings","extendedRepeat","baseToken","length","simpleRepeat","suggestions","repeated"],"mappings":"AAGA,oBAAe,CAACA,OAAgB,EAAEC,KAAqB,KAAI;EACzD,IAAIC,OAAO,GAAGF,OAAO,CAACG,YAAY,CAACC,QAAQ,CAACC,cAAc;AAC1D,EAAA,IAAIJ,KAAK,CAACK,SAAS,CAACC,MAAM,KAAK,CAAC,EAAE;AAChCL,IAAAA,OAAO,GAAGF,OAAO,CAACG,YAAY,CAACC,QAAQ,CAACI,YAAY;AACtD,EAAA;EAEA,OAAO;IACLN,OAAO;IACPO,WAAW,EAAE,CAACT,OAAO,CAACG,YAAY,CAACM,WAAW,CAACC,QAAQ;GACxD;AACH,CAAC;;;;"}
@@ -0,0 +1,678 @@
// Run with: npx tsx src/examples/client/elicitationUrlExample.ts
//
// This example demonstrates how to use URL elicitation to securely
// collect user input in a remote (HTTP) server.
// URL elicitation allows servers to prompt the end-user to open a URL in their browser
// to collect sensitive information.
import { Client } from '../../client/index.js';
import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js';
import { createInterface } from 'node:readline';
import { ListToolsResultSchema, CallToolResultSchema, ElicitRequestSchema, McpError, ErrorCode, UrlElicitationRequiredError, ElicitationCompleteNotificationSchema } from '../../types.js';
import { getDisplayName } from '../../shared/metadataUtils.js';
import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js';
import { UnauthorizedError } from '../../client/auth.js';
import { createServer } from 'node:http';
// Set up OAuth (required for this example)
const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001)
const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`;
let oauthProvider = undefined;
console.log('Getting OAuth token...');
const clientMetadata = {
client_name: 'Elicitation MCP Client',
redirect_uris: [OAUTH_CALLBACK_URL],
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'client_secret_post',
scope: 'mcp:tools'
};
oauthProvider = new InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => {
console.log(`\n🔗 Please open this URL in your browser to authorize:\n ${redirectUrl.toString()}`);
});
// Create readline interface for user input
const readline = createInterface({
input: process.stdin,
output: process.stdout
});
let abortCommand = new AbortController();
// Global client and transport for interactive commands
let client = null;
let transport = null;
let serverUrl = 'http://localhost:3000/mcp';
let sessionId = undefined;
let isProcessingCommand = false;
let isProcessingElicitations = false;
const elicitationQueue = [];
let elicitationQueueSignal = null;
let elicitationsCompleteSignal = null;
// Map to track pending URL elicitations waiting for completion notifications
const pendingURLElicitations = new Map();
async function main() {
console.log('MCP Interactive Client');
console.log('=====================');
// Connect to server immediately with default settings
await connect();
// Start the elicitation loop in the background
elicitationLoop().catch(error => {
console.error('Unexpected error in elicitation loop:', error);
process.exit(1);
});
// Short delay allowing the server to send any SSE elicitations on connection
await new Promise(resolve => setTimeout(resolve, 200));
// Wait until we are done processing any initial elicitations
await waitForElicitationsToComplete();
// Print help and start the command loop
printHelp();
await commandLoop();
}
async function waitForElicitationsToComplete() {
// Wait until the queue is empty and nothing is being processed
while (elicitationQueue.length > 0 || isProcessingElicitations) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
function printHelp() {
console.log('\nAvailable commands:');
console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)');
console.log(' disconnect - Disconnect from server');
console.log(' terminate-session - Terminate the current session');
console.log(' reconnect - Reconnect to the server');
console.log(' list-tools - List available tools');
console.log(' call-tool <name> [args] - Call a tool with optional JSON arguments');
console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool');
console.log(' third-party-auth - Test tool that requires third-party OAuth credentials');
console.log(' help - Show this help');
console.log(' quit - Exit the program');
}
async function commandLoop() {
await new Promise(resolve => {
if (!isProcessingElicitations) {
resolve();
}
else {
elicitationsCompleteSignal = resolve;
}
});
readline.question('\n> ', { signal: abortCommand.signal }, async (input) => {
isProcessingCommand = true;
const args = input.trim().split(/\s+/);
const command = args[0]?.toLowerCase();
try {
switch (command) {
case 'connect':
await connect(args[1]);
break;
case 'disconnect':
await disconnect();
break;
case 'terminate-session':
await terminateSession();
break;
case 'reconnect':
await reconnect();
break;
case 'list-tools':
await listTools();
break;
case 'call-tool':
if (args.length < 2) {
console.log('Usage: call-tool <name> [args]');
}
else {
const toolName = args[1];
let toolArgs = {};
if (args.length > 2) {
try {
toolArgs = JSON.parse(args.slice(2).join(' '));
}
catch {
console.log('Invalid JSON arguments. Using empty args.');
}
}
await callTool(toolName, toolArgs);
}
break;
case 'payment-confirm':
await callPaymentConfirmTool();
break;
case 'third-party-auth':
await callThirdPartyAuthTool();
break;
case 'help':
printHelp();
break;
case 'quit':
case 'exit':
await cleanup();
return;
default:
if (command) {
console.log(`Unknown command: ${command}`);
}
break;
}
}
catch (error) {
console.error(`Error executing command: ${error}`);
}
finally {
isProcessingCommand = false;
}
// Process another command after we've processed the this one
await commandLoop();
});
}
async function elicitationLoop() {
while (true) {
// Wait until we have elicitations to process
await new Promise(resolve => {
if (elicitationQueue.length > 0) {
resolve();
}
else {
elicitationQueueSignal = resolve;
}
});
isProcessingElicitations = true;
abortCommand.abort(); // Abort the command loop if it's running
// Process all queued elicitations
while (elicitationQueue.length > 0) {
const queued = elicitationQueue.shift();
console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`);
try {
const result = await handleElicitationRequest(queued.request);
queued.resolve(result);
}
catch (error) {
queued.reject(error instanceof Error ? error : new Error(String(error)));
}
}
console.log('✅ All queued elicitations processed. Resuming command loop...\n');
isProcessingElicitations = false;
// Reset the abort controller for the next command loop
abortCommand = new AbortController();
// Resume the command loop
if (elicitationsCompleteSignal) {
elicitationsCompleteSignal();
elicitationsCompleteSignal = null;
}
}
}
/**
* Enqueues an elicitation request and returns the result.
*
* This function is used so that our CLI (which can only handle one input request at a time)
* can handle elicitation requests and the command loop.
*
* @param request - The elicitation request to be handled
* @returns The elicitation result
*/
async function elicitationRequestHandler(request) {
// If we are processing a command, handle this elicitation immediately
if (isProcessingCommand) {
console.log('📋 Processing elicitation immediately (during command execution)');
return await handleElicitationRequest(request);
}
// Otherwise, queue the request to be handled by the elicitation loop
console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`);
return new Promise((resolve, reject) => {
elicitationQueue.push({
request,
resolve,
reject
});
// Signal the elicitation loop that there's work to do
if (elicitationQueueSignal) {
elicitationQueueSignal();
elicitationQueueSignal = null;
}
});
}
/**
* Handles an elicitation request.
*
* This function is used to handle the elicitation request and return the result.
*
* @param request - The elicitation request to be handled
* @returns The elicitation result
*/
async function handleElicitationRequest(request) {
const mode = request.params.mode;
console.log('\n🔔 Elicitation Request Received:');
console.log(`Mode: ${mode}`);
if (mode === 'url') {
return {
action: await handleURLElicitation(request.params)
};
}
else {
// Should not happen because the client declares its capabilities to the server,
// but being defensive is a good practice:
throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`);
}
}
/**
* Handles a URL elicitation by opening the URL in the browser.
*
* Note: This is a shared code for both request handlers and error handlers.
* As a result of sharing schema, there is no big forking of logic for the client.
*
* @param params - The URL elicitation request parameters
* @returns The action to take (accept, cancel, or decline)
*/
async function handleURLElicitation(params) {
const url = params.url;
const elicitationId = params.elicitationId;
const message = params.message;
console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration
// Parse URL to show domain for security
let domain = 'unknown domain';
try {
const parsedUrl = new URL(url);
domain = parsedUrl.hostname;
}
catch {
console.error('Invalid URL provided by server');
return 'decline';
}
// Example security warning to help prevent phishing attacks
console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️');
console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m');
console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n');
console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`);
console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`);
console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`);
// 1. Ask for user consent to open the URL
const consent = await new Promise(resolve => {
readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => {
resolve(input.trim().toLowerCase());
});
});
// 2. If user did not consent, return appropriate result
if (consent === 'no' || consent === 'n') {
console.log('❌ URL navigation declined.');
return 'decline';
}
else if (consent !== 'yes' && consent !== 'y') {
console.log('🚫 Invalid response. Cancelling elicitation.');
return 'cancel';
}
// 3. Wait for completion notification in the background
const completionPromise = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pendingURLElicitations.delete(elicitationId);
console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`);
reject(new Error('Elicitation completion timeout'));
}, 5 * 60 * 1000); // 5 minute timeout
pendingURLElicitations.set(elicitationId, {
resolve: () => {
clearTimeout(timeout);
resolve();
},
reject,
timeout
});
});
completionPromise.catch(error => {
console.error('Background completion wait failed:', error);
});
// 4. Direct user to open the URL in their browser
console.log(`\n🔗 Please open this URL in your browser:\n ${url}`);
console.log('\n⏳ Waiting for you to complete the interaction in your browser...');
console.log(' The server will send a notification once you complete the action.');
// 5. Acknowledge the user accepted the elicitation
return 'accept';
}
/**
* Example OAuth callback handler - in production, use a more robust approach
* for handling callbacks and storing tokens
*/
/**
* Starts a temporary HTTP server to receive the OAuth callback
*/
async function waitForOAuthCallback() {
return new Promise((resolve, reject) => {
const server = createServer((req, res) => {
// Ignore favicon requests
if (req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
return;
}
console.log(`📥 Received callback: ${req.url}`);
const parsedUrl = new URL(req.url || '', 'http://localhost');
const code = parsedUrl.searchParams.get('code');
const error = parsedUrl.searchParams.get('error');
if (code) {
console.log(`✅ Authorization code received: ${code?.substring(0, 10)}...`);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Successful!</h1>
<p>This simulates successful authorization of the MCP client, which now has an access token for the MCP server.</p>
<p>This window will close automatically in 10 seconds.</p>
<script>setTimeout(() => window.close(), 10000);</script>
</body>
</html>
`);
resolve(code);
setTimeout(() => server.close(), 15000);
}
else if (error) {
console.log(`❌ Authorization error: ${error}`);
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<body>
<h1>Authorization Failed</h1>
<p>Error: ${error}</p>
</body>
</html>
`);
reject(new Error(`OAuth authorization failed: ${error}`));
}
else {
console.log(`❌ No authorization code or error in callback`);
res.writeHead(400);
res.end('Bad request');
reject(new Error('No authorization code provided'));
}
});
server.listen(OAUTH_CALLBACK_PORT, () => {
console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`);
});
});
}
/**
* Attempts to connect to the MCP server with OAuth authentication.
* Handles OAuth flow recursively if authorization is required.
*/
async function attemptConnection(oauthProvider) {
console.log('🚢 Creating transport with OAuth provider...');
const baseUrl = new URL(serverUrl);
transport = new StreamableHTTPClientTransport(baseUrl, {
sessionId: sessionId,
authProvider: oauthProvider
});
console.log('🚢 Transport created');
try {
console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...');
await client.connect(transport);
sessionId = transport.sessionId;
console.log('Transport created with session ID:', sessionId);
console.log('✅ Connected successfully');
}
catch (error) {
if (error instanceof UnauthorizedError) {
console.log('🔐 OAuth required - waiting for authorization...');
const callbackPromise = waitForOAuthCallback();
const authCode = await callbackPromise;
await transport.finishAuth(authCode);
console.log('🔐 Authorization code received:', authCode);
console.log('🔌 Reconnecting with authenticated transport...');
// Recursively retry connection after OAuth completion
await attemptConnection(oauthProvider);
}
else {
console.error('❌ Connection failed with non-auth error:', error);
throw error;
}
}
}
async function connect(url) {
if (client) {
console.log('Already connected. Disconnect first.');
return;
}
if (url) {
serverUrl = url;
}
console.log(`🔗 Attempting to connect to ${serverUrl}...`);
// Create a new client with elicitation capability
console.log('👤 Creating MCP client...');
client = new Client({
name: 'example-client',
version: '1.0.0'
}, {
capabilities: {
elicitation: {
// Only URL elicitation is supported in this demo
// (see server/elicitationExample.ts for a demo of form mode elicitation)
url: {}
}
}
});
console.log('👤 Client created');
// Set up elicitation request handler with proper validation
client.setRequestHandler(ElicitRequestSchema, elicitationRequestHandler);
// Set up notification handler for elicitation completion
client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => {
const { elicitationId } = notification.params;
const pending = pendingURLElicitations.get(elicitationId);
if (pending) {
clearTimeout(pending.timeout);
pendingURLElicitations.delete(elicitationId);
console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`);
pending.resolve();
}
else {
// Shouldn't happen - discard it!
console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`);
}
});
try {
console.log('🔐 Starting OAuth flow...');
await attemptConnection(oauthProvider);
console.log('Connected to MCP server');
// Set up error handler after connection is established so we don't double log errors
client.onerror = error => {
console.error('\x1b[31mClient error:', error, '\x1b[0m');
};
}
catch (error) {
console.error('Failed to connect:', error);
client = null;
transport = null;
return;
}
}
async function disconnect() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
await transport.close();
console.log('Disconnected from MCP server');
client = null;
transport = null;
}
catch (error) {
console.error('Error disconnecting:', error);
}
}
async function terminateSession() {
if (!client || !transport) {
console.log('Not connected.');
return;
}
try {
console.log('Terminating session with ID:', transport.sessionId);
await transport.terminateSession();
console.log('Session terminated successfully');
// Check if sessionId was cleared after termination
if (!transport.sessionId) {
console.log('Session ID has been cleared');
sessionId = undefined;
// Also close the transport and clear client objects
await transport.close();
console.log('Transport closed after session termination');
client = null;
transport = null;
}
else {
console.log('Server responded with 405 Method Not Allowed (session termination not supported)');
console.log('Session ID is still active:', transport.sessionId);
}
}
catch (error) {
console.error('Error terminating session:', error);
}
}
async function reconnect() {
if (client) {
await disconnect();
}
await connect();
}
async function listTools() {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const toolsRequest = {
method: 'tools/list',
params: {}
};
const toolsResult = await client.request(toolsRequest, ListToolsResultSchema);
console.log('Available tools:');
if (toolsResult.tools.length === 0) {
console.log(' No tools available');
}
else {
for (const tool of toolsResult.tools) {
console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`);
}
}
}
catch (error) {
console.log(`Tools not supported by this server (${error})`);
}
}
async function callTool(name, args) {
if (!client) {
console.log('Not connected to server.');
return;
}
try {
const request = {
method: 'tools/call',
params: {
name,
arguments: args
}
};
console.log(`Calling tool '${name}' with args:`, args);
const result = await client.request(request, CallToolResultSchema);
console.log('Tool result:');
const resourceLinks = [];
result.content.forEach(item => {
if (item.type === 'text') {
console.log(` ${item.text}`);
}
else if (item.type === 'resource_link') {
const resourceLink = item;
resourceLinks.push(resourceLink);
console.log(` 📁 Resource Link: ${resourceLink.name}`);
console.log(` URI: ${resourceLink.uri}`);
if (resourceLink.mimeType) {
console.log(` Type: ${resourceLink.mimeType}`);
}
if (resourceLink.description) {
console.log(` Description: ${resourceLink.description}`);
}
}
else if (item.type === 'resource') {
console.log(` [Embedded Resource: ${item.resource.uri}]`);
}
else if (item.type === 'image') {
console.log(` [Image: ${item.mimeType}]`);
}
else if (item.type === 'audio') {
console.log(` [Audio: ${item.mimeType}]`);
}
else {
console.log(` [Unknown content type]:`, item);
}
});
// Offer to read resource links
if (resourceLinks.length > 0) {
console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource <uri>' to read their content.`);
}
}
catch (error) {
if (error instanceof UrlElicitationRequiredError) {
console.log('\n🔔 Elicitation Required Error Received:');
console.log(`Message: ${error.message}`);
for (const e of error.elicitations) {
await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response
}
return;
}
console.log(`Error calling tool ${name}: ${error}`);
}
}
async function cleanup() {
if (client && transport) {
try {
// First try to terminate the session gracefully
if (transport.sessionId) {
try {
console.log('Terminating session before exit...');
await transport.terminateSession();
console.log('Session terminated successfully');
}
catch (error) {
console.error('Error terminating session:', error);
}
}
// Then close the transport
await transport.close();
}
catch (error) {
console.error('Error closing transport:', error);
}
}
process.stdin.setRawMode(false);
readline.close();
console.log('\nGoodbye!');
process.exit(0);
}
async function callPaymentConfirmTool() {
console.log('Calling payment-confirm tool...');
await callTool('payment-confirm', { cartId: 'cart_123' });
}
async function callThirdPartyAuthTool() {
console.log('Calling third-party-auth tool...');
await callTool('third-party-auth', { param1: 'test' });
}
// Set up raw mode for keyboard input to capture Escape key
process.stdin.setRawMode(true);
process.stdin.on('data', async (data) => {
// Check for Escape key (27)
if (data.length === 1 && data[0] === 27) {
console.log('\nESC key pressed. Disconnecting from server...');
// Abort current operation and disconnect from server
if (client && transport) {
await disconnect();
console.log('Disconnected. Press Enter to continue.');
}
else {
console.log('Not connected to server.');
}
// Re-display the prompt
process.stdout.write('> ');
}
});
// Handle Ctrl+C
process.on('SIGINT', async () => {
console.log('\nReceived SIGINT. Cleaning up...');
await cleanup();
});
// Start the interactive client
main().catch((error) => {
console.error('Error running MCP client:', error);
process.exit(1);
});
//# sourceMappingURL=elicitationUrlExample.js.map