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,922 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
interface Array<T> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S | undefined;
findLast(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): number;
/**
* Returns a copy of an array with its elements reversed.
*/
toReversed(): T[];
/**
* Returns a copy of an array with its elements sorted.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
* ```ts
* [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: T, b: T) => number): T[];
/**
* Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @param items Elements to insert into the copied array in place of the deleted elements.
* @returns The copied array.
*/
toSpliced(start: number, deleteCount: number, ...items: T[]): T[];
/**
* Copies an array and removes elements while returning the remaining elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @returns A copy of the original array with the remaining elements.
*/
toSpliced(start: number, deleteCount?: number): T[];
/**
* Copies an array, then overwrites the value at the provided index with the
* given value. If the index is negative, then it replaces from the end
* of the array.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to write into the copied array.
* @returns The copied array with the updated value.
*/
with(index: number, value: T): T[];
}
interface ReadonlyArray<T> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends T>(
predicate: (value: T, index: number, array: readonly T[]) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: T, index: number, array: readonly T[]) => unknown,
thisArg?: any,
): T | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (value: T, index: number, array: readonly T[]) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copied array with all of its elements reversed.
*/
toReversed(): T[];
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
* ```ts
* [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: T, b: T) => number): T[];
/**
* Copies an array and removes elements while, if necessary, inserting new elements in their place, returning the remaining elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @param items Elements to insert into the copied array in place of the deleted elements.
* @returns A copy of the original array with the remaining elements.
*/
toSpliced(start: number, deleteCount: number, ...items: T[]): T[];
/**
* Copies an array and removes elements while returning the remaining elements.
* @param start The zero-based location in the array from which to start removing elements.
* @param deleteCount The number of elements to remove.
* @returns A copy of the original array with the remaining elements.
*/
toSpliced(start: number, deleteCount?: number): T[];
/**
* Copies an array, then overwrites the value at the provided index with the
* given value. If the index is negative, then it replaces from the end
* of the array
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: T): T[];
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Int8Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Int8Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Int8Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Int8Array<ArrayBuffer>;
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint8Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint8Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint8Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint8Array<ArrayBuffer>;
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint8ClampedArray<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint8ClampedArray.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint8ClampedArray<ArrayBuffer>;
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Int16Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Int16Array.from([11, 2, -22, 1]);
* myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Int16Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Int16Array<ArrayBuffer>;
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint16Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint16Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint16Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint16Array<ArrayBuffer>;
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (value: number, index: number, array: this) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Int32Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Int32Array.from([11, 2, -22, 1]);
* myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Int32Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Int32Array<ArrayBuffer>;
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Uint32Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Uint32Array.from([11, 2, 22, 1]);
* myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Uint32Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Uint32Array<ArrayBuffer>;
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float32Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float32Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float32Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float32Array<ArrayBuffer>;
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends number>(
predicate: (
value: number,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: number,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): Float64Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = Float64Array.from([11.25, 2, -22.5, 1]);
* myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5]
* ```
*/
toSorted(compareFn?: (a: number, b: number) => number): Float64Array<ArrayBuffer>;
/**
* Copies the array and inserts the given number at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: number): Float64Array<ArrayBuffer>;
}
interface BigInt64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends bigint>(
predicate: (
value: bigint,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: bigint,
index: number,
array: this,
) => unknown,
thisArg?: any,
): bigint | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: bigint,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): BigInt64Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]);
* myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n]
* ```
*/
toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array<ArrayBuffer>;
/**
* Copies the array and inserts the given bigint at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: bigint): BigInt64Array<ArrayBuffer>;
}
interface BigUint64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the value of the last element in the array where predicate is true, and undefined
* otherwise.
* @param predicate findLast calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found, findLast
* immediately returns that element value. Otherwise, findLast returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLast<S extends bigint>(
predicate: (
value: bigint,
index: number,
array: this,
) => value is S,
thisArg?: any,
): S | undefined;
findLast(
predicate: (
value: bigint,
index: number,
array: this,
) => unknown,
thisArg?: any,
): bigint | undefined;
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param predicate findLastIndex calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findLastIndex(
predicate: (
value: bigint,
index: number,
array: this,
) => unknown,
thisArg?: any,
): number;
/**
* Copies the array and returns the copy with the elements in reverse order.
*/
toReversed(): BigUint64Array<ArrayBuffer>;
/**
* Copies and sorts the array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if the first argument is less than the second argument, zero if they're equal, and a positive
* value otherwise. If omitted, the elements are sorted in ascending order.
* ```ts
* const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]);
* myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n]
* ```
*/
toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array<ArrayBuffer>;
/**
* Copies the array and inserts the given bigint at the provided index.
* @param index The index of the value to overwrite. If the index is
* negative, then it replaces from the end of the array.
* @param value The value to insert into the copied array.
* @returns A copy of the original array with the inserted value.
*/
with(index: number, value: bigint): BigUint64Array<ArrayBuffer>;
}
@@ -0,0 +1,27 @@
import { toSSG as toSSG$1 } from "../../helper/ssg/ssg.js";
import "../../helper/ssg/index.js";
//#region src/adapter/bun/ssg.ts
const { write } = Bun;
/**
* @experimental
* `bunFileSystemModule` is an experimental feature.
* The API might be changed.
* @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.
*/
const bunFileSystemModule = {
writeFile: async (path, data) => {
await write(path, data);
},
mkdir: async () => {}
};
/**
* @experimental
* `toSSG` is an experimental feature.
* The API might be changed.
* @deprecated `hono/bun` will be removed in v5. Install `@hono/bun` and import from there instead.
*/
const toSSG = async (app, options) => {
return toSSG$1(app, bunFileSystemModule, options);
};
//#endregion
export { bunFileSystemModule, toSSG };
@@ -0,0 +1,21 @@
/**
* @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 TicketsPlane = createLucideIcon("TicketsPlane", [
["path", { d: "M10.5 17h1.227a2 2 0 0 0 1.345-.52L18 12", key: "16muxl" }],
["path", { d: "m12 13.5 3.75.5", key: "1i9qhk" }],
["path", { d: "m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8", key: "12lg5p" }],
["path", { d: "M6 10V8", key: "1y41hn" }],
["path", { d: "M6 14v1", key: "cao2tf" }],
["path", { d: "M6 19v2", key: "1loha6" }],
["rect", { x: "2", y: "8", width: "20", height: "13", rx: "2", key: "p3bz5l" }]
]);
export { TicketsPlane as default };
//# sourceMappingURL=tickets-plane.js.map
@@ -0,0 +1,105 @@
import { expect, test } from "vitest";
import * as z from "zod/v4";
test("locales - uz", () => {
z.config(z.locales.uz());
const invalidType = z.number().safeParse("a");
expect(invalidType.error!.issues[0].code).toBe("invalid_type");
expect(invalidType.error!.issues[0].message).toBe("Noto‘g‘ri kirish: kutilgan raqam, qabul qilingan string");
const invalidType2 = z.string().safeParse(1);
expect(invalidType2.error!.issues[0].code).toBe("invalid_type");
expect(invalidType2.error!.issues[0].message).toBe("Noto‘g‘ri kirish: kutilgan string, qabul qilingan raqam");
const invalidValue = z.enum(["a", "b"]).safeParse(1);
expect(invalidValue.error!.issues[0].code).toBe("invalid_value");
expect(invalidValue.error!.issues[0].message).toBe('Noto‘g‘ri variant: quyidagilardan biri kutilgan "a"|"b"');
const tooBig = z.number().max(10).safeParse(15);
expect(tooBig.error!.issues[0].code).toBe("too_big");
expect(tooBig.error!.issues[0].message).toBe("Juda katta: kutilgan number <=10");
const tooSmall = z.number().min(10).safeParse(5);
expect(tooSmall.error!.issues[0].code).toBe("too_small");
expect(tooSmall.error!.issues[0].message).toBe("Juda kichik: kutilgan number >=10");
const invalidFormatRegex = z.string().regex(/abcd/).safeParse("invalid-string");
expect(invalidFormatRegex.error!.issues[0].code).toBe("invalid_format");
expect(invalidFormatRegex.error!.issues[0].message).toContain("shabloniga mos kelishi kerak");
const invalidFormatStartsWith = z.string().startsWith("abcd").safeParse("invalid-string");
expect(invalidFormatStartsWith.error!.issues[0].code).toBe("invalid_format");
expect(invalidFormatStartsWith.error!.issues[0].message).toContain('"abcd" bilan boshlanishi kerak');
const notMultipleOf = z.number().multipleOf(3).safeParse(10);
expect(notMultipleOf.error!.issues[0].code).toBe("not_multiple_of");
expect(notMultipleOf.error!.issues[0].message).toContain("3 ning karralisi bo‘lishi kerak");
const unrecognizedKeys = z.object({ a: z.string(), b: z.number() }).strict().safeParse({ a: "a", b: 1, c: 2 });
expect(unrecognizedKeys.error!.issues[0].code).toBe("unrecognized_keys");
expect(unrecognizedKeys.error!.issues[0].message).toContain('Noma’lum kalit: "c"');
const invalidUnion = z.union([z.string(), z.number()]).safeParse(true);
expect(invalidUnion.error!.issues[0].code).toBe("invalid_union");
expect(invalidUnion.error!.issues[0].message).toBe("Noto‘g‘ri kirish");
const tooBigString = z.string().max(5).safeParse("too long string");
expect(tooBigString.error!.issues[0].code).toBe("too_big");
expect(tooBigString.error!.issues[0].message).toContain("belgi");
expect(tooBigString.error!.issues[0].message).toContain("bo‘lishi kerak");
const tooSmallArray = z.array(z.string()).min(3).safeParse(["a", "b"]);
expect(tooSmallArray.error!.issues[0].code).toBe("too_small");
expect(tooSmallArray.error!.issues[0].message).toContain("element");
expect(tooSmallArray.error!.issues[0].message).toContain("bo‘lishi kerak");
const invalidFormatEndsWith = z.string().endsWith("xyz").safeParse("invalid-string");
expect(invalidFormatEndsWith.error!.issues[0].code).toBe("invalid_format");
expect(invalidFormatEndsWith.error!.issues[0].message).toContain('"xyz" bilan tugashi kerak');
const invalidFormatIncludes = z.string().includes("test").safeParse("invalid-string");
expect(invalidFormatIncludes.error!.issues[0].code).toBe("invalid_format");
expect(invalidFormatIncludes.error!.issues[0].message).toContain('"test" ni o‘z ichiga olishi kerak');
const invalidFormatEmail = z.string().email().safeParse("invalid-email");
expect(invalidFormatEmail.error!.issues[0].code).toBe("invalid_format");
expect(invalidFormatEmail.error!.issues[0].message).toContain("elektron pochta manzili");
const invalidFormatUrl = z.string().url().safeParse("invalid-url");
expect(invalidFormatUrl.error!.issues[0].code).toBe("invalid_format");
expect(invalidFormatUrl.error!.issues[0].message).toContain("URL");
const unrecognizedKeysMultiple = z
.object({ a: z.string(), b: z.number() })
.strict()
.safeParse({ a: "a", b: 1, c: 2, d: 3 });
expect(unrecognizedKeysMultiple.error!.issues[0].code).toBe("unrecognized_keys");
expect(unrecognizedKeysMultiple.error!.issues[0].message).toContain("Noma’lum kalitlar");
const invalidElement = z.array(z.string()).safeParse([1, 2, 3]);
expect(invalidElement.error!.issues[0].code).toBe("invalid_type");
expect(invalidElement.error!.issues[0].message).toContain("raqam");
const tooSmallMap = z
.map(z.string(), z.string())
.min(3)
.safeParse(new Map([["a", "b"]]));
expect(tooSmallMap.error!.issues[0].code).toBe("too_small");
expect(tooSmallMap.error!.issues[0].message).toContain("yozuv");
expect(tooSmallMap.error!.issues[0].message).toContain("bo‘lishi kerak");
const tooBigMap = z
.map(z.string(), z.string())
.max(2)
.safeParse(
new Map([
["a", "b"],
["c", "d"],
["e", "f"],
])
);
expect(tooBigMap.error!.issues[0].code).toBe("too_big");
expect(tooBigMap.error!.issues[0].message).toContain("yozuv");
expect(tooBigMap.error!.issues[0].message).toContain("bo‘lishi kerak");
});
@@ -0,0 +1,786 @@
//#region src/core/compat.d.ts
/**
* References
* - https://compat-table.github.io/compat-table/es6/
* - MDN
*/
declare enum Feature {
AggregateError = 1,
ArrowFunction = 2,
ErrorPrototypeStack = 4,
ObjectAssign = 8,
BigIntTypedArray = 16,
RegExp = 32,
Temporal = 64
}
//#endregion
//#region src/core/constants.d.ts
declare const enum SerovalConstant {
Null = 0,
Undefined = 1,
True = 2,
False = 3,
NegZero = 4,
Inf = 5,
NegInf = 6,
Nan = 7
}
declare const enum SerovalNodeType {
Number = 0,
String = 1,
Constant = 2,
BigInt = 3,
IndexedValue = 4,
Date = 5,
RegExp = 6,
Set = 7,
Map = 8,
Array = 9,
Object = 10,
NullConstructor = 11,
Promise = 12,
Error = 13,
AggregateError = 14,
TypedArray = 15,
BigIntTypedArray = 16,
WKSymbol = 17,
Reference = 18,
ArrayBuffer = 19,
DataView = 20,
Boxed = 21,
PromiseConstructor = 22,
PromiseSuccess = 23,
PromiseFailure = 24,
Plugin = 25,
SpecialReference = 26,
IteratorFactory = 27,
IteratorFactoryInstance = 28,
AsyncIteratorFactory = 29,
AsyncIteratorFactoryInstance = 30,
StreamConstructor = 31,
StreamNext = 32,
StreamThrow = 33,
StreamReturn = 34,
Sequence = 35,
Temporal = 36
}
declare const enum SerovalTemporalType {
Instant = 0,
Duration = 1,
PlainDate = 2,
PlainDateTime = 3,
PlainMonthDay = 4,
PlainTime = 5,
PlainYearMonth = 6,
ZonedDateTime = 7
}
declare const enum SerovalObjectFlags {
None = 0,
NonExtensible = 1,
Sealed = 2,
Frozen = 3
}
declare const enum Symbols {
AsyncIterator = 0,
HasInstance = 1,
IsConcatSpreadable = 2,
Iterator = 3,
Match = 4,
MatchAll = 5,
Replace = 6,
Search = 7,
Species = 8,
Split = 9,
ToPrimitive = 10,
ToStringTag = 11,
Unscopables = 12
}
declare const enum ErrorConstructorTag {
Error = 0,
EvalError = 1,
RangeError = 2,
ReferenceError = 3,
SyntaxError = 4,
TypeError = 5,
URIError = 6
}
//#endregion
//#region src/core/special-reference.d.ts
declare const enum SpecialReference {
MapSentinel = 0,
PromiseConstructor = 1,
PromiseSuccess = 2,
PromiseFailure = 3,
StreamConstructor = 4,
ArrayBufferConstructor = 5
}
//#endregion
//#region src/core/types.d.ts
interface SerovalBaseNode {
t: SerovalNodeType;
i: number | undefined;
s: unknown;
c: string | SerovalTemporalType | undefined;
m: string | undefined;
p: SerovalObjectRecordNode | undefined;
e: SerovalMapRecordNode | undefined;
a: (SerovalNode | 0)[] | undefined;
f: SerovalNode | undefined;
b: number | undefined;
o: SerovalObjectFlags | undefined;
l: number | undefined;
}
type SerovalObjectRecordKey = string | SerovalNode;
interface SerovalObjectRecordNode {
k: SerovalObjectRecordKey[];
v: SerovalNode[];
}
interface SerovalMapRecordNode {
k: SerovalNode[];
v: SerovalNode[];
}
interface SerovalNumberNode extends SerovalBaseNode {
t: SerovalNodeType.Number;
s: number;
}
interface SerovalStringNode extends SerovalBaseNode {
t: SerovalNodeType.String;
s: string;
}
interface SerovalConstantNode extends SerovalBaseNode {
t: SerovalNodeType.Constant;
s: SerovalConstant;
}
type SerovalPrimitiveNode = SerovalNumberNode | SerovalStringNode | SerovalConstantNode;
interface SerovalIndexedValueNode extends SerovalBaseNode {
t: SerovalNodeType.IndexedValue;
i: number;
}
interface SerovalBigIntNode extends SerovalBaseNode {
t: SerovalNodeType.BigInt;
s: string;
}
interface SerovalDateNode extends SerovalBaseNode {
t: SerovalNodeType.Date;
i: number;
s: string;
}
interface SerovalRegExpNode extends SerovalBaseNode {
t: SerovalNodeType.RegExp;
i: number;
c: string;
m: string;
}
interface SerovalArrayBufferNode extends SerovalBaseNode {
t: SerovalNodeType.ArrayBuffer;
i: number;
s: string;
f: SerovalNodeWithID;
}
interface SerovalTypedArrayNode extends SerovalBaseNode {
t: SerovalNodeType.TypedArray;
i: number;
c: string;
f: SerovalNode;
b: number;
l: number;
}
interface SerovalBigIntTypedArrayNode extends SerovalBaseNode {
t: SerovalNodeType.BigIntTypedArray;
i: number;
c: string;
f: SerovalNode;
b: number;
l: number;
}
interface SerovalTemporalNode extends SerovalBaseNode {
t: SerovalNodeType.Temporal;
i: number;
c: SerovalTemporalType;
s: string;
}
type SerovalSemiPrimitiveNode = SerovalBigIntNode | SerovalDateNode | SerovalRegExpNode | SerovalTypedArrayNode | SerovalBigIntTypedArrayNode | SerovalTemporalNode;
interface SerovalSetNode extends SerovalBaseNode {
t: SerovalNodeType.Set;
i: number;
a: SerovalNode[];
}
interface SerovalMapNode extends SerovalBaseNode {
t: SerovalNodeType.Map;
i: number;
e: SerovalMapRecordNode;
f: SerovalNodeWithID;
}
interface SerovalArrayNode extends SerovalBaseNode {
t: SerovalNodeType.Array;
a: (SerovalNode | 0)[];
i: number;
o: SerovalObjectFlags;
}
interface SerovalObjectNode extends SerovalBaseNode {
t: SerovalNodeType.Object;
p: SerovalObjectRecordNode;
i: number;
o: SerovalObjectFlags;
}
interface SerovalNullConstructorNode extends SerovalBaseNode {
t: SerovalNodeType.NullConstructor;
p: SerovalObjectRecordNode;
i: number;
o: SerovalObjectFlags;
}
interface SerovalPromiseNode extends SerovalBaseNode {
t: SerovalNodeType.Promise;
s: 0 | 1;
f: SerovalNode;
i: number;
}
interface SerovalErrorNode extends SerovalBaseNode {
t: SerovalNodeType.Error;
s: ErrorConstructorTag;
m: string;
p: SerovalObjectRecordNode | undefined;
i: number;
}
interface SerovalAggregateErrorNode extends SerovalBaseNode {
t: SerovalNodeType.AggregateError;
i: number;
m: string;
p: SerovalObjectRecordNode | undefined;
}
interface SerovalWKSymbolNode extends SerovalBaseNode {
t: SerovalNodeType.WKSymbol;
i: number;
s: Symbols;
}
interface SerovalReferenceNode extends SerovalBaseNode {
t: SerovalNodeType.Reference;
i: number;
s: string;
}
interface SerovalDataViewNode extends SerovalBaseNode {
t: SerovalNodeType.DataView;
i: number;
f: SerovalNode;
b: number;
l: number;
}
interface SerovalBoxedNode extends SerovalBaseNode {
t: SerovalNodeType.Boxed;
i: number;
f: SerovalNode;
}
interface SerovalPromiseConstructorNode extends SerovalBaseNode {
t: SerovalNodeType.PromiseConstructor;
i: number;
s: number;
f: SerovalNodeWithID;
}
interface SerovalPromiseResolveNode extends SerovalBaseNode {
t: SerovalNodeType.PromiseSuccess;
i: number;
a: [resolver: SerovalNodeWithID, resolved: SerovalNode];
}
interface SerovalPromiseRejectNode extends SerovalBaseNode {
t: SerovalNodeType.PromiseFailure;
i: number;
a: [resolver: SerovalNodeWithID, resolved: SerovalNode];
}
interface SerovalPluginNode extends SerovalBaseNode {
t: SerovalNodeType.Plugin;
i: number;
s: Record<string, SerovalNode>;
c: string;
}
/**
* Represents special values as placeholders
*/
interface SerovalSpecialReferenceNode extends SerovalBaseNode {
t: SerovalNodeType.SpecialReference;
i: number;
s: SpecialReference;
}
interface SerovalIteratorFactoryNode extends SerovalBaseNode {
t: SerovalNodeType.IteratorFactory;
i: number;
f: SerovalNodeWithID;
}
interface SerovalIteratorFactoryInstanceNode extends SerovalBaseNode {
t: SerovalNodeType.IteratorFactoryInstance;
a: [instance: SerovalNodeWithID, sequence: SerovalNodeWithID];
}
interface SerovalAsyncIteratorFactoryNode extends SerovalBaseNode {
t: SerovalNodeType.AsyncIteratorFactory;
i: number;
a: [promise: SerovalNodeWithID, symbol: SerovalNodeWithID];
}
interface SerovalAsyncIteratorFactoryInstanceNode extends SerovalBaseNode {
t: SerovalNodeType.AsyncIteratorFactoryInstance;
a: [instance: SerovalNodeWithID, sequence: SerovalNodeWithID];
}
interface SerovalStreamConstructorNode extends SerovalBaseNode {
t: SerovalNodeType.StreamConstructor;
i: number;
a: SerovalNode[];
f: SerovalNodeWithID;
}
interface SerovalStreamNextNode extends SerovalBaseNode {
t: SerovalNodeType.StreamNext;
i: number;
f: SerovalNode;
}
interface SerovalStreamThrowNode extends SerovalBaseNode {
t: SerovalNodeType.StreamThrow;
i: number;
f: SerovalNode;
}
interface SerovalStreamReturnNode extends SerovalBaseNode {
t: SerovalNodeType.StreamReturn;
i: number;
f: SerovalNode;
}
interface SerovalSequenceNode extends SerovalBaseNode {
t: SerovalNodeType.Sequence;
i: number;
s: number;
a: SerovalNode[];
l: number;
}
type SerovalSyncNode = SerovalPrimitiveNode | SerovalIndexedValueNode | SerovalSemiPrimitiveNode | SerovalSetNode | SerovalMapNode | SerovalArrayNode | SerovalObjectNode | SerovalNullConstructorNode | SerovalPromiseNode | SerovalErrorNode | SerovalAggregateErrorNode | SerovalWKSymbolNode | SerovalReferenceNode | SerovalArrayBufferNode | SerovalDataViewNode | SerovalBoxedNode | SerovalPluginNode | SerovalSpecialReferenceNode | SerovalIteratorFactoryNode | SerovalIteratorFactoryInstanceNode | SerovalAsyncIteratorFactoryNode | SerovalAsyncIteratorFactoryInstanceNode | SerovalSequenceNode;
type SerovalAsyncNode = SerovalPromiseNode | SerovalPromiseConstructorNode | SerovalPromiseResolveNode | SerovalPromiseRejectNode | SerovalStreamConstructorNode | SerovalStreamNextNode | SerovalStreamThrowNode | SerovalStreamReturnNode;
type SerovalNode = SerovalSyncNode | SerovalAsyncNode;
type SerovalNodeWithID = Extract<SerovalNode, {
i: number;
}>;
//#endregion
//#region src/core/context/deserializer.d.ts
interface BaseDeserializerContextOptions extends PluginAccessOptions {
refs?: Map<number, unknown>;
features?: number;
disabledFeatures?: number;
depthLimit?: number;
/** Maximum encoded characters per ArrayBuffer. Defaults to 1,000,000. */
maxBase64Length?: number;
}
interface BaseDeserializerContext extends PluginAccessOptions {
readonly mode: SerovalMode;
/**
* Mapping ids to values
*/
refs: Map<number, unknown> & {
types: Map<number, SerovalNodeType>;
};
features: number;
depthLimit: number;
maxBase64Length: number;
}
interface VanillaDeserializerContextOptions extends Omit<BaseDeserializerContextOptions, 'refs'> {
markedRefs: number[] | Set<number>;
}
interface VanillaDeserializerState {
marked: Set<number>;
}
interface VanillaDeserializerContext {
mode: SerovalMode.Vanilla;
base: BaseDeserializerContext;
child: DeserializePluginContext | undefined;
state: VanillaDeserializerState;
}
interface CrossDeserializerContext {
mode: SerovalMode.Cross;
base: BaseDeserializerContext;
child: DeserializePluginContext | undefined;
}
type CrossDeserializerContextOptions = BaseDeserializerContextOptions;
type DeserializerContext = VanillaDeserializerContext | CrossDeserializerContext;
declare class DeserializePluginContext {
private _p;
private depth;
constructor(_p: DeserializerContext, depth: number);
deserialize<T>(node: SerovalNode): T;
}
//#endregion
//#region src/core/context/serializer.d.ts
declare const enum AssignmentType {
Index = 0,
Add = 1,
Set = 2,
Delete = 3,
Define = 4
}
interface IndexAssignment {
t: AssignmentType.Index;
s: string;
k: undefined;
v: string;
}
interface SetAssignment {
t: AssignmentType.Set;
s: string;
k: string;
v: string;
}
interface AddAssignment {
t: AssignmentType.Add;
s: string;
k: undefined;
v: string;
}
interface DeleteAssignment {
t: AssignmentType.Delete;
s: string;
k: string;
v: undefined;
}
interface DefineAssignment {
t: AssignmentType.Define;
s: string;
k: string;
v: undefined;
}
type Assignment = IndexAssignment | AddAssignment | SetAssignment | DeleteAssignment | DefineAssignment;
interface FlaggedObject {
type: SerovalObjectFlags;
value: string;
}
interface BaseSerializerContextOptions extends PluginAccessOptions {
features: number;
markedRefs: number[] | Set<number>;
}
interface BaseSerializerContext extends PluginAccessOptions {
readonly mode: SerovalMode;
features: number;
stack: number[];
/**
* Array of object mutations
*/
flags: FlaggedObject[];
/**
* Array of assignments to be done (used for recursion)
*/
assignments: Assignment[];
/**
* Refs that are...referenced
*/
marked: Set<number>;
}
interface CrossContextOptions {
scopeId?: string;
}
interface VanillaSerializerState {
valid: Map<number, number>;
vars: string[];
}
interface VanillaSerializerContext {
mode: SerovalMode.Vanilla;
base: BaseSerializerContext;
state: VanillaSerializerState;
child: SerializePluginContext | undefined;
}
type VanillaSerializerContextOptions = BaseSerializerContextOptions;
interface CrossSerializerContext {
mode: SerovalMode.Cross;
base: BaseSerializerContext;
state: CrossContextOptions;
child: SerializePluginContext | undefined;
}
interface CrossSerializerContextOptions extends BaseSerializerContextOptions, CrossContextOptions {}
type SerializerContext = VanillaSerializerContext | CrossSerializerContext;
declare class SerializePluginContext {
private _p;
constructor(_p: SerializerContext);
serialize(node: SerovalNode): string;
}
//#endregion
//#region src/core/context/parser.d.ts
interface BaseParserContextOptions extends PluginAccessOptions {
disabledFeatures?: number;
refs?: Map<unknown, number>;
depthLimit?: number;
/** Copy each typed array or DataView's visible bytes into its own buffer. */
compactArrayBufferViews?: boolean;
}
interface BaseParserContext extends PluginAccessOptions {
readonly mode: SerovalMode;
marked: Set<number>;
refs: Map<unknown, number>;
features: number;
depthLimit: number;
compactArrayBufferViews: boolean;
}
//#endregion
//#region src/core/context/sync-parser.d.ts
type SyncParserContextOptions = BaseParserContextOptions;
declare const enum ParserMode {
Sync = 1,
Stream = 2
}
interface SyncParserContext {
type: ParserMode.Sync;
base: BaseParserContext;
child: SyncParsePluginContext | undefined;
}
declare class SyncParsePluginContext {
private _p;
private depth;
constructor(_p: SyncParserContext, depth: number);
parse<T>(current: T): SerovalNode;
}
interface StreamParserContextOptions extends SyncParserContextOptions {
onParse: (node: SerovalNode, initial: boolean) => void;
onError?: (error: unknown) => void;
onDone?: () => void;
}
interface StreamParserContext {
type: ParserMode.Stream;
base: BaseParserContext;
state: StreamParserState;
}
declare class StreamParsePluginContext {
private _p;
private depth;
constructor(_p: StreamParserContext, depth: number);
parse<T>(current: T): SerovalNode;
parseWithError<T>(current: T): SerovalNode | undefined;
isAlive(): boolean;
pushPendingState(): void;
popPendingState(): void;
onParse(node: SerovalNode): void;
onError(error: unknown): void;
addCleanup(callback: () => void): void;
}
interface StreamParserState {
alive: boolean;
pending: number;
initial: boolean;
buffer: SerovalNode[];
onParse: (node: SerovalNode, initial: boolean) => void;
onError?: (error: unknown) => void;
onDone?: () => void;
cleanups: (() => void)[];
}
//#endregion
//#region src/core/plugin.d.ts
declare const enum SerovalMode {
Vanilla = 1,
Cross = 2
}
interface PluginData {
id: number;
}
type PluginInfo = {
[key: string]: SerovalNode;
};
interface Plugin<Value, Info extends PluginInfo> {
/**
* A unique string that helps idenfity the plugin
*/
tag: string;
/**
* List of dependency plugins
*/
extends?: Plugin<any, any>[];
/**
* Method to test if a value is an expected value of the plugin
* @param value
*/
test(value: unknown): boolean;
/**
* Parsing modes
*/
parse: {
sync?: (value: Value, ctx: SyncParsePluginContext, data: PluginData) => Info;
async?: (value: Value, ctx: AsyncParsePluginContext, data: PluginData) => Promise<Info>;
stream?: (value: Value, ctx: StreamParsePluginContext, data: PluginData) => Info;
};
/**
* Convert the parsed node into a JS string
*/
serialize(node: Info, ctx: SerializePluginContext, data: PluginData): string;
/**
* Convert the parsed node into its runtime equivalent.
*/
deserialize(node: Info, ctx: DeserializePluginContext, data: PluginData): Value;
}
declare function createPlugin<Value, Info extends PluginInfo>(plugin: Plugin<Value, Info>): Plugin<Value, Info>;
interface PluginAccessOptions {
plugins?: Plugin<any, any>[];
}
declare function resolvePlugins(plugins?: Plugin<any, any>[]): Plugin<any, any>[] | undefined;
//#endregion
//#region src/core/context/async-parser.d.ts
type AsyncParserContextOptions = BaseParserContextOptions;
interface AsyncParserContext {
base: BaseParserContext;
child: AsyncParsePluginContext | undefined;
}
declare class AsyncParsePluginContext {
private _p;
private depth;
constructor(_p: AsyncParserContext, depth: number);
parse<T>(current: T): Promise<SerovalNode>;
}
//#endregion
//#region src/core/cross/index.d.ts
interface CrossSerializeOptions extends SyncParserContextOptions, CrossContextOptions {}
declare function crossSerialize<T>(source: T, options?: CrossSerializeOptions): string;
interface CrossSerializeAsyncOptions extends AsyncParserContextOptions, CrossContextOptions {}
declare function crossSerializeAsync<T>(source: T, options?: CrossSerializeAsyncOptions): Promise<string>;
type ToCrossJSONOptions = SyncParserContextOptions;
declare function toCrossJSON<T>(source: T, options?: ToCrossJSONOptions): SerovalNode;
type ToCrossJSONAsyncOptions = AsyncParserContextOptions;
declare function toCrossJSONAsync<T>(source: T, options?: ToCrossJSONAsyncOptions): Promise<SerovalNode>;
interface CrossSerializeStreamOptions extends Omit<StreamParserContextOptions, 'onParse'>, CrossContextOptions {
onSerialize: (data: string, initial: boolean) => void;
}
declare function crossSerializeStream<T>(source: T, options: CrossSerializeStreamOptions): () => void;
type ToCrossJSONStreamOptions = StreamParserContextOptions;
declare function toCrossJSONStream<T>(source: T, options: ToCrossJSONStreamOptions): () => void;
type FromCrossJSONOptions = CrossDeserializerContextOptions;
declare function fromCrossJSON<T>(source: SerovalNode, options: FromCrossJSONOptions): T;
//#endregion
//#region src/core/errors.d.ts
declare class SerovalError extends Error {
cause: unknown;
constructor(type: string, cause: unknown);
}
declare class SerovalParserError extends SerovalError {
constructor(cause: unknown);
}
declare class SerovalSerializationError extends SerovalError {
constructor(cause: unknown);
}
declare class SerovalDeserializationError extends SerovalError {
constructor(cause: unknown);
}
declare class SerovalUnsupportedTypeError extends Error {
value: unknown;
constructor(value: unknown);
}
declare class SerovalUnsupportedNodeError extends Error {
constructor(node: SerovalNode);
}
declare class SerovalMissingPluginError extends Error {
constructor(tag: string);
}
declare class SerovalMissingInstanceError extends Error {
constructor(tag: string);
}
declare class SerovalMissingReferenceError extends Error {
value: unknown;
constructor(value: unknown);
}
declare class SerovalMissingReferenceForIdError extends Error {
constructor(id: string);
}
declare class SerovalUnknownTypedArrayError extends Error {
constructor(name: string);
}
declare class SerovalMalformedNodeError extends Error {
constructor(node: SerovalNode);
}
declare class SerovalConflictedNodeIdError extends Error {
constructor(node: SerovalNode);
}
declare class SerovalDepthLimitError extends Error {
constructor(limit: number);
}
//#endregion
//#region src/core/keys.d.ts
declare function getCrossReferenceHeader(id?: string): string;
//#endregion
//#region src/core/opaque-reference.d.ts
/**
* An opaque reference allows hiding values from the serializer.
*/
declare class OpaqueReference<V, R = undefined> {
readonly value: V;
readonly replacement?: R | undefined;
constructor(value: V, replacement?: R | undefined);
}
//#endregion
//#region src/core/reference.d.ts
declare function createReference<T>(id: string, value: T): T;
//#endregion
//#region src/core/Serializer.d.ts
interface SerializerOptions extends PluginAccessOptions {
globalIdentifier: string;
scopeId?: string;
disabledFeatures?: number;
compactArrayBufferViews?: boolean;
onData: (result: string) => void;
onError: (error: unknown) => void;
onDone?: () => void;
}
declare class Serializer {
private options;
private alive;
private flushed;
private done;
private pending;
private cleanups;
private refs;
private plugins?;
constructor(options: SerializerOptions);
keys: Set<string>;
write(key: string, value: unknown): void;
ids: number;
private getNextID;
push(value: unknown): string;
flush(): void;
close(): void;
}
//#endregion
//#region src/core/stream.d.ts
interface StreamListener<T> {
next(value: T): void;
throw(value: unknown): void;
return(value: T): void;
}
/**
* An internal class rather than a tagged POJO: identity is checked with
* `instanceof`, which untrusted input cannot forge (the class is not exported).
*
* The behavior is intentionally duplicated from `STREAM_CONSTRUCTOR`. That
* constructor's source is embedded verbatim into the eval-based `deserialize`
* output, which has no access to this class, so the two cannot be shared. A
* stream read back through `deserialize` is therefore a plain POJO and, by
* design, is not treated as a genuine Stream on re-serialization. Keep the two
* implementations in sync.
*/
declare class Stream<T> {
private buffer;
private listeners;
private alive;
private success;
private count;
private flush;
private replay;
on(listener: StreamListener<T>): () => void;
next(value: T): void;
throw(value: unknown): void;
return(value: T): void;
}
declare function isStream<T>(value: unknown): value is Stream<T>;
declare function createStream<T>(): Stream<T>;
//#endregion
//#region src/core/tree/index.d.ts
type SyncParserContextOptions$1 = Omit<BaseParserContextOptions, 'refs'>;
type AsyncParserContextOptions$1 = Omit<BaseParserContextOptions, 'refs'>;
declare function serialize<T>(source: T, options?: SyncParserContextOptions$1): string;
declare function serializeAsync<T>(source: T, options?: AsyncParserContextOptions$1): Promise<string>;
declare function deserialize<T>(source: string): T;
interface SerovalJSON {
t: SerovalNode;
f: number;
m: number[];
}
interface FromJSONOptions extends PluginAccessOptions, Pick<BaseDeserializerContextOptions, 'maxBase64Length'> {
disabledFeatures?: number;
}
declare function toJSON<T>(source: T, options?: SyncParserContextOptions$1): SerovalJSON;
declare function toJSONAsync<T>(source: T, options?: AsyncParserContextOptions$1): Promise<SerovalJSON>;
declare function compileJSON(source: SerovalJSON, options?: PluginAccessOptions): string;
declare function fromJSON<T>(source: SerovalJSON, options?: FromJSONOptions): T;
//#endregion
export { type AsyncParsePluginContext, AsyncParserContextOptions, type BaseDeserializerContextOptions, type BaseParserContextOptions, type BaseSerializerContextOptions, type CrossContextOptions, type CrossDeserializerContextOptions, CrossSerializeAsyncOptions, CrossSerializeOptions, CrossSerializeStreamOptions, type CrossSerializerContextOptions, type DeserializePluginContext, Feature, FromCrossJSONOptions, FromJSONOptions, OpaqueReference, Plugin, PluginAccessOptions, PluginData, PluginInfo, type SerializePluginContext, Serializer, SerovalConflictedNodeIdError, SerovalDepthLimitError, SerovalDeserializationError, SerovalError, SerovalJSON, SerovalMalformedNodeError, SerovalMissingInstanceError, SerovalMissingPluginError, SerovalMissingReferenceError, SerovalMissingReferenceForIdError, SerovalMode, type SerovalNode, SerovalParserError, SerovalSerializationError, SerovalUnknownTypedArrayError, SerovalUnsupportedNodeError, SerovalUnsupportedTypeError, type Stream, type StreamListener, type StreamParsePluginContext, type StreamParserContextOptions, type SyncParsePluginContext, SyncParserContextOptions, ToCrossJSONAsyncOptions, ToCrossJSONOptions, ToCrossJSONStreamOptions, type VanillaDeserializerContextOptions, type VanillaSerializerContextOptions, compileJSON, createPlugin, createReference, createStream, crossSerialize, crossSerializeAsync, crossSerializeStream, deserialize, fromCrossJSON, fromJSON, getCrossReferenceHeader, isStream, resolvePlugins, serialize, serializeAsync, toCrossJSON, toCrossJSONAsync, toCrossJSONStream, toJSON, toJSONAsync };
@@ -0,0 +1,353 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MotionUtils = {}));
})(this, (function (exports) { 'use strict';
function addUniqueItem(arr, item) {
if (arr.indexOf(item) === -1)
arr.push(item);
}
function removeItem(arr, item) {
const index = arr.indexOf(item);
if (index > -1)
arr.splice(index, 1);
}
// Adapted from array-move
function moveItem([...arr], fromIndex, toIndex) {
const startIndex = fromIndex < 0 ? arr.length + fromIndex : fromIndex;
if (startIndex >= 0 && startIndex < arr.length) {
const endIndex = toIndex < 0 ? arr.length + toIndex : toIndex;
const [item] = arr.splice(fromIndex, 1);
arr.splice(endIndex, 0, item);
}
return arr;
}
const clamp = (min, max, v) => {
if (v > max)
return max;
if (v < min)
return min;
return v;
};
function formatErrorMessage(message, errorCode) {
return errorCode
? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}`
: message;
}
exports.warning = () => { };
exports.invariant = () => { };
if (typeof process !== "undefined" &&
process.env?.NODE_ENV !== "production") {
exports.warning = (check, message, errorCode) => {
if (!check && typeof console !== "undefined") {
console.warn(formatErrorMessage(message, errorCode));
}
};
exports.invariant = (check, message, errorCode) => {
if (!check) {
throw new Error(formatErrorMessage(message, errorCode));
}
};
}
const MotionGlobalConfig = {};
/**
* Check if value is a numerical string, ie a string that is purely a number eg "100" or "-100.1"
*/
const isNumericalString = (v) => /^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(v);
function isObject(value) {
return typeof value === "object" && value !== null;
}
/**
* Check if the value is a zero value string like "0px" or "0%"
*/
const isZeroValueString = (v) => /^0[^.\s]+$/u.test(v);
/*#__NO_SIDE_EFFECTS__*/
function memo(callback) {
let result;
return () => {
if (result === undefined)
result = callback();
return result;
};
}
/*#__NO_SIDE_EFFECTS__*/
const noop = (any) => any;
/**
* Pipe
* Compose other transformers to run linearily
* pipe(min(20), max(40))
* @param {...functions} transformers
* @return {function}
*/
const combineFunctions = (a, b) => (v) => b(a(v));
const pipe = (...transformers) => transformers.reduce(combineFunctions);
/*
Progress within given range
Given a lower limit and an upper limit, we return the progress
(expressed as a number 0-1) represented by the given value, and
limit that progress to within 0-1.
@param [number]: Lower limit
@param [number]: Upper limit
@param [number]: Value to find progress within given range
@return [number]: Progress of value within range as expressed 0-1
*/
/*#__NO_SIDE_EFFECTS__*/
const progress = (from, to, value) => {
const toFromDifference = to - from;
return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
};
class SubscriptionManager {
constructor() {
this.subscriptions = [];
}
add(handler) {
addUniqueItem(this.subscriptions, handler);
return () => removeItem(this.subscriptions, handler);
}
notify(a, b, c) {
const numSubscriptions = this.subscriptions.length;
if (!numSubscriptions)
return;
if (numSubscriptions === 1) {
/**
* If there's only a single handler we can just call it without invoking a loop.
*/
this.subscriptions[0](a, b, c);
}
else {
for (let i = 0; i < numSubscriptions; i++) {
/**
* Check whether the handler exists before firing as it's possible
* the subscriptions were modified during this loop running.
*/
const handler = this.subscriptions[i];
handler && handler(a, b, c);
}
}
}
getSize() {
return this.subscriptions.length;
}
clear() {
this.subscriptions.length = 0;
}
}
/**
* Converts seconds to milliseconds
*
* @param seconds - Time in seconds.
* @return milliseconds - Converted time in milliseconds.
*/
/*#__NO_SIDE_EFFECTS__*/
const secondsToMilliseconds = (seconds) => seconds * 1000;
/*#__NO_SIDE_EFFECTS__*/
const millisecondsToSeconds = (milliseconds) => milliseconds / 1000;
/*
Convert velocity into velocity per second
@param [number]: Unit per frame
@param [number]: Frame duration in ms
*/
function velocityPerSecond(velocity, frameDuration) {
return frameDuration ? velocity * (1000 / frameDuration) : 0;
}
const warned = new Set();
function hasWarned(message) {
return warned.has(message);
}
function warnOnce(condition, message, errorCode) {
if (condition || warned.has(message))
return;
console.warn(formatErrorMessage(message, errorCode));
warned.add(message);
}
const wrap = (min, max, v) => {
const rangeSize = max - min;
return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
};
/*
Bezier function generator
This has been modified from Gaëtan Renaudeau's BezierEasing
https://github.com/gre/bezier-easing/blob/master/src/index.js
https://github.com/gre/bezier-easing/blob/master/LICENSE
I've removed the newtonRaphsonIterate algo because in benchmarking it
wasn't noticeably faster than binarySubdivision, indeed removing it
usually improved times, depending on the curve.
I also removed the lookup table, as for the added bundle size and loop we're
only cutting ~4 or so subdivision iterations. I bumped the max iterations up
to 12 to compensate and this still tended to be faster for no perceivable
loss in accuracy.
Usage
const easeOut = cubicBezier(.17,.67,.83,.67);
const x = easeOut(0.5); // returns 0.627...
*/
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) *
t;
const subdivisionPrecision = 0.0000001;
const subdivisionMaxIterations = 12;
function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
let currentX;
let currentT;
let i = 0;
do {
currentT = lowerBound + (upperBound - lowerBound) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - x;
if (currentX > 0.0) {
upperBound = currentT;
}
else {
lowerBound = currentT;
}
} while (Math.abs(currentX) > subdivisionPrecision &&
++i < subdivisionMaxIterations);
return currentT;
}
function cubicBezier(mX1, mY1, mX2, mY2) {
// If this is a linear gradient, return linear easing
if (mX1 === mY1 && mX2 === mY2)
return noop;
const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
// If animation is at start/end, return t without easing
return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
}
// Accepts an easing function and returns a new one that outputs mirrored values for
// the second half of the animation. Turns easeIn into easeInOut.
const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;
// Accepts an easing function and returns a new one that outputs reversed values.
// Turns easeIn into easeOut.
const reverseEasing = (easing) => (p) => 1 - easing(1 - p);
const backOut = /*@__PURE__*/ cubicBezier(0.33, 1.53, 0.69, 0.99);
const backIn = /*@__PURE__*/ reverseEasing(backOut);
const backInOut = /*@__PURE__*/ mirrorEasing(backIn);
const anticipate = (p) => p >= 1
? 1
: (p *= 2) < 1
? 0.5 * backIn(p)
: 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
const circIn = (p) => 1 - Math.sin(Math.acos(p));
const circOut = reverseEasing(circIn);
const circInOut = mirrorEasing(circIn);
const easeIn = /*@__PURE__*/ cubicBezier(0.42, 0, 1, 1);
const easeOut = /*@__PURE__*/ cubicBezier(0, 0, 0.58, 1);
const easeInOut = /*@__PURE__*/ cubicBezier(0.42, 0, 0.58, 1);
function steps(numSteps, direction = "end") {
return (progress) => {
progress =
direction === "end"
? Math.min(progress, 0.999)
: Math.max(progress, 0.001);
const expanded = progress * numSteps;
const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
return clamp(0, 1, rounded / numSteps);
};
}
const isEasingArray = (ease) => {
return Array.isArray(ease) && typeof ease[0] !== "number";
};
function getEasingForSegment(easing, i) {
return isEasingArray(easing) ? easing[wrap(0, easing.length, i)] : easing;
}
const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number";
const easingLookup = {
linear: noop,
easeIn,
easeInOut,
easeOut,
circIn,
circInOut,
circOut,
backIn,
backInOut,
backOut,
anticipate,
};
const isValidEasing = (easing) => {
return typeof easing === "string";
};
const easingDefinitionToFunction = (definition) => {
if (isBezierDefinition(definition)) {
// If cubic bezier definition, create bezier curve
exports.invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`, "cubic-bezier-length");
const [x1, y1, x2, y2] = definition;
return cubicBezier(x1, y1, x2, y2);
}
else if (isValidEasing(definition)) {
// Else lookup from table
exports.invariant(easingLookup[definition] !== undefined, `Invalid easing type '${definition}'`, "invalid-easing-type");
return easingLookup[definition];
}
return definition;
};
exports.MotionGlobalConfig = MotionGlobalConfig;
exports.SubscriptionManager = SubscriptionManager;
exports.addUniqueItem = addUniqueItem;
exports.anticipate = anticipate;
exports.backIn = backIn;
exports.backInOut = backInOut;
exports.backOut = backOut;
exports.circIn = circIn;
exports.circInOut = circInOut;
exports.circOut = circOut;
exports.clamp = clamp;
exports.cubicBezier = cubicBezier;
exports.easeIn = easeIn;
exports.easeInOut = easeInOut;
exports.easeOut = easeOut;
exports.easingDefinitionToFunction = easingDefinitionToFunction;
exports.getEasingForSegment = getEasingForSegment;
exports.hasWarned = hasWarned;
exports.isBezierDefinition = isBezierDefinition;
exports.isEasingArray = isEasingArray;
exports.isNumericalString = isNumericalString;
exports.isObject = isObject;
exports.isZeroValueString = isZeroValueString;
exports.memo = memo;
exports.millisecondsToSeconds = millisecondsToSeconds;
exports.mirrorEasing = mirrorEasing;
exports.moveItem = moveItem;
exports.noop = noop;
exports.pipe = pipe;
exports.progress = progress;
exports.removeItem = removeItem;
exports.reverseEasing = reverseEasing;
exports.secondsToMilliseconds = secondsToMilliseconds;
exports.steps = steps;
exports.velocityPerSecond = velocityPerSecond;
exports.warnOnce = warnOnce;
exports.wrap = wrap;
}));
@@ -0,0 +1,11 @@
import { MatcherBaseClass, MatchExtended, UserInputsOptions } from './types';
import Options from './Options';
declare class Matching {
private options;
matchers: Record<string, MatcherBaseClass>;
constructor(options: Options);
private processResult;
private handlePromises;
match(password: string, userInputsOptions?: UserInputsOptions): MatchExtended[] | Promise<MatchExtended[]>;
}
export default Matching;
@@ -0,0 +1,41 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/helper/adapter/index.ts
const env = (c, runtime) => {
const globalEnv = globalThis?.process?.env;
runtime ??= getRuntimeKey();
return {
bun: () => globalEnv,
node: () => globalEnv,
"edge-light": () => globalEnv,
deno: () => {
return Deno.env.toObject();
},
workerd: () => c.env,
fastly: () => ({}),
other: () => ({})
}[runtime]();
};
const knownUserAgents = {
deno: "Deno",
bun: "Bun",
workerd: "Cloudflare-Workers",
node: "Node.js"
};
const getRuntimeKey = () => {
const global = globalThis;
if (typeof navigator !== "undefined" && typeof navigator.userAgent === "string") {
for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) if (checkUserAgentEquals(userAgent)) return runtimeKey;
}
if (typeof global?.EdgeRuntime === "string") return "edge-light";
if (global?.fastly !== void 0) return "fastly";
if (global?.process?.release?.name === "node") return "node";
return "other";
};
const checkUserAgentEquals = (platform) => {
return navigator.userAgent.startsWith(platform);
};
//#endregion
exports.checkUserAgentEquals = checkUserAgentEquals;
exports.env = env;
exports.getRuntimeKey = getRuntimeKey;
exports.knownUserAgents = knownUserAgents;
@@ -0,0 +1,24 @@
/**
* @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 Hotel = createLucideIcon("Hotel", [
["path", { d: "M10 22v-6.57", key: "1wmca3" }],
["path", { d: "M12 11h.01", key: "z322tv" }],
["path", { d: "M12 7h.01", key: "1ivr5q" }],
["path", { d: "M14 15.43V22", key: "1q2vjd" }],
["path", { d: "M15 16a5 5 0 0 0-6 0", key: "o9wqvi" }],
["path", { d: "M16 11h.01", key: "xkw8gn" }],
["path", { d: "M16 7h.01", key: "1kdx03" }],
["path", { d: "M8 11h.01", key: "1dfujw" }],
["path", { d: "M8 7h.01", key: "1vti4s" }],
["rect", { x: "4", y: "2", width: "16", height: "20", rx: "2", key: "1uxh74" }]
]);
export { Hotel as default };
//# sourceMappingURL=hotel.js.map
@@ -0,0 +1,421 @@
flf2a$ 4 3 9 63 12 0 8127 0
Author : Marcin Glinsky and others
Date : 2003/09/02 20:09:19
Version: 1.0
-------------------------------------------------
Font ascii_new_roman, created by Marcin Glinski
and others from alt.ascii-art
-------------------------------------------------
This font has been created using JavE's FIGlet font export assistant.
Have a look at: http://www.jave.de
Permission is hereby given to modify this font, as long as the
modifier's name is placed on a comment line.
$ #
$ #
$ #
$ ##
__, #
(-V #
_o #
( ##
"#
#
#
##
##
#
#
##
_||_, #
(-(__ #
_||_) #
( ##
_, _,#
(-o ,' #
_,',o'#
( ##
&#
#
#
##
__, #
(-/ #
#
##
____, #
(-// #
_\\_ #
( ##
___, #
(-\\ #
_//_ #
( ##
*#
#
#
##
___, #
(-_|_. #
_| #
( ##
,#
#
#
##
#
____, #
( #
##
.#
#
#
##
___, #
(-// #
_//_ #
( ##
_____,#
(-/ /\ #
_\/_/ #
( ##
___, #
(-/| #
'_|, #
( ##
__, #
(- ) #
,'_, #
( ##
__, #
(-_) #
__) #
( ##
____, #
(-/_|_,#
_|, #
( ##
____, #
(-|_ #
__) #
( ##
___, #
(-/_ #
_(__) #
( ##
___, #
(- / #
_/, #
( ##
_____,#
(-(__) #
_(__) #
( ##
_____,#
(-(__) #
__/, #
( ##
__, #
(-o #
_o #
( ##
__, #
(-o #
_p #
( ##
<#
#
#
##
=#
#
#
##
>#
#
#
##
_____,#
(-( _)#
_(, #
( ##
___, #
(-/_\ #
_((_/_#
( ##
____,#
(-/_| #
_/ |,#
( ##
____ #
(-|__) #
_|__) #
( ##
____, #
(-/ #
_\__, #
( ##
____, #
(-| \ #
_|__/ #
( ##
____, #
(-|_, #
_|__, #
( ##
____, #
(-|_, #
_| #
( ##
____, #
(-/ _, #
_\__| #
( ##
__, _,#
(-|__| #
_| |,#
( ##
__, #
(-| #
_|_, #
( ##
_, #
(-| #
__|, #
( ##
__, , #
( |_/ #
_| \, #
( ##
__, #
(-| #
_|__, #
( ##
__, _,#
(-|\/| #
_| _|,#
( ##
_, _,#
(-|\ | #
_| \|,#
( ##
____, #
(-/ \ #
_\__/,#
( ##
____, #
(-|__) #
_| #
( ##
____, #
(-/ \ #
_\_\/,#
( ##
____, #
(-|__) #
_| \,#
( ##
____, #
(-(__ #
____) #
( ##
____, #
(-| #
_|, #
( ##
_, _, #
(-| \ #
_|__/ #
( ##
__ _,#
(-\ / #
_\/ #
( ##
_ _,#
(-| | #
_|/\|,#
( ##
_, _, #
(-\_/ #
_/ \, #
( ##
_ _, #
(-\_/ #
_|, #
( ##
___, #
(- / #
_/__, #
( ##
[#
#
#
##
_, #
(-\\ #
_\\, #
( ##
]#
#
#
##
___, #
(-/\ #
' ` #
##
_#
#
#
##
`#
#
#
##
____,#
(-/_| #
_/ |,#
( ##
____ #
(-|__) #
_|__) #
( ##
____, #
(-/ #
_\__, #
( ##
____, #
(-| \ #
_|__/ #
( ##
____, #
(-|_, #
_|__, #
( ##
____, #
(-|_, #
_| #
( ##
____, #
(-/ _, #
_\__| #
( ##
__, _,#
(-|__| #
_| |,#
( ##
__, #
(-| #
_|_, #
( ##
_, #
(-| #
__|, #
( ##
__, , #
( |_/ #
_| \, #
( ##
__, #
(-| #
_|__, #
( ##
__, _,#
(-|\/| #
_| _|,#
( ##
_, _,#
(-|\ | #
_| \|,#
( ##
____, #
(-/ \ #
_\__/,#
( ##
____, #
(-|__) #
_| #
( ##
____, #
(-/ \ #
_\_\/,#
( ##
____, #
(-|__) #
_| \,#
( ##
____, #
(-(__ #
____) #
( ##
____, #
(-| #
_|, #
( ##
_, _, #
(-| \ #
_|__/ #
( ##
__ _,#
(-\ / #
_\/ #
( ##
_ _,#
(-| | #
_|/\|,#
( ##
_, _, #
(-\_/ #
_/ \, #
( ##
_ _, #
(-\_/ #
_|, #
( ##
___, #
(- / #
_/__, #
( ##
{#
#
#
##
__, #
(-| #
| #
_|, ##
}#
#
#
##
~#
#
#
##
____,#
(-/_| #
_/ |,#
( ##
____, #
(-/ \ #
_\__/,#
( ##
_, _, #
(-| \ #
_|__/ #
( ##
____,#
(-/_| #
_/ |,#
( ##
____, #
(-/ \ #
_\__/,#
( ##
_, _, #
(-| \ #
_|__/ #
( ##
ß#
#
#
##
@@ -0,0 +1,7 @@
import { URISchemeHandler, URIOptions } from "../uri";
import { URNComponents } from "./urn";
export interface UUIDComponents extends URNComponents {
uuid?: string;
}
declare const handler: URISchemeHandler<UUIDComponents, URIOptions, URNComponents>;
export default handler;
@@ -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 SquareChartGantt = createLucideIcon("SquareChartGantt", [
["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", key: "afitv7" }],
["path", { d: "M9 8h7", key: "kbo1nt" }],
["path", { d: "M8 12h6", key: "ikassy" }],
["path", { d: "M11 16h5", key: "oq65wt" }]
]);
export { SquareChartGantt as default };
//# sourceMappingURL=square-chart-gantt.js.map
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"2":"_pJ _MB _lH _i","578":"_xH _NL"},C:{"1":"_gK","2":"_bB _RO _L","322":"jB","2370":"_xN _kI _cM _aK","8258":"kB","16450":"_ZP _wC"},D:{"1":"_wC","2":"_xF _MB _lH _kI _aP cB","194":"_xH _NL","4162":"_0N","6210":"dB _ZM"},E:{"2":"_yG","3076":"_6D"},F:{"2":"_0B _QJ _2J _nU CB _O","194":"_9P _4E _1J","4162":"DB _PP"},G:{"2":"_YN","3076":"_UE"},H:{"2":"1D"},I:{"2":"_P"},J:{"2":"_B"},K:{"2":"_N"},L:{"4162":"I"},M:{"2":"YC"},N:{"2":"_A"},O:{"2":"bC"},P:{"2":"_F"},Q:{"2":"JE"},R:{"2":"KE"},S:{"2":"_C"}},B:6,C:"JPEG\xA0XL (JXL) image format",D:true};
@@ -0,0 +1 @@
module.exports={C:{"78":0.0037,"115":0.03326,"120":0.08868,"121":0.18475,"123":0.01109,"124":0.00739,"140":0.01109,"143":0.0037,"144":0.0037,"145":0.0037,"146":0.0037,"147":0.00739,"148":0.00739,"150":0.00739,"151":0.01109,"152":0.01478,"153":0.02217,"154":0.21062,"155":0.56903,"156":0.40645,"157":0.01848,"158":0.0037,_:"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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 116 117 118 119 122 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 141 142 149 159 160 3.5 3.6"},D:{"70":0.0037,"76":0.0037,"79":0.00739,"87":0.00739,"97":0.00739,"101":0.0037,"103":0.09607,"104":0.0776,"105":0.08129,"106":0.08129,"107":0.0776,"108":0.08129,"109":0.42493,"110":0.08129,"111":0.11455,"112":0.0739,"114":0.0037,"115":0.01109,"116":0.18475,"117":0.0776,"118":0.1478,"119":0.18845,"120":0.28452,"121":0.0037,"122":0.03326,"123":0.01478,"124":0.10346,"125":0.00739,"126":0.03326,"127":0.0037,"128":0.02956,"130":0.01478,"131":0.14411,"132":0.01478,"133":0.21431,"134":0.0776,"135":0.07021,"136":0.08129,"137":0.08129,"138":0.11455,"139":0.09607,"140":0.10716,"141":0.09238,"142":0.26974,"143":0.01478,"144":0.06282,"145":0.05173,"146":0.03326,"147":0.03326,"148":0.10716,"149":0.0776,"150":0.26604,"151":1.76621,"152":9.07123,"153":7.11288,"154":1.72187,"155":0.01848,_:"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 63 64 65 66 67 68 69 71 72 73 74 75 77 78 80 81 83 84 85 86 88 89 90 91 92 93 94 95 96 98 99 100 102 113 129 156 157"},F:{"95":0.01109,"101":0.01109,"102":0.0037,"106":0.0037,"120":0.0037,"134":0.13302,"135":0.6688,_:"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 96 97 98 99 100 103 104 105 107 108 109 110 111 112 113 114 115 116 117 118 119 121 122 123 124 125 126 127 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.0037,"92":0.0037,"109":0.0037,"119":0.08499,"120":0.09238,"122":0.0037,"131":0.0037,"134":0.00739,"135":0.01109,"136":0.0037,"139":0.00739,"141":0.0037,"142":0.00739,"143":0.0037,"144":0.00739,"145":0.01478,"146":0.0037,"147":0.00739,"148":0.01109,"149":0.02956,"150":0.04434,"151":0.18845,"152":1.65167,"153":1.71448,"154":0.46927,_:"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 114 115 116 117 118 121 123 124 125 126 127 128 129 130 132 133 137 138 140"},E:{"27":0.1478,_:"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 14.1 15.1 15.2-15.3 15.4 16.0 16.2 16.3 16.4 16.5 17.0 27.1 TP","13.1":0.0037,"15.5":0.0037,"15.6":0.01109,"16.1":0.0037,"16.6":0.02956,"17.1":0.02956,"17.2":0.0037,"17.3":0.0037,"17.4":0.00739,"17.5":0.0037,"17.6":0.04065,"18.0":0.0037,"18.1":0.0037,"18.2":0.00739,"18.3":0.01478,"18.4":0.00739,"18.5-18.7":0.03326,"26.0":0.04434,"26.1":0.03695,"26.2":0.05173,"26.3":0.02587,"26.4":0.01848,"26.5":0.19584,"26.6":0.70944,"27.2":0.00739},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00126,"5.0-5.1":0.00126,"6.0-6.1":0,"7.0-7.1":0.00252,"8.1-8.4":0,"9.0-9.2":0,"9.3":0,"10.0-10.2":0,"10.3":0.01259,"11.0-11.2":0.00126,"11.3-11.4":0.00252,"12.0-12.1":0,"12.2-12.5":0.03274,"13.0-13.1":0,"13.2":0.0063,"13.3":0,"13.4-13.7":0.00126,"14.0-14.4":0.00504,"14.5-14.8":0.00756,"15.0-15.1":0.00756,"15.2-15.3":0.00504,"15.4":0.0063,"15.5":0.00756,"15.6-15.8":0.16371,"16.0":0.01259,"16.1":0.02267,"16.2":0.01259,"16.3":0.0277,"16.4":0.0063,"16.5":0.01007,"16.6-16.7":0.22793,"17.0":0.00882,"17.1":0.01259,"17.2":0.01259,"17.3":0.01889,"17.4":0.02645,"17.5":0.05163,"17.6-17.7":0.13349,"18.0":0.0277,"18.1":0.05541,"18.2":0.07556,"18.3":0.13097,"18.4":0.08186,"18.5-18.7":1.69125,"26.0":0.08186,"26.1":0.08311,"26.2":0.2166,"26.3":0.23423,"26.4":0.17127,"26.5":1.14723,"26.6":7.07857,"27.0":0.54276,"27.1":0,"27.2":0.01385},P:{"22":0.00956,"23":0.01912,"24":0.01912,"25":0.01912,"26":0.01912,"27":0.02868,"28":0.14339,"29":0.11471,"30":2.60972,_:"4 20 21 5.0-5.4 6.2-6.4 8.2 9.2 10.1 11.1-11.2 12.0 14.0 15.0 16.0 17.0 18.0 19.0","7.2-7.4":0.00956,"13.0":0.00956},I:{"0":0.0126,"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.00001},K:{"0":0.19549,_:"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":49.53103},R:{_:"0"},M:{"0":0.25224},Q:{_:"14.9"},O:{"0":0.02522},H:{all:0}};
@@ -0,0 +1,87 @@
{
"name": "ignore",
"version": "7.0.5",
"description": "Ignore is a manager and filter for .gitignore rules, the one used by eslint, gitbook and many others.",
"types": "index.d.ts",
"files": [
"legacy.js",
"index.js",
"index.d.ts",
"LICENSE-MIT"
],
"scripts": {
"prepublishOnly": "npm run build",
"build": "babel -o legacy.js index.js",
"==================== linting ======================": "",
"lint": "eslint .",
"===================== import ======================": "",
"ts": "npm run test:ts && npm run test:16",
"test:ts": "ts-node ./test/import/simple.ts",
"test:16": "npm run test:ts:16 && npm run test:cjs:16 && npm run test:mjs:16",
"test:ts:16": "ts-node --compilerOptions '{\"moduleResolution\": \"Node16\", \"module\": \"Node16\"}' ./test/import/simple.ts && tsc ./test/import/simple.ts --lib ES6 --moduleResolution Node16 --module Node16 && node ./test/import/simple.js",
"test:cjs:16": "ts-node --compilerOptions '{\"moduleResolution\": \"Node16\", \"module\": \"Node16\"}' ./test/import/simple.cjs",
"test:mjs:16": "ts-node --compilerOptions '{\"moduleResolution\": \"Node16\", \"module\": \"Node16\"}' ./test/import/simple.mjs && babel -o ./test/import/simple-mjs.js ./test/import/simple.mjs && node ./test/import/simple-mjs.js",
"===================== cases =======================": "",
"test:cases": "npm run tap test/*.test.js -- --coverage",
"tap": "tap --reporter classic",
"===================== debug =======================": "",
"test:git": "npm run tap test/git-check-ignore.test.js",
"test:ignore": "npm run tap test/ignore.test.js",
"test:ignore:only": "IGNORE_ONLY_IGNORES=1 npm run tap test/ignore.test.js",
"test:others": "npm run tap test/others.test.js",
"test:no-coverage": "npm run tap test/*.test.js -- --no-check-coverage",
"test": "npm run lint && npm run ts && npm run build && npm run test:cases",
"test:win32": "IGNORE_TEST_WIN32=1 npm run test",
"report": "tap --coverage-report=html"
},
"repository": {
"type": "git",
"url": "git@github.com:kaelzhang/node-ignore.git"
},
"keywords": [
"ignore",
".gitignore",
"gitignore",
"npmignore",
"rules",
"manager",
"filter",
"regexp",
"regex",
"fnmatch",
"glob",
"asterisks",
"regular-expression"
],
"author": "kael",
"license": "MIT",
"bugs": {
"url": "https://github.com/kaelzhang/node-ignore/issues"
},
"devDependencies": {
"@babel/cli": "^7.22.9",
"@babel/core": "^7.22.9",
"@babel/preset-env": "^7.22.9",
"@typescript-eslint/eslint-plugin": "^8.19.1",
"debug": "^4.3.4",
"eslint": "^8.46.0",
"eslint-config-ostai": "^3.0.0",
"eslint-plugin-import": "^2.28.0",
"mkdirp": "^3.0.1",
"pre-suf": "^1.1.1",
"rimraf": "^6.0.1",
"spawn-sync": "^2.0.0",
"tap": "^16.3.9",
"tmp": "0.2.3",
"ts-node": "^10.9.2",
"typescript": "^5.6.2"
},
"engines": {
"node": ">= 4"
}
}
@@ -0,0 +1,17 @@
//#region src/adapter/service-worker/types.d.ts
interface ExtendableEvent extends Event {
waitUntil(f: Promise<any>): void;
}
/**
* @deprecated `hono/service-worker` will be removed in v5. Install `@hono/service-worker` and import from there instead.
*/
export interface FetchEvent extends ExtendableEvent {
readonly clientId: string;
readonly handled: Promise<void>;
readonly preloadResponse: Promise<any>;
readonly request: Request;
readonly resultingClientId: string;
respondWith(r: Response | PromiseLike<Response>): void;
}
//#endregion
export {};
@@ -0,0 +1,384 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
const KEYS = {
ArrayExpression: [
"elements"
],
ArrayPattern: [
"elements"
],
ArrowFunctionExpression: [
"params",
"body"
],
AssignmentExpression: [
"left",
"right"
],
AssignmentPattern: [
"left",
"right"
],
AwaitExpression: [
"argument"
],
BinaryExpression: [
"left",
"right"
],
BlockStatement: [
"body"
],
BreakStatement: [
"label"
],
CallExpression: [
"callee",
"arguments"
],
CatchClause: [
"param",
"body"
],
ChainExpression: [
"expression"
],
ClassBody: [
"body"
],
ClassDeclaration: [
"id",
"superClass",
"body"
],
ClassExpression: [
"id",
"superClass",
"body"
],
ConditionalExpression: [
"test",
"consequent",
"alternate"
],
ContinueStatement: [
"label"
],
DebuggerStatement: [],
DoWhileStatement: [
"body",
"test"
],
EmptyStatement: [],
ExperimentalRestProperty: [
"argument"
],
ExperimentalSpreadProperty: [
"argument"
],
ExportAllDeclaration: [
"exported",
"source"
],
ExportDefaultDeclaration: [
"declaration"
],
ExportNamedDeclaration: [
"declaration",
"specifiers",
"source"
],
ExportSpecifier: [
"exported",
"local"
],
ExpressionStatement: [
"expression"
],
ForInStatement: [
"left",
"right",
"body"
],
ForOfStatement: [
"left",
"right",
"body"
],
ForStatement: [
"init",
"test",
"update",
"body"
],
FunctionDeclaration: [
"id",
"params",
"body"
],
FunctionExpression: [
"id",
"params",
"body"
],
Identifier: [],
IfStatement: [
"test",
"consequent",
"alternate"
],
ImportDeclaration: [
"specifiers",
"source"
],
ImportDefaultSpecifier: [
"local"
],
ImportExpression: [
"source"
],
ImportNamespaceSpecifier: [
"local"
],
ImportSpecifier: [
"imported",
"local"
],
JSXAttribute: [
"name",
"value"
],
JSXClosingElement: [
"name"
],
JSXClosingFragment: [],
JSXElement: [
"openingElement",
"children",
"closingElement"
],
JSXEmptyExpression: [],
JSXExpressionContainer: [
"expression"
],
JSXFragment: [
"openingFragment",
"children",
"closingFragment"
],
JSXIdentifier: [],
JSXMemberExpression: [
"object",
"property"
],
JSXNamespacedName: [
"namespace",
"name"
],
JSXOpeningElement: [
"name",
"attributes"
],
JSXOpeningFragment: [],
JSXSpreadAttribute: [
"argument"
],
JSXSpreadChild: [
"expression"
],
JSXText: [],
LabeledStatement: [
"label",
"body"
],
Literal: [],
LogicalExpression: [
"left",
"right"
],
MemberExpression: [
"object",
"property"
],
MetaProperty: [
"meta",
"property"
],
MethodDefinition: [
"key",
"value"
],
NewExpression: [
"callee",
"arguments"
],
ObjectExpression: [
"properties"
],
ObjectPattern: [
"properties"
],
PrivateIdentifier: [],
Program: [
"body"
],
Property: [
"key",
"value"
],
PropertyDefinition: [
"key",
"value"
],
RestElement: [
"argument"
],
ReturnStatement: [
"argument"
],
SequenceExpression: [
"expressions"
],
SpreadElement: [
"argument"
],
StaticBlock: [
"body"
],
Super: [],
SwitchCase: [
"test",
"consequent"
],
SwitchStatement: [
"discriminant",
"cases"
],
TaggedTemplateExpression: [
"tag",
"quasi"
],
TemplateElement: [],
TemplateLiteral: [
"quasis",
"expressions"
],
ThisExpression: [],
ThrowStatement: [
"argument"
],
TryStatement: [
"block",
"handler",
"finalizer"
],
UnaryExpression: [
"argument"
],
UpdateExpression: [
"argument"
],
VariableDeclaration: [
"declarations"
],
VariableDeclarator: [
"id",
"init"
],
WhileStatement: [
"test",
"body"
],
WithStatement: [
"object",
"body"
],
YieldExpression: [
"argument"
]
};
// Types.
const NODE_TYPES = Object.keys(KEYS);
// Freeze the keys.
for (const type of NODE_TYPES) {
Object.freeze(KEYS[type]);
}
Object.freeze(KEYS);
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
/**
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
*/
// List to ignore keys.
const KEY_BLACKLIST = new Set([
"parent",
"leadingComments",
"trailingComments"
]);
/**
* Check whether a given key should be used or not.
* @param {string} key The key to check.
* @returns {boolean} `true` if the key should be used.
*/
function filterKey(key) {
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
}
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
function getKeys(node) {
return Object.keys(node).filter(filterKey);
}
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
// eslint-disable-next-line valid-jsdoc
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
function unionWith(additionalKeys) {
const retv = /** @type {{
[type: string]: ReadonlyArray<string>
}} */ (Object.assign({}, KEYS));
for (const type of Object.keys(additionalKeys)) {
if (Object.prototype.hasOwnProperty.call(retv, type)) {
const keys = new Set(additionalKeys[type]);
for (const key of retv[type]) {
keys.add(key);
}
retv[type] = Object.freeze(Array.from(keys));
} else {
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
}
}
return Object.freeze(retv);
}
exports.KEYS = KEYS;
exports.getKeys = getKeys;
exports.unionWith = unionWith;
@@ -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 ListCheck = createLucideIcon("ListCheck", [
["path", { d: "M11 18H3", key: "n3j2dh" }],
["path", { d: "m15 18 2 2 4-4", key: "1szwhi" }],
["path", { d: "M16 12H3", key: "1a2rj7" }],
["path", { d: "M16 6H3", key: "1wxfjs" }]
]);
export { ListCheck as default };
//# sourceMappingURL=list-check.js.map
@@ -0,0 +1,2 @@
import { accepts } from "./accepts.js";
export { accepts };
@@ -0,0 +1,807 @@
import email.feedparser
import email.header
import email.message
import email.parser
import email.policy
import sys
import typing
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from . import requirements, specifiers, utils, version as version_module
T = typing.TypeVar("T")
from typing import Literal, TypedDict
try:
ExceptionGroup # Added in Python 3.11+
except NameError: # pragma: no cover
class ExceptionGroup(Exception): # noqa: N818
"""A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
If :external:exc:`ExceptionGroup` is already defined by Python itself,
that version is used instead.
"""
message: str
exceptions: List[Exception]
def __init__(self, message: str, exceptions: List[Exception]) -> None:
self.message = message
self.exceptions = exceptions
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
else: # pragma: no cover
ExceptionGroup = ExceptionGroup
class InvalidMetadata(ValueError):
"""A metadata field contains invalid data."""
field: str
"""The name of the field that contains invalid data."""
def __init__(self, field: str, message: str) -> None:
self.field = field
super().__init__(message)
# The RawMetadata class attempts to make as few assumptions about the underlying
# serialization formats as possible. The idea is that as long as a serialization
# formats offer some very basic primitives in *some* way then we can support
# serializing to and from that format.
class RawMetadata(TypedDict, total=False):
"""A dictionary of raw core metadata.
Each field in core metadata maps to a key of this dictionary (when data is
provided). The key is lower-case and underscores are used instead of dashes
compared to the equivalent core metadata field. Any core metadata field that
can be specified multiple times or can hold multiple values in a single
field have a key with a plural name. See :class:`Metadata` whose attributes
match the keys of this dictionary.
Core metadata fields that can be specified multiple times are stored as a
list or dict depending on which is appropriate for the field. Any fields
which hold multiple values in a single field are stored as a list.
"""
# Metadata 1.0 - PEP 241
metadata_version: str
name: str
version: str
platforms: List[str]
summary: str
description: str
keywords: List[str]
home_page: str
author: str
author_email: str
license: str
# Metadata 1.1 - PEP 314
supported_platforms: List[str]
download_url: str
classifiers: List[str]
requires: List[str]
provides: List[str]
obsoletes: List[str]
# Metadata 1.2 - PEP 345
maintainer: str
maintainer_email: str
requires_dist: List[str]
provides_dist: List[str]
obsoletes_dist: List[str]
requires_python: str
requires_external: List[str]
project_urls: Dict[str, str]
# Metadata 2.0
# PEP 426 attempted to completely revamp the metadata format
# but got stuck without ever being able to build consensus on
# it and ultimately ended up withdrawn.
#
# However, a number of tools had started emitting METADATA with
# `2.0` Metadata-Version, so for historical reasons, this version
# was skipped.
# Metadata 2.1 - PEP 566
description_content_type: str
provides_extra: List[str]
# Metadata 2.2 - PEP 643
dynamic: List[str]
# Metadata 2.3 - PEP 685
# No new fields were added in PEP 685, just some edge case were
# tightened up to provide better interoperability.
_STRING_FIELDS = {
"author",
"author_email",
"description",
"description_content_type",
"download_url",
"home_page",
"license",
"maintainer",
"maintainer_email",
"metadata_version",
"name",
"requires_python",
"summary",
"version",
}
_LIST_FIELDS = {
"classifiers",
"dynamic",
"obsoletes",
"obsoletes_dist",
"platforms",
"provides",
"provides_dist",
"provides_extra",
"requires",
"requires_dist",
"requires_external",
"supported_platforms",
}
_DICT_FIELDS = {
"project_urls",
}
def _parse_keywords(data: str) -> List[str]:
"""Split a string of comma-separate keyboards into a list of keywords."""
return [k.strip() for k in data.split(",")]
def _parse_project_urls(data: List[str]) -> Dict[str, str]:
"""Parse a list of label/URL string pairings separated by a comma."""
urls = {}
for pair in data:
# Our logic is slightly tricky here as we want to try and do
# *something* reasonable with malformed data.
#
# The main thing that we have to worry about, is data that does
# not have a ',' at all to split the label from the Value. There
# isn't a singular right answer here, and we will fail validation
# later on (if the caller is validating) so it doesn't *really*
# matter, but since the missing value has to be an empty str
# and our return value is dict[str, str], if we let the key
# be the missing value, then they'd have multiple '' values that
# overwrite each other in a accumulating dict.
#
# The other potential issue is that it's possible to have the
# same label multiple times in the metadata, with no solid "right"
# answer with what to do in that case. As such, we'll do the only
# thing we can, which is treat the field as unparsable and add it
# to our list of unparsed fields.
parts = [p.strip() for p in pair.split(",", 1)]
parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items
# TODO: The spec doesn't say anything about if the keys should be
# considered case sensitive or not... logically they should
# be case-preserving and case-insensitive, but doing that
# would open up more cases where we might have duplicate
# entries.
label, url = parts
if label in urls:
# The label already exists in our set of urls, so this field
# is unparsable, and we can just add the whole thing to our
# unparsable data and stop processing it.
raise KeyError("duplicate labels in project urls")
urls[label] = url
return urls
def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str:
"""Get the body of the message."""
# If our source is a str, then our caller has managed encodings for us,
# and we don't need to deal with it.
if isinstance(source, str):
payload: str = msg.get_payload()
return payload
# If our source is a bytes, then we're managing the encoding and we need
# to deal with it.
else:
bpayload: bytes = msg.get_payload(decode=True)
try:
return bpayload.decode("utf8", "strict")
except UnicodeDecodeError:
raise ValueError("payload in an invalid encoding")
# The various parse_FORMAT functions here are intended to be as lenient as
# possible in their parsing, while still returning a correctly typed
# RawMetadata.
#
# To aid in this, we also generally want to do as little touching of the
# data as possible, except where there are possibly some historic holdovers
# that make valid data awkward to work with.
#
# While this is a lower level, intermediate format than our ``Metadata``
# class, some light touch ups can make a massive difference in usability.
# Map METADATA fields to RawMetadata.
_EMAIL_TO_RAW_MAPPING = {
"author": "author",
"author-email": "author_email",
"classifier": "classifiers",
"description": "description",
"description-content-type": "description_content_type",
"download-url": "download_url",
"dynamic": "dynamic",
"home-page": "home_page",
"keywords": "keywords",
"license": "license",
"maintainer": "maintainer",
"maintainer-email": "maintainer_email",
"metadata-version": "metadata_version",
"name": "name",
"obsoletes": "obsoletes",
"obsoletes-dist": "obsoletes_dist",
"platform": "platforms",
"project-url": "project_urls",
"provides": "provides",
"provides-dist": "provides_dist",
"provides-extra": "provides_extra",
"requires": "requires",
"requires-dist": "requires_dist",
"requires-external": "requires_external",
"requires-python": "requires_python",
"summary": "summary",
"supported-platform": "supported_platforms",
"version": "version",
}
_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]:
"""Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
This function returns a two-item tuple of dicts. The first dict is of
recognized fields from the core metadata specification. Fields that can be
parsed and translated into Python's built-in types are converted
appropriately. All other fields are left as-is. Fields that are allowed to
appear multiple times are stored as lists.
The second dict contains all other fields from the metadata. This includes
any unrecognized fields. It also includes any fields which are expected to
be parsed into a built-in type but were not formatted appropriately. Finally,
any fields that are expected to appear only once but are repeated are
included in this dict.
"""
raw: Dict[str, Union[str, List[str], Dict[str, str]]] = {}
unparsed: Dict[str, List[str]] = {}
if isinstance(data, str):
parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)
else:
parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
# We have to wrap parsed.keys() in a set, because in the case of multiple
# values for a key (a list), the key will appear multiple times in the
# list of keys, but we're avoiding that by using get_all().
for name in frozenset(parsed.keys()):
# Header names in RFC are case insensitive, so we'll normalize to all
# lower case to make comparisons easier.
name = name.lower()
# We use get_all() here, even for fields that aren't multiple use,
# because otherwise someone could have e.g. two Name fields, and we
# would just silently ignore it rather than doing something about it.
headers = parsed.get_all(name) or []
# The way the email module works when parsing bytes is that it
# unconditionally decodes the bytes as ascii using the surrogateescape
# handler. When you pull that data back out (such as with get_all() ),
# it looks to see if the str has any surrogate escapes, and if it does
# it wraps it in a Header object instead of returning the string.
#
# As such, we'll look for those Header objects, and fix up the encoding.
value = []
# Flag if we have run into any issues processing the headers, thus
# signalling that the data belongs in 'unparsed'.
valid_encoding = True
for h in headers:
# It's unclear if this can return more types than just a Header or
# a str, so we'll just assert here to make sure.
assert isinstance(h, (email.header.Header, str))
# If it's a header object, we need to do our little dance to get
# the real data out of it. In cases where there is invalid data
# we're going to end up with mojibake, but there's no obvious, good
# way around that without reimplementing parts of the Header object
# ourselves.
#
# That should be fine since, if mojibacked happens, this key is
# going into the unparsed dict anyways.
if isinstance(h, email.header.Header):
# The Header object stores it's data as chunks, and each chunk
# can be independently encoded, so we'll need to check each
# of them.
chunks: List[Tuple[bytes, Optional[str]]] = []
for bin, encoding in email.header.decode_header(h):
try:
bin.decode("utf8", "strict")
except UnicodeDecodeError:
# Enable mojibake.
encoding = "latin1"
valid_encoding = False
else:
encoding = "utf8"
chunks.append((bin, encoding))
# Turn our chunks back into a Header object, then let that
# Header object do the right thing to turn them into a
# string for us.
value.append(str(email.header.make_header(chunks)))
# This is already a string, so just add it.
else:
value.append(h)
# We've processed all of our values to get them into a list of str,
# but we may have mojibake data, in which case this is an unparsed
# field.
if not valid_encoding:
unparsed[name] = value
continue
raw_name = _EMAIL_TO_RAW_MAPPING.get(name)
if raw_name is None:
# This is a bit of a weird situation, we've encountered a key that
# we don't know what it means, so we don't know whether it's meant
# to be a list or not.
#
# Since we can't really tell one way or another, we'll just leave it
# as a list, even though it may be a single item list, because that's
# what makes the most sense for email headers.
unparsed[name] = value
continue
# If this is one of our string fields, then we'll check to see if our
# value is a list of a single item. If it is then we'll assume that
# it was emitted as a single string, and unwrap the str from inside
# the list.
#
# If it's any other kind of data, then we haven't the faintest clue
# what we should parse it as, and we have to just add it to our list
# of unparsed stuff.
if raw_name in _STRING_FIELDS and len(value) == 1:
raw[raw_name] = value[0]
# If this is one of our list of string fields, then we can just assign
# the value, since email *only* has strings, and our get_all() call
# above ensures that this is a list.
elif raw_name in _LIST_FIELDS:
raw[raw_name] = value
# Special Case: Keywords
# The keywords field is implemented in the metadata spec as a str,
# but it conceptually is a list of strings, and is serialized using
# ", ".join(keywords), so we'll do some light data massaging to turn
# this into what it logically is.
elif raw_name == "keywords" and len(value) == 1:
raw[raw_name] = _parse_keywords(value[0])
# Special Case: Project-URL
# The project urls is implemented in the metadata spec as a list of
# specially-formatted strings that represent a key and a value, which
# is fundamentally a mapping, however the email format doesn't support
# mappings in a sane way, so it was crammed into a list of strings
# instead.
#
# We will do a little light data massaging to turn this into a map as
# it logically should be.
elif raw_name == "project_urls":
try:
raw[raw_name] = _parse_project_urls(value)
except KeyError:
unparsed[name] = value
# Nothing that we've done has managed to parse this, so it'll just
# throw it in our unparsable data and move on.
else:
unparsed[name] = value
# We need to support getting the Description from the message payload in
# addition to getting it from the the headers. This does mean, though, there
# is the possibility of it being set both ways, in which case we put both
# in 'unparsed' since we don't know which is right.
try:
payload = _get_payload(parsed, data)
except ValueError:
unparsed.setdefault("description", []).append(
parsed.get_payload(decode=isinstance(data, bytes))
)
else:
if payload:
# Check to see if we've already got a description, if so then both
# it, and this body move to unparsable.
if "description" in raw:
description_header = cast(str, raw.pop("description"))
unparsed.setdefault("description", []).extend(
[description_header, payload]
)
elif "description" in unparsed:
unparsed["description"].append(payload)
else:
raw["description"] = payload
# We need to cast our `raw` to a metadata, because a TypedDict only support
# literal key names, but we're computing our key names on purpose, but the
# way this function is implemented, our `TypedDict` can only have valid key
# names.
return cast(RawMetadata, raw), unparsed
_NOT_FOUND = object()
# Keep the two values in sync.
_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"]
_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"]
_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
class _Validator(Generic[T]):
"""Validate a metadata field.
All _process_*() methods correspond to a core metadata field. The method is
called with the field's raw value. If the raw value is valid it is returned
in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
as appropriate).
"""
name: str
raw_name: str
added: _MetadataVersion
def __init__(
self,
*,
added: _MetadataVersion = "1.0",
) -> None:
self.added = added
def __set_name__(self, _owner: "Metadata", name: str) -> None:
self.name = name
self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
def __get__(self, instance: "Metadata", _owner: Type["Metadata"]) -> T:
# With Python 3.8+, the caching can be replaced with functools.cached_property().
# No need to check the cache as attribute lookup will resolve into the
# instance's __dict__ before __get__ is called.
cache = instance.__dict__
value = instance._raw.get(self.name)
# To make the _process_* methods easier, we'll check if the value is None
# and if this field is NOT a required attribute, and if both of those
# things are true, we'll skip the the converter. This will mean that the
# converters never have to deal with the None union.
if self.name in _REQUIRED_ATTRS or value is not None:
try:
converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
except AttributeError:
pass
else:
value = converter(value)
cache[self.name] = value
try:
del instance._raw[self.name] # type: ignore[misc]
except KeyError:
pass
return cast(T, value)
def _invalid_metadata(
self, msg: str, cause: Optional[Exception] = None
) -> InvalidMetadata:
exc = InvalidMetadata(
self.raw_name, msg.format_map({"field": repr(self.raw_name)})
)
exc.__cause__ = cause
return exc
def _process_metadata_version(self, value: str) -> _MetadataVersion:
# Implicitly makes Metadata-Version required.
if value not in _VALID_METADATA_VERSIONS:
raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
return cast(_MetadataVersion, value)
def _process_name(self, value: str) -> str:
if not value:
raise self._invalid_metadata("{field} is a required field")
# Validate the name as a side-effect.
try:
utils.canonicalize_name(value, validate=True)
except utils.InvalidName as exc:
raise self._invalid_metadata(
f"{value!r} is invalid for {{field}}", cause=exc
)
else:
return value
def _process_version(self, value: str) -> version_module.Version:
if not value:
raise self._invalid_metadata("{field} is a required field")
try:
return version_module.parse(value)
except version_module.InvalidVersion as exc:
raise self._invalid_metadata(
f"{value!r} is invalid for {{field}}", cause=exc
)
def _process_summary(self, value: str) -> str:
"""Check the field contains no newlines."""
if "\n" in value:
raise self._invalid_metadata("{field} must be a single line")
return value
def _process_description_content_type(self, value: str) -> str:
content_types = {"text/plain", "text/x-rst", "text/markdown"}
message = email.message.EmailMessage()
message["content-type"] = value
content_type, parameters = (
# Defaults to `text/plain` if parsing failed.
message.get_content_type().lower(),
message["content-type"].params,
)
# Check if content-type is valid or defaulted to `text/plain` and thus was
# not parseable.
if content_type not in content_types or content_type not in value.lower():
raise self._invalid_metadata(
f"{{field}} must be one of {list(content_types)}, not {value!r}"
)
if (charset := parameters.get("charset", "UTF-8")) != "UTF-8":
raise self._invalid_metadata(
f"{{field}} can only specify the UTF-8 charset, not {list(charset)}"
)
markdown_variants = {"GFM", "CommonMark"}
variant = parameters.get("variant", "GFM") # Use an acceptable default.
if content_type == "text/markdown" and variant not in markdown_variants:
raise self._invalid_metadata(
f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
f"not {variant!r}",
)
return value
def _process_dynamic(self, value: List[str]) -> List[str]:
for dynamic_field in map(str.lower, value):
if dynamic_field in {"name", "version", "metadata-version"}:
raise self._invalid_metadata(
f"{value!r} is not allowed as a dynamic field"
)
elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
raise self._invalid_metadata(f"{value!r} is not a valid dynamic field")
return list(map(str.lower, value))
def _process_provides_extra(
self,
value: List[str],
) -> List[utils.NormalizedName]:
normalized_names = []
try:
for name in value:
normalized_names.append(utils.canonicalize_name(name, validate=True))
except utils.InvalidName as exc:
raise self._invalid_metadata(
f"{name!r} is invalid for {{field}}", cause=exc
)
else:
return normalized_names
def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
try:
return specifiers.SpecifierSet(value)
except specifiers.InvalidSpecifier as exc:
raise self._invalid_metadata(
f"{value!r} is invalid for {{field}}", cause=exc
)
def _process_requires_dist(
self,
value: List[str],
) -> List[requirements.Requirement]:
reqs = []
try:
for req in value:
reqs.append(requirements.Requirement(req))
except requirements.InvalidRequirement as exc:
raise self._invalid_metadata(f"{req!r} is invalid for {{field}}", cause=exc)
else:
return reqs
class Metadata:
"""Representation of distribution metadata.
Compared to :class:`RawMetadata`, this class provides objects representing
metadata fields instead of only using built-in types. Any invalid metadata
will cause :exc:`InvalidMetadata` to be raised (with a
:py:attr:`~BaseException.__cause__` attribute as appropriate).
"""
_raw: RawMetadata
@classmethod
def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> "Metadata":
"""Create an instance from :class:`RawMetadata`.
If *validate* is true, all metadata will be validated. All exceptions
related to validation will be gathered and raised as an :class:`ExceptionGroup`.
"""
ins = cls()
ins._raw = data.copy() # Mutations occur due to caching enriched values.
if validate:
exceptions: List[Exception] = []
try:
metadata_version = ins.metadata_version
metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
except InvalidMetadata as metadata_version_exc:
exceptions.append(metadata_version_exc)
metadata_version = None
# Make sure to check for the fields that are present, the required
# fields (so their absence can be reported).
fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
# Remove fields that have already been checked.
fields_to_check -= {"metadata_version"}
for key in fields_to_check:
try:
if metadata_version:
# Can't use getattr() as that triggers descriptor protocol which
# will fail due to no value for the instance argument.
try:
field_metadata_version = cls.__dict__[key].added
except KeyError:
exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
exceptions.append(exc)
continue
field_age = _VALID_METADATA_VERSIONS.index(
field_metadata_version
)
if field_age > metadata_age:
field = _RAW_TO_EMAIL_MAPPING[key]
exc = InvalidMetadata(
field,
"{field} introduced in metadata version "
"{field_metadata_version}, not {metadata_version}",
)
exceptions.append(exc)
continue
getattr(ins, key)
except InvalidMetadata as exc:
exceptions.append(exc)
if exceptions:
raise ExceptionGroup("invalid metadata", exceptions)
return ins
@classmethod
def from_email(
cls, data: Union[bytes, str], *, validate: bool = True
) -> "Metadata":
"""Parse metadata from email headers.
If *validate* is true, the metadata will be validated. All exceptions
related to validation will be gathered and raised as an :class:`ExceptionGroup`.
"""
raw, unparsed = parse_email(data)
if validate:
exceptions: list[Exception] = []
for unparsed_key in unparsed:
if unparsed_key in _EMAIL_TO_RAW_MAPPING:
message = f"{unparsed_key!r} has invalid data"
else:
message = f"unrecognized field: {unparsed_key!r}"
exceptions.append(InvalidMetadata(unparsed_key, message))
if exceptions:
raise ExceptionGroup("unparsed", exceptions)
try:
return cls.from_raw(raw, validate=validate)
except ExceptionGroup as exc_group:
raise ExceptionGroup(
"invalid or unparsed metadata", exc_group.exceptions
) from None
metadata_version: _Validator[_MetadataVersion] = _Validator()
""":external:ref:`core-metadata-metadata-version`
(required; validated to be a valid metadata version)"""
name: _Validator[str] = _Validator()
""":external:ref:`core-metadata-name`
(required; validated using :func:`~packaging.utils.canonicalize_name` and its
*validate* parameter)"""
version: _Validator[version_module.Version] = _Validator()
""":external:ref:`core-metadata-version` (required)"""
dynamic: _Validator[Optional[List[str]]] = _Validator(
added="2.2",
)
""":external:ref:`core-metadata-dynamic`
(validated against core metadata field names and lowercased)"""
platforms: _Validator[Optional[List[str]]] = _Validator()
""":external:ref:`core-metadata-platform`"""
supported_platforms: _Validator[Optional[List[str]]] = _Validator(added="1.1")
""":external:ref:`core-metadata-supported-platform`"""
summary: _Validator[Optional[str]] = _Validator()
""":external:ref:`core-metadata-summary` (validated to contain no newlines)"""
description: _Validator[Optional[str]] = _Validator() # TODO 2.1: can be in body
""":external:ref:`core-metadata-description`"""
description_content_type: _Validator[Optional[str]] = _Validator(added="2.1")
""":external:ref:`core-metadata-description-content-type` (validated)"""
keywords: _Validator[Optional[List[str]]] = _Validator()
""":external:ref:`core-metadata-keywords`"""
home_page: _Validator[Optional[str]] = _Validator()
""":external:ref:`core-metadata-home-page`"""
download_url: _Validator[Optional[str]] = _Validator(added="1.1")
""":external:ref:`core-metadata-download-url`"""
author: _Validator[Optional[str]] = _Validator()
""":external:ref:`core-metadata-author`"""
author_email: _Validator[Optional[str]] = _Validator()
""":external:ref:`core-metadata-author-email`"""
maintainer: _Validator[Optional[str]] = _Validator(added="1.2")
""":external:ref:`core-metadata-maintainer`"""
maintainer_email: _Validator[Optional[str]] = _Validator(added="1.2")
""":external:ref:`core-metadata-maintainer-email`"""
license: _Validator[Optional[str]] = _Validator()
""":external:ref:`core-metadata-license`"""
classifiers: _Validator[Optional[List[str]]] = _Validator(added="1.1")
""":external:ref:`core-metadata-classifier`"""
requires_dist: _Validator[Optional[List[requirements.Requirement]]] = _Validator(
added="1.2"
)
""":external:ref:`core-metadata-requires-dist`"""
requires_python: _Validator[Optional[specifiers.SpecifierSet]] = _Validator(
added="1.2"
)
""":external:ref:`core-metadata-requires-python`"""
# Because `Requires-External` allows for non-PEP 440 version specifiers, we
# don't do any processing on the values.
requires_external: _Validator[Optional[List[str]]] = _Validator(added="1.2")
""":external:ref:`core-metadata-requires-external`"""
project_urls: _Validator[Optional[Dict[str, str]]] = _Validator(added="1.2")
""":external:ref:`core-metadata-project-url`"""
# PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
# regardless of metadata version.
provides_extra: _Validator[Optional[List[utils.NormalizedName]]] = _Validator(
added="2.1",
)
""":external:ref:`core-metadata-provides-extra`"""
provides_dist: _Validator[Optional[List[str]]] = _Validator(added="1.2")
""":external:ref:`core-metadata-provides-dist`"""
obsoletes_dist: _Validator[Optional[List[str]]] = _Validator(added="1.2")
""":external:ref:`core-metadata-obsoletes-dist`"""
requires: _Validator[Optional[List[str]]] = _Validator(added="1.1")
"""``Requires`` (deprecated)"""
provides: _Validator[Optional[List[str]]] = _Validator(added="1.1")
"""``Provides`` (deprecated)"""
obsoletes: _Validator[Optional[List[str]]] = _Validator(added="1.1")
"""``Obsoletes`` (deprecated)"""
@@ -0,0 +1 @@
{"version":3,"names":["_classPrivateMethodSet","TypeError"],"sources":["../../src/helpers/classPrivateMethodSet.js"],"sourcesContent":["/* @minVersion 7.1.6 */\n/* @onlyBabel7 */\n\n// use readOnlyError instead of attemptSet\n\nexport default function _classPrivateMethodSet() {\n throw new TypeError(\"attempted to reassign private method\");\n}\n"],"mappings":";;;;;;AAKe,SAASA,sBAAsBA,CAAA,EAAG;EAC/C,MAAM,IAAIC,SAAS,CAAC,sCAAsC,CAAC;AAC7D","ignoreList":[]}
@@ -0,0 +1,85 @@
'use strict';
module.exports = function generate__limitLength(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
if (!($isData || typeof $schema == 'number')) {
throw new Error($keyword + ' must be number');
}
var $op = $keyword == 'maxLength' ? '>' : '<';
out += 'if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
if (it.opts.unicode === false) {
out += ' ' + ($data) + '.length ';
} else {
out += ' ucs2length(' + ($data) + ') ';
}
out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT be ';
if ($keyword == 'maxLength') {
out += 'longer';
} else {
out += 'shorter';
}
out += ' than ';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + ($schema);
}
out += ' characters\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
@@ -0,0 +1,2 @@
import { PatternRouter } from "./router.js";
export { PatternRouter };
@@ -0,0 +1,35 @@
/**
* @fileoverview Defining the hashing function in one place.
* @author Michael Ficarra
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const murmur = require("imurmurhash");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
/**
* hash the given string
* @param {string} str the string to hash
* @returns {string} the hash
*/
function hash(str) {
return murmur(str).result().toString(36);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = hash;
@@ -0,0 +1,47 @@
import { transform } from '../utils/transform.mjs';
import { transformValue } from './transform-value.mjs';
/**
* Create a `MotionValue` that maps the output of another `MotionValue` by
* mapping it from one range of values into another.
*
* @remarks
*
* Given an input range of `[-200, -100, 100, 200]` and an output range of
* `[0, 1, 1, 0]`, the returned `MotionValue` will:
*
* - When provided a value between `-200` and `-100`, will return a value between `0` and `1`.
* - When provided a value between `-100` and `100`, will return `1`.
* - When provided a value between `100` and `200`, will return a value between `1` and `0`
*
* The input range must be a linear series of numbers. The output range
* can be any value type supported by Motion: numbers, colors, shadows, etc.
*
* Every value in the output range must be of the same type and in the same format.
*
* ```jsx
* const x = motionValue(0)
* const xRange = [-200, -100, 100, 200]
* const opacityRange = [0, 1, 1, 0]
* const opacity = mapValue(x, xRange, opacityRange)
* ```
*
* @param inputValue - `MotionValue`
* @param inputRange - A linear series of numbers (either all increasing or decreasing)
* @param outputRange - A series of numbers, colors or strings. Must be the same length as `inputRange`.
* @param options -
*
* - clamp: boolean. Clamp values to within the given range. Defaults to `true`
* - ease: EasingFunction[]. Easing functions to use on the interpolations between each value in the input and output ranges. If provided as an array, the array must be one item shorter than the input and output ranges, as the easings apply to the transition between each.
*
* @returns `MotionValue`
*
* @public
*/
function mapValue(inputValue, inputRange, outputRange, options) {
const map = transform(inputRange, outputRange, options);
return transformValue(() => map(inputValue.get()));
}
export { mapValue };
//# sourceMappingURL=map-value.mjs.map
@@ -0,0 +1 @@
{"version":3,"file":"list-ordered.js","sources":["../../../src/icons/list-ordered.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ListOrdered\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTAgMTJoMTEiIC8+CiAgPHBhdGggZD0iTTEwIDE4aDExIiAvPgogIDxwYXRoIGQ9Ik0xMCA2aDExIiAvPgogIDxwYXRoIGQ9Ik00IDEwaDIiIC8+CiAgPHBhdGggZD0iTTQgNmgxdjQiIC8+CiAgPHBhdGggZD0iTTYgMThINGMwLTEgMi0yIDItM3MtMS0xLjUtMi0xIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/list-ordered\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 ListOrdered = createLucideIcon('ListOrdered', [\n ['path', { d: 'M10 12h11', key: '6m4ad9' }],\n ['path', { d: 'M10 18h11', key: '11hvi2' }],\n ['path', { d: 'M10 6h11', key: 'c7qv1k' }],\n ['path', { d: 'M4 10h2', key: '16xx2s' }],\n ['path', { d: 'M4 6h1v4', key: 'cnovpq' }],\n ['path', { d: 'M6 18H4c0-1 2-2 2-3s-1-1.5-2-1', key: 'm9a95d' }],\n]);\n\nexport default ListOrdered;\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,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,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,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,CAAkC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,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;AACjE,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/types/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,249 @@
/**
* @fileoverview Rule to flag numbers that will lose significant figure precision at runtime
* @author Jacob Moore
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/** Class representing a number in scientific notation. */
class ScientificNotation {
/** @type {string} The digits of the coefficient. A decimal point is implied after the first digit. */
coefficient;
/** @type {number} The order of magnitude. */
magnitude;
constructor(coefficient, magnitude) {
this.coefficient = coefficient;
this.magnitude = magnitude;
}
/* c8 ignore start -- debug only */
toString() {
return `${this.coefficient[0]}${this.coefficient.length > 1 ? `.${this.coefficient.slice(1)}` : ""}e${this.magnitude}`;
}
/* c8 ignore stop */
}
/**
* Returns whether the node is number literal
* @param {Node} node the node literal being evaluated
* @returns {boolean} true if the node is a number literal
*/
function isNumber(node) {
return typeof node.value === "number";
}
/**
* Gets the source code of the given number literal. Removes `_` numeric separators from the result.
* @param {Node} node the number `Literal` node
* @returns {string} raw source code of the literal, without numeric separators
*/
function getRaw(node) {
return node.raw.replace(/_/gu, "");
}
/**
* Checks whether the number is base ten
* @param {ASTNode} node the node being evaluated
* @returns {boolean} true if the node is in base ten
*/
function isBaseTen(node) {
const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"];
return (
prefixes.every(prefix => !node.raw.startsWith(prefix)) &&
!/^0[0-7]+$/u.test(node.raw)
);
}
/**
* Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type
* @param {Node} node the node being evaluated
* @returns {boolean} true if they do not match
*/
function notBaseTenLosesPrecision(node) {
const rawString = getRaw(node).toUpperCase();
let base;
if (rawString.startsWith("0B")) {
base = 2;
} else if (rawString.startsWith("0X")) {
base = 16;
} else {
base = 8;
}
return !rawString.endsWith(node.value.toString(base).toUpperCase());
}
/**
* Returns the number stripped of leading zeros
* @param {string} numberAsString the string representation of the number
* @returns {string} the stripped string
*/
function removeLeadingZeros(numberAsString) {
for (let i = 0; i < numberAsString.length; i++) {
if (numberAsString[i] !== "0") {
return numberAsString.slice(i);
}
}
return numberAsString;
}
/**
* Returns the number stripped of trailing zeros
* @param {string} numberAsString the string representation of the number
* @returns {string} the stripped string
*/
function removeTrailingZeros(numberAsString) {
for (let i = numberAsString.length - 1; i >= 0; i--) {
if (numberAsString[i] !== "0") {
return numberAsString.slice(0, i + 1);
}
}
return numberAsString;
}
/**
* Converts an integer to an object containing the integer's coefficient and order of magnitude
* @param {string} stringInteger the string representation of the integer being converted
* @returns {ScientificNotation} the object containing the integer's coefficient and order of magnitude
*/
function normalizeInteger(stringInteger) {
const trimmedInteger = removeLeadingZeros(stringInteger);
const significantDigits = removeTrailingZeros(trimmedInteger);
return new ScientificNotation(significantDigits, trimmedInteger.length - 1);
}
/**
* Converts a float to an object containing the float's coefficient and order of magnitude
* @param {string} stringFloat the string representation of the float being converted
* @returns {ScientificNotation} the object containing the float's coefficient and order of magnitude
*/
function normalizeFloat(stringFloat) {
const trimmedFloat = removeLeadingZeros(stringFloat);
const indexOfDecimalPoint = trimmedFloat.indexOf(".");
switch (indexOfDecimalPoint) {
case 0: {
const significantDigits = removeLeadingZeros(trimmedFloat.slice(1));
return new ScientificNotation(
significantDigits,
significantDigits.length - trimmedFloat.length,
);
}
case -1:
return new ScientificNotation(
trimmedFloat,
trimmedFloat.length - 1,
);
default:
return new ScientificNotation(
trimmedFloat.replace(".", ""),
indexOfDecimalPoint - 1,
);
}
}
/**
* Converts a base ten number to proper scientific notation
* @param {string} stringNumber the string representation of the base ten number to be converted
* @param {boolean} parseAsFloat if true, the coefficient will be always parsed as a float, regardless of whether a decimal point is present
* @returns {ScientificNotation} the object containing the number's coefficient and order of magnitude
*/
function convertNumberToScientificNotation(stringNumber, parseAsFloat) {
const splitNumber = stringNumber.split("e");
const originalCoefficient = splitNumber[0];
const normalizedNumber =
parseAsFloat || stringNumber.includes(".")
? normalizeFloat(originalCoefficient)
: normalizeInteger(originalCoefficient);
if (splitNumber.length > 1) {
normalizedNumber.magnitude += parseInt(splitNumber[1], 10);
}
return normalizedNumber;
}
/**
* Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type
* @param {Node} node the node being evaluated
* @returns {boolean} true if they do not match
*/
function baseTenLosesPrecision(node) {
const rawNumber = getRaw(node).toLowerCase();
const normalizedRawNumber = convertNumberToScientificNotation(
rawNumber,
false,
);
const requestedPrecision = normalizedRawNumber.coefficient.length;
if (requestedPrecision > 100) {
return true;
}
const storedNumber = node.value.toPrecision(requestedPrecision);
const normalizedStoredNumber = convertNumberToScientificNotation(
storedNumber,
true,
);
return (
normalizedRawNumber.magnitude !== normalizedStoredNumber.magnitude ||
normalizedRawNumber.coefficient !== normalizedStoredNumber.coefficient
);
}
/**
* Checks that the user-intended number equals the actual number after is has been converted to the Number type
* @param {Node} node the node being evaluated
* @returns {boolean} true if they do not match
*/
function losesPrecision(node) {
return isBaseTen(node)
? baseTenLosesPrecision(node)
: notBaseTenLosesPrecision(node);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "problem",
dialects: ["typescript", "javascript"],
language: "javascript",
docs: {
description: "Disallow literal numbers that lose precision",
recommended: true,
url: "https://eslint.org/docs/latest/rules/no-loss-of-precision",
},
schema: [],
messages: {
noLossOfPrecision:
"This number literal will lose precision at runtime.",
},
},
create(context) {
return {
Literal(node) {
if (node.value && isNumber(node) && losesPrecision(node)) {
context.report({
messageId: "noLossOfPrecision",
node,
});
}
},
};
},
};
@@ -0,0 +1,6 @@
"use strict";
const addSeconds = require("./addSeconds.js");
function subSeconds(date, seconds) {
return addSeconds(date, -seconds);
}
module.exports = subSeconds;
@@ -0,0 +1,44 @@
import * as core from "../core/index.js";
import { type ZodError } from "./errors.js";
export type ZodSafeParseResult<T> = ZodSafeParseSuccess<T> | ZodSafeParseError<T>;
export type ZodSafeParseSuccess<T> = {
success: true;
data: T;
error?: never;
};
export type ZodSafeParseError<T> = {
success: false;
data?: never;
error: ZodError<T>;
};
export declare const parse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const parseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeParse: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeParseAsync: <T extends core.$ZodType>(schema: T, value: unknown, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
export { validate, validateAsync } from "../core/index.js";
export declare const encode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.input<T>;
export declare const decode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => core.output<T>;
export declare const encodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.input<T>>;
export declare const decodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>, _params?: {
callee?: core.util.AnyFunc;
Err?: core.$ZodErrorClass;
}) => Promise<core.output<T>>;
export declare const safeEncode: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.input<T>>;
export declare const safeDecode: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => ZodSafeParseResult<core.output<T>>;
export declare const safeEncodeAsync: <T extends core.$ZodType>(schema: T, value: core.output<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.input<T>>>;
export declare const safeDecodeAsync: <T extends core.$ZodType>(schema: T, value: core.input<T>, _ctx?: core.ParseContext<core.$ZodIssue>) => Promise<ZodSafeParseResult<core.output<T>>>;
@@ -0,0 +1,18 @@
import { Parser } from "../index.js";
export declare const parsers: {
__babel_estree: Parser;
__js_expression: Parser;
__ts_expression: Parser;
__vue_event_binding: Parser;
__vue_expression: Parser;
__vue_ts_event_binding: Parser;
__vue_ts_expression: Parser;
babel: Parser;
"babel-flow": Parser;
"babel-ts": Parser;
json: Parser;
"json-stringify": Parser;
json5: Parser;
jsonc: Parser;
};
@@ -0,0 +1,21 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v1.0.1](https://github.com/ljharb/get-proto/compare/v1.0.0...v1.0.1) - 2025-01-02
### Commits
- [Fix] for the `Object.getPrototypeOf` window, throw for non-objects [`7fe6508`](https://github.com/ljharb/get-proto/commit/7fe6508b71419ebe1976bedb86001d1feaeaa49a)
## v1.0.0 - 2025-01-01
### Commits
- Initial implementation, tests, readme, types [`5c70775`](https://github.com/ljharb/get-proto/commit/5c707751e81c3deeb2cf980d185fc7fd43611415)
- Initial commit [`7c65c2a`](https://github.com/ljharb/get-proto/commit/7c65c2ad4e33d5dae2f219ebe1a046ae2256972c)
- npm init [`0b8cf82`](https://github.com/ljharb/get-proto/commit/0b8cf824c9634e4a34ef7dd2a2cdc5be6ac79518)
- Only apps should have lockfiles [`a6d1bff`](https://github.com/ljharb/get-proto/commit/a6d1bffc364f5828377cea7194558b2dbef7aea2)
@@ -0,0 +1 @@
{"version":3,"file":"play-circle.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1 @@
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA6B,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAgB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAwB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAqB,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAkC,MAAM,sBAAsB,CAAC;AAUrF,MAAM,MAAM,iBAAiB,GAAG;IAC5B;;OAEG;IACH,QAAQ,EAAE,mBAAmB,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE,GAAG,CAAC;IAEf;;;;OAIG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,GAAG,CAAC;IAGxB,oBAAoB,CAAC,EAAE,IAAI,CAAC,2BAA2B,EAAE,UAAU,CAAC,CAAC;IACrE,yBAAyB,CAAC,EAAE,IAAI,CAAC,gCAAgC,EAAE,cAAc,CAAC,CAAC;IACnF,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,UAAU,CAAC,CAAC;IAC/D,YAAY,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;CACxD,CAAC;AAeF,eAAO,MAAM,mBAAmB,YAAa;IACzC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,GAAG,CAAC;IACf,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC9B,KAAG,aAgCH,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,CAyCxE;AAED,MAAM,MAAM,mBAAmB,GAAG;IAC9B;;;OAGG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,CAAC;IAEvB;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAuBlF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oCAAoC,CAAC,SAAS,EAAE,GAAG,GAAG,MAAM,CAI3E"}
@@ -0,0 +1,174 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.suppressOthers = exports.supportsInert = exports.inertOthers = exports.hideOthers = void 0;
var getDefaultParent = function (originalTarget) {
if (typeof document === 'undefined') {
return null;
}
var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;
return sampleTarget.ownerDocument.body;
};
var counterMap = new WeakMap();
var uncontrolledNodes = new WeakMap();
var markerMap = {};
var lockCount = 0;
var unwrapHost = function (node) {
return node && (node.host || unwrapHost(node.parentNode));
};
var correctTargets = function (parent, targets) {
return targets
.map(function (target) {
if (parent.contains(target)) {
return target;
}
var correctedTarget = unwrapHost(target);
if (correctedTarget && parent.contains(correctedTarget)) {
return correctedTarget;
}
console.error('aria-hidden', target, 'in not contained inside', parent, '. Doing nothing');
return null;
})
.filter(function (x) { return Boolean(x); });
};
/**
* Marks everything except given node(or nodes) as aria-hidden
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @param {String} [controlAttribute] - html Attribute to control
* @return {Undo} undo command
*/
var applyAttributeToOthers = function (originalTarget, parentNode, markerName, controlAttribute) {
var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
if (!markerMap[markerName]) {
markerMap[markerName] = new WeakMap();
}
var markerCounter = markerMap[markerName];
var hiddenNodes = [];
var elementsToKeep = new Set();
var elementsToStop = new Set(targets);
var keep = function (el) {
if (!el || elementsToKeep.has(el)) {
return;
}
elementsToKeep.add(el);
keep(el.parentNode);
};
targets.forEach(keep);
var deep = function (parent) {
if (!parent || elementsToStop.has(parent)) {
return;
}
Array.prototype.forEach.call(parent.children, function (node) {
if (elementsToKeep.has(node)) {
deep(node);
}
else {
try {
var attr = node.getAttribute(controlAttribute);
var alreadyHidden = attr !== null && attr !== 'false';
var counterValue = (counterMap.get(node) || 0) + 1;
var markerValue = (markerCounter.get(node) || 0) + 1;
counterMap.set(node, counterValue);
markerCounter.set(node, markerValue);
hiddenNodes.push(node);
if (counterValue === 1 && alreadyHidden) {
uncontrolledNodes.set(node, true);
}
if (markerValue === 1) {
node.setAttribute(markerName, 'true');
}
if (!alreadyHidden) {
node.setAttribute(controlAttribute, 'true');
}
}
catch (e) {
console.error('aria-hidden: cannot operate on ', node, e);
}
}
});
};
deep(parentNode);
elementsToKeep.clear();
lockCount++;
return function () {
hiddenNodes.forEach(function (node) {
var counterValue = counterMap.get(node) - 1;
var markerValue = markerCounter.get(node) - 1;
counterMap.set(node, counterValue);
markerCounter.set(node, markerValue);
if (!counterValue) {
if (!uncontrolledNodes.has(node)) {
node.removeAttribute(controlAttribute);
}
uncontrolledNodes.delete(node);
}
if (!markerValue) {
node.removeAttribute(markerName);
}
});
lockCount--;
if (!lockCount) {
// clear
counterMap = new WeakMap();
counterMap = new WeakMap();
uncontrolledNodes = new WeakMap();
markerMap = {};
}
};
};
/**
* Marks everything except given node(or nodes) as aria-hidden
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @return {Undo} undo command
*/
var hideOthers = function (originalTarget, parentNode, markerName) {
if (markerName === void 0) { markerName = 'data-aria-hidden'; }
var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
var activeParentNode = parentNode || getDefaultParent(originalTarget);
if (!activeParentNode) {
return function () { return null; };
}
// we should not hide aria-live elements - https://github.com/theKashey/aria-hidden/issues/10
// and script elements, as they have no impact on accessibility.
targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll('[aria-live], script')));
return applyAttributeToOthers(targets, activeParentNode, markerName, 'aria-hidden');
};
exports.hideOthers = hideOthers;
/**
* Marks everything except given node(or nodes) as inert
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @return {Undo} undo command
*/
var inertOthers = function (originalTarget, parentNode, markerName) {
if (markerName === void 0) { markerName = 'data-inert-ed'; }
var activeParentNode = parentNode || getDefaultParent(originalTarget);
if (!activeParentNode) {
return function () { return null; };
}
return applyAttributeToOthers(originalTarget, activeParentNode, markerName, 'inert');
};
exports.inertOthers = inertOthers;
/**
* @returns if current browser supports inert
*/
var supportsInert = function () {
return typeof HTMLElement !== 'undefined' && HTMLElement.prototype.hasOwnProperty('inert');
};
exports.supportsInert = supportsInert;
/**
* Automatic function to "suppress" DOM elements - _hide_ or _inert_ in the best possible way
* @param {Element | Element[]} originalTarget - elements to keep on the page
* @param [parentNode] - top element, defaults to document.body
* @param {String} [markerName] - a special attribute to mark every node
* @return {Undo} undo command
*/
var suppressOthers = function (originalTarget, parentNode, markerName) {
if (markerName === void 0) { markerName = 'data-suppressed'; }
return ((0, exports.supportsInert)() ? exports.inertOthers : exports.hideOthers)(originalTarget, parentNode, markerName);
};
exports.suppressOthers = suppressOthers;
@@ -0,0 +1,103 @@
2.0.0 / 2018-10-26
==================
* Drop support for Node.js 0.6
* Replace internal `eval` usage with `Function` constructor
* Use instance methods on `process` to check for listeners
1.1.2 / 2018-01-11
==================
* perf: remove argument reassignment
* Support Node.js 0.6 to 9.x
1.1.1 / 2017-07-27
==================
* Remove unnecessary `Buffer` loading
* Support Node.js 0.6 to 8.x
1.1.0 / 2015-09-14
==================
* Enable strict mode in more places
* Support io.js 3.x
* Support io.js 2.x
* Support web browser loading
- Requires bundler like Browserify or webpack
1.0.1 / 2015-04-07
==================
* Fix `TypeError`s when under `'use strict'` code
* Fix useless type name on auto-generated messages
* Support io.js 1.x
* Support Node.js 0.12
1.0.0 / 2014-09-17
==================
* No changes
0.4.5 / 2014-09-09
==================
* Improve call speed to functions using the function wrapper
* Support Node.js 0.6
0.4.4 / 2014-07-27
==================
* Work-around v8 generating empty stack traces
0.4.3 / 2014-07-26
==================
* Fix exception when global `Error.stackTraceLimit` is too low
0.4.2 / 2014-07-19
==================
* Correct call site for wrapped functions and properties
0.4.1 / 2014-07-19
==================
* Improve automatic message generation for function properties
0.4.0 / 2014-07-19
==================
* Add `TRACE_DEPRECATION` environment variable
* Remove non-standard grey color from color output
* Support `--no-deprecation` argument
* Support `--trace-deprecation` argument
* Support `deprecate.property(fn, prop, message)`
0.3.0 / 2014-06-16
==================
* Add `NO_DEPRECATION` environment variable
0.2.0 / 2014-06-15
==================
* Add `deprecate.property(obj, prop, message)`
* Remove `supports-color` dependency for node.js 0.8
0.1.0 / 2014-06-15
==================
* Add `deprecate.function(fn, message)`
* Add `process.on('deprecation', fn)` emitter
* Automatically generate message when omitted from `deprecate()`
0.0.1 / 2014-06-15
==================
* Fix warning for dynamic calls at singe call site
0.0.0 / 2014-06-15
==================
* Initial implementation
@@ -0,0 +1,7 @@
const PROTOCOL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
function isAbsoluteURL(value) {
return PROTOCOL.test(value);
}
export {
isAbsoluteURL
};
@@ -0,0 +1,19 @@
import { _ as _path } from './shared/pathe.M-eThtNZ.mjs';
export { c as basename, d as dirname, e as extname, f as format, i as isAbsolute, j as join, m as matchesGlob, n as normalize, a as normalizeString, p as parse, b as relative, r as resolve, s as sep, t as toNamespacedPath } from './shared/pathe.M-eThtNZ.mjs';
const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
const _platforms = { posix: void 0, win32: void 0 };
const mix = (del = delimiter) => {
return new Proxy(_path, {
get(_, prop) {
if (prop === "delimiter") return del;
if (prop === "posix") return posix;
if (prop === "win32") return win32;
return _platforms[prop] || _path[prop];
}
});
};
const posix = /* @__PURE__ */ mix(":");
const win32 = /* @__PURE__ */ mix(";");
export { posix as default, delimiter, posix, win32 };
@@ -0,0 +1,20 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void;
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"2":"_I","514":"_K"},C:{"2":"_HF","322":"_QI"},D:{"2":"_qG","164":"_4G"},E:{"2":"_iF","1060":"_wF"},F:{"2":"_JP","514":"_7R"},G:{"2":"_XF","1060":"_JE"},H:{"2":"1D"},I:{"2":"_P"},J:{"2":"_B"},K:{"2":"_D","164":"H"},L:{"164":"I"},M:{"2":"YC"},N:{"2":"_A"},O:{"164":"bC"},P:{"164":"_F"},Q:{"164":"JE"},R:{"164":"KE"},S:{"322":"_C"}},B:7,C:"Speech Recognition API",D:true};
@@ -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 GitPullRequest = createLucideIcon("GitPullRequest", [
["circle", { cx: "18", cy: "18", r: "3", key: "1xkwt0" }],
["circle", { cx: "6", cy: "6", r: "3", key: "1lh9wr" }],
["path", { d: "M13 6h3a2 2 0 0 1 2 2v7", key: "1yeb86" }],
["line", { x1: "6", x2: "6", y1: "9", y2: "21", key: "rroup" }]
]);
export { GitPullRequest as default };
//# sourceMappingURL=git-pull-request.js.map
@@ -0,0 +1,625 @@
flf2a$ 6 5 8 -1 12
Based on a lowercase font posted by robert@cs.caltech.edu
Figletized by Wendell Hicken 11/93 (whicken@parasoft.com)
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
6 - height of a character
5 - height of a character, not including descenders
8 - max line length (excluding comment lines) + a fudge factor
-1 - default smushmode for this font (like "-m 15" on command line)
12 - number of comment lines
@
@
@
@
@
@@
@
|@
|@
@
o@
@@
@
| |@
` `@
@
@
@@
@
. . @
-+-+-@
-+-+-@
` ` @
@@
, @
,-|-.@
`-|-.@
| |@
`-|-'@
` @@
@
o /@
/ @
/ @
/ o@
@@
@
@
,-. @
|_|_@
| @
@@
@
|@
' @
@
@
@@
@
/@
| @
| @
| @
\@@
@
\ @
|@
|@
|@
/ @@
@
@
.|.@
-*-@
'|`@
@@
@
@
| @
-+- @
| @
@@
@
@
@
@
| @
' @@
@
@
@
---@
@
@@
@
@
@
@
o@
@@
@
/@
/ @
/ @
/ @
@@
@
,--.@
| |@
| |@
`--'@
@@
@
'|@
|@
|@
`@
@@
@
,--.@
,--'@
| @
`--'@
@@
@
,--.@
-|@
|@
`--'@
@@
@
| |@
`--|@
|@
`@
@@
@
---.@
`--.@
|@
`--'@
@@
@
,--.@
|--.@
| |@
`--'@
@@
@
---.@
/@
| @
| @
@@
@
,--.@
,--.@
| |@
`--'@
@@
@
,--.@
`__|@
|@
'@
@@
@
@
o@
@
o@
@@
@
@
o@
@
|@
' @@
@
/@
/ @
\ @
\@
@@
@
@
---@
---@
@
@@
@
\ @
\@
/@
/ @
@@
@
,---.@
,-'@
| @
o @
@@
@
,---.@
| o_/@
| @
`---'@
@@
@
,---.@
|---|@
| |@
` '@
@@
@
,---.@
|---.@
| |@
`---'@
@@
@
,---.@
| @
| @
`---'@
@@
@
,--. @
| |@
| |@
`--' @
@@
@
,---.@
|--- @
| @
`---'@
@@
@
,---.@
|__. @
| @
` @
@@
@
,---.@
| _.@
| |@
`---'@
@@
@
| |@
|---|@
| |@
` '@
@@
@
|@
|@
|@
`@
@@
@
|@
|@
|@
`---'@
@@
@
| /@
|__/ @
| \ @
` `@
@@
@
| @
| @
| @
`---'@
@@
@
,-.-.@
| | |@
| | |@
` ' '@
@@
@
, .@
|\ |@
| \ |@
` `'@
@@
@
,---.@
| |@
| |@
`---'@
@@
@
,---.@
|---'@
| @
` @
@@
@
,---.@
| |@
| |@
`---\@
@@
@
,---.@
|---'@
| \ @
` `@
@@
@
,---.@
`---.@
|@
`---'@
@@
@
--.--@
| @
| @
` @
@@
@
. .@
| |@
| |@
`---'@
@@
@
. ,@
| |@
\ / @
`' @
@@
@
. . .@
| | |@
| | |@
`-'-'@
@@
@
. ,@
>< @
| |@
' `@
@@
@
, .@
| |@
`---'@
| @
` @@
@
,---,@
.-' @
| @
`---'@
@@
@
,-@
| @
: @
| @
`-@@
@
\ @
\ @
\ @
\@
@@
@
-.@
|@
:@
|@
-'@@
@
. @
/ \@
@
@
@@
@
@
@
@
@
---@@
@
| @
`@
@
@
@@
@
@
,---.@
,---|@
`---^@
@@
@
| @
|---.@
| |@
`---'@
@@
@
@
,---.@
| @
`---'@
@@
@
|@
,---|@
| |@
`---'@
@@
@
@
,---.@
|---'@
`---'@
@@
@
,---.@
|__. @
| @
` @
@@
@
@
,---.@
| |@
`---|@
`---'@@
@
| @
|---.@
| |@
` '@
@@
@
o@
.@
|@
`@
@@
@
o@
.@
|@
|@
`---'@@
@
| @
|__/ @
| \ @
` `@
@@
@
| @
| @
| @
`---'@
@@
@
@
,-.-.@
| | |@
` ' '@
@@
@
@
,---.@
| |@
` '@
@@
@
@
,---.@
| |@
`---'@
@@
@
@
,---.@
| |@
|---'@
| @@
@
@
,---.@
| |@
`---|@
|@@
@
@
,---.@
| @
` @
@@
@
@
,---.@
`---.@
`---'@
@@
@
| @
|--- @
| @
`---'@
@@
@
@
. .@
| |@
`---'@
@@
@
@
. ,@
\ / @
`' @
@@
@
@
. . .@
| | |@
`-'-'@
@@
@
@
. ,@
>< @
' `@
@@
@
@
, .@
| |@
`---|@
`---'@@
@
@
,---,@
.-' @
'---'@
@@
@
,-@
| @
-: @
| @
`-@@
@
|@
|@
|@
|@
@@
@
-. @
| @
:-@
| @
-' @@
@
_ @
/ \_/@
@
@
@@
o o @
,---.@
|---|@
| |@
` '@
@@
o o @
,---.@
| |@
| |@
`---'@
@@
o o @
. .@
| |@
| |@
`---'@
@@
@
o o @
,---.@
,---|@
`---^@
@@
@
o o @
,---.@
| |@
`---'@
@@
@
o o @
. .@
| |@
`---'@
@@
@
,---.@
|---.@
| |@
|---'@
| @@
@@ -0,0 +1,201 @@
//#region src/utils/url.ts
const splitPath = (path) => {
const paths = path.split("/");
if (paths[0] === "") paths.shift();
return paths;
};
const splitRoutingPath = (routePath) => {
const { groups, path } = extractGroupsFromPath(routePath);
const paths = splitPath(path);
return replaceGroupMarks(paths, groups);
};
const extractGroupsFromPath = (path) => {
const groups = [];
path = path.replace(/\{[^}]+\}/g, (match, index) => {
const mark = `@${index}`;
groups.push([mark, match]);
return mark;
});
return {
groups,
path
};
};
const replaceGroupMarks = (paths, groups) => {
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i];
for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
paths[j] = paths[j].replace(mark, groups[i][1]);
break;
}
}
return paths;
};
const patternCache = {};
const getPattern = (label, next) => {
if (label === "*") return "*";
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
if (match) {
const cacheKey = `${label}#${next}`;
if (!patternCache[cacheKey]) {
if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
cacheKey,
match[1],
new RegExp(`^${match[2]}(?=/${next})`)
] : [
label,
match[1],
new RegExp(`^${match[2]}$`)
];
else patternCache[cacheKey] = [
label,
match[1],
true
];
}
return patternCache[cacheKey];
}
return null;
};
const tryDecode = (str, decoder) => {
try {
return decoder(str);
} catch {
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
try {
return decoder(match);
} catch {
return match;
}
});
}
};
/**
* Try to apply decodeURI() to given string.
* If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.
* @param str The string to decode.
* @returns The decoded string that sometimes contains undecodable percent encoding.
* @example
* tryDecodeURI('Hello%20World') // 'Hello World'
* tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'
*/
const tryDecodeURI = (str) => tryDecode(str, decodeURI);
const getPath = (request) => {
const url = request.url;
const start = url.indexOf("/", url.indexOf(":") + 4);
let i = start;
for (; i < url.length; i++) {
const charCode = url.charCodeAt(i);
if (charCode === 37) {
const queryIndex = url.indexOf("?", i);
const hashIndex = url.indexOf("#", i);
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
const path = url.slice(start, end);
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
} else if (charCode === 63 || charCode === 35) break;
}
return url.slice(start, i);
};
/**
* @deprecated
* Use the `URL` API instead.
*/
const getQueryStrings = (url) => {
const queryIndex = url.indexOf("?", 8);
if (queryIndex === -1) return "";
const hashIndex = url.indexOf("#", 8);
return hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : "";
};
const getPathNoStrict = (request) => {
const result = getPath(request);
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
};
/**
* Merge paths.
* @param {string[]} ...paths - The paths to merge.
* @returns {string} The merged path.
* @example
* mergePath('/api', '/users') // '/api/users'
* mergePath('/api/', '/users') // '/api/users'
* mergePath('/api', '/') // '/api'
* mergePath('/api/', '/') // '/api/'
*/
const mergePath = (base, sub, ...rest) => {
if (rest.length) sub = mergePath(sub, ...rest);
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
};
const checkOptionalParameter = (path) => {
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) return null;
const segments = path.split("/");
const results = [];
let basePath = "";
segments.forEach((segment) => {
if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
else if (/\:/.test(segment)) {
if (segment.charCodeAt(segment.length - 1) === 63) {
if (results.length === 0 && basePath === "") results.push("/");
else results.push(basePath);
const optionalSegment = segment.slice(0, -1);
basePath += "/" + optionalSegment;
results.push(basePath);
} else basePath += "/" + segment;
}
});
return results.filter((v, i, a) => a.indexOf(v) === i);
};
const tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
const _decodeURI = (value) => {
if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
return tryDecodeURIComponent(value);
};
const _getQueryParam = (url, key, multiple) => {
const hashIndex = url.indexOf("#", 8);
if (hashIndex !== -1) url = url.slice(0, hashIndex);
let encoded;
if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
let keyIndex = url.indexOf("?", 8);
if (keyIndex === -1) return;
if (!url.startsWith(key, keyIndex + 1)) keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
while (keyIndex !== -1) {
const trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1);
if (trailingKeyCode === 61) {
const valueIndex = keyIndex + key.length + 2;
const endIndex = url.indexOf("&", valueIndex);
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
keyIndex = url.indexOf(`&${key}`, keyIndex + 1);
}
encoded = /[%+]/.test(url);
if (!encoded) return;
}
const results = Object.create(null);
encoded ??= /[%+]/.test(url);
let keyIndex = url.indexOf("?", 8);
while (keyIndex !== -1) {
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
let valueIndex = url.indexOf("=", keyIndex);
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
if (encoded) name = _decodeURI(name);
keyIndex = nextKeyIndex;
if (name === "") continue;
let value;
if (valueIndex === -1) value = "";
else {
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
if (encoded) value = _decodeURI(value);
}
if (multiple) {
if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
results[name].push(value);
} else results[name] ??= value;
}
return key ? results[key] : results;
};
const getQueryParam = _getQueryParam;
const getQueryParams = (url, key) => {
return _getQueryParam(url, key, true);
};
const decodeURIComponent_ = decodeURIComponent;
//#endregion
export { checkOptionalParameter, decodeURIComponent_, getPath, getPathNoStrict, getPattern, getQueryParam, getQueryParams, getQueryStrings, mergePath, splitPath, splitRoutingPath, tryDecode, tryDecodeURI, tryDecodeURIComponent };
@@ -0,0 +1,192 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FloatingUIUtilsDOM = {}));
})(this, (function (exports) { 'use strict';
function hasWindow() {
return typeof window !== 'undefined';
}
function getNodeName(node) {
if (isNode(node)) {
return (node.nodeName || '').toLowerCase();
}
// Mocked nodes in testing environments may not be instances of Node. By
// returning `#document` an infinite loop won't occur.
// https://github.com/floating-ui/floating-ui/issues/2317
return '#document';
}
function getWindow(node) {
var _node$ownerDocument;
return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
var _ref;
return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode(value) {
if (!hasWindow()) {
return false;
}
return value instanceof Node || value instanceof getWindow(value).Node;
}
function isElement(value) {
if (!hasWindow()) {
return false;
}
return value instanceof Element || value instanceof getWindow(value).Element;
}
function isHTMLElement(value) {
if (!hasWindow()) {
return false;
}
return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
if (!hasWindow() || typeof ShadowRoot === 'undefined') {
return false;
}
return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
function isOverflowElement(element) {
const {
overflow,
overflowX,
overflowY,
display
} = getComputedStyle(element);
return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && display !== 'inline' && display !== 'contents';
}
function isTableElement(element) {
return /^(table|td|th)$/.test(getNodeName(element));
}
function isTopLayer(element) {
try {
if (element.matches(':popover-open')) {
return true;
}
} catch (_e) {
// no-op
}
try {
return element.matches(':modal');
} catch (_e) {
return false;
}
}
const willChangeRe = /transform|translate|scale|rotate|perspective|filter/;
const containRe = /paint|layout|strict|content/;
const isNotNone = value => !!value && value !== 'none';
let isWebKitValue;
function isContainingBlock(elementOrCss) {
const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;
// https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block
// https://drafts.csswg.org/css-transforms-2/#individual-transforms
return isNotNone(css.transform) || isNotNone(css.translate) || isNotNone(css.scale) || isNotNone(css.rotate) || isNotNone(css.perspective) || !isWebKit() && (isNotNone(css.backdropFilter) || isNotNone(css.filter)) || willChangeRe.test(css.willChange || '') || containRe.test(css.contain || '');
}
function getContainingBlock(element) {
let currentNode = getParentNode(element);
while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
if (isContainingBlock(currentNode)) {
return currentNode;
} else if (isTopLayer(currentNode)) {
return null;
}
currentNode = getParentNode(currentNode);
}
return null;
}
function isWebKit() {
if (isWebKitValue == null) {
isWebKitValue = typeof CSS !== 'undefined' && CSS.supports && CSS.supports('-webkit-backdrop-filter', 'none');
}
return isWebKitValue;
}
function isLastTraversableNode(node) {
return /^(html|body|#document)$/.test(getNodeName(node));
}
function getComputedStyle(element) {
return getWindow(element).getComputedStyle(element);
}
function getNodeScroll(element) {
if (isElement(element)) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
return {
scrollLeft: element.scrollX,
scrollTop: element.scrollY
};
}
function getParentNode(node) {
if (getNodeName(node) === 'html') {
return node;
}
const result =
// Step into the shadow DOM of the parent of a slotted node.
node.assignedSlot ||
// DOM Element detected.
node.parentNode ||
// ShadowRoot detected.
isShadowRoot(node) && node.host ||
// Fallback.
getDocumentElement(node);
return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
const parentNode = getParentNode(node);
if (isLastTraversableNode(parentNode)) {
return node.ownerDocument ? node.ownerDocument.body : node.body;
}
if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
return parentNode;
}
return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
var _node$ownerDocument2;
if (list === void 0) {
list = [];
}
if (traverseIframes === void 0) {
traverseIframes = true;
}
const scrollableAncestor = getNearestOverflowAncestor(node);
const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
const win = getWindow(scrollableAncestor);
if (isBody) {
const frameElement = getFrameElement(win);
return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
} else {
return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
}
function getFrameElement(win) {
return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
}
exports.getComputedStyle = getComputedStyle;
exports.getContainingBlock = getContainingBlock;
exports.getDocumentElement = getDocumentElement;
exports.getFrameElement = getFrameElement;
exports.getNearestOverflowAncestor = getNearestOverflowAncestor;
exports.getNodeName = getNodeName;
exports.getNodeScroll = getNodeScroll;
exports.getOverflowAncestors = getOverflowAncestors;
exports.getParentNode = getParentNode;
exports.getWindow = getWindow;
exports.isContainingBlock = isContainingBlock;
exports.isElement = isElement;
exports.isHTMLElement = isHTMLElement;
exports.isLastTraversableNode = isLastTraversableNode;
exports.isNode = isNode;
exports.isOverflowElement = isOverflowElement;
exports.isShadowRoot = isShadowRoot;
exports.isTableElement = isTableElement;
exports.isTopLayer = isTopLayer;
exports.isWebKit = isWebKit;
}));
@@ -0,0 +1 @@
{"version":3,"file":"panel-top-open.js","sources":["../../../src/icons/panel-top-open.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name PanelTopOpen\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cmVjdCB3aWR0aD0iMTgiIGhlaWdodD0iMTgiIHg9IjMiIHk9IjMiIHJ4PSIyIiAvPgogIDxwYXRoIGQ9Ik0zIDloMTgiIC8+CiAgPHBhdGggZD0ibTE1IDE0LTMgMy0zLTMiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/panel-top-open\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 PanelTopOpen = createLucideIcon('PanelTopOpen', [\n ['rect', { width: '18', height: '18', x: '3', y: '3', rx: '2', key: 'afitv7' }],\n ['path', { d: 'M3 9h18', key: '1pudct' }],\n ['path', { d: 'm15 14-3 3-3-3', key: 'g215vf' }],\n]);\n\nexport default PanelTopOpen;\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,CAAA,CACpD,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,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;AACjD,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,14 @@
import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from "../../types"
import {validateUnion} from "../code"
export type AnyOfError = ErrorNoParams<"anyOf", AnySchema[]>
const def: CodeKeywordDefinition = {
keyword: "anyOf",
schemaType: "array",
trackErrors: true,
code: validateUnion,
error: {message: "must match a schema in anyOf"},
}
export default def
@@ -0,0 +1,173 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @import * as types from "eslint-scope" */
const READ = 0x1;
const WRITE = 0x2;
const RW = READ | WRITE;
/**
* A Reference represents a single occurrence of an identifier in code.
* @constructor Reference
* @implements {types.Reference}
*/
class Reference {
constructor(
ident,
scope,
flag,
writeExpr,
maybeImplicitGlobal,
partial,
init,
) {
/**
* Identifier syntax node.
* @member {espreeIdentifier} Reference#identifier
*/
this.identifier = ident;
/**
* Reference to the enclosing Scope.
* @member {Scope} Reference#from
*/
this.from = scope;
/**
* Whether the reference comes from a dynamic scope (such as 'eval',
* 'with', etc.), and may be trapped by dynamic scopes.
* @member {boolean} Reference#tainted
*/
this.tainted = false;
/**
* The variable this reference is resolved with.
* @member {Variable} Reference#resolved
*/
this.resolved = null;
/**
* The read-write mode of the reference. (Value is one of {@link
* Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}).
* @member {number} Reference#flag
*/
this.flag = flag;
if (this.isWrite()) {
/**
* If reference is writeable, this is the tree being written to it.
* @member {espreeNode} Reference#writeExpr
*/
this.writeExpr = writeExpr;
/**
* Whether the Reference might refer to a partial value of writeExpr.
* @member {boolean} Reference#partial
*/
this.partial = partial;
/**
* Whether the Reference is to write of initialization.
* @member {boolean} Reference#init
*/
this.init = init;
}
this.__maybeImplicitGlobal = maybeImplicitGlobal;
}
/**
* Whether the reference is static.
* @function Reference#isStatic
* @returns {boolean} static
*/
isStatic() {
return (
!this.tainted && !!this.resolved && this.resolved.scope.isStatic()
);
}
/**
* Whether the reference is writeable.
* @function Reference#isWrite
* @returns {boolean} write
*/
isWrite() {
return !!(this.flag & Reference.WRITE);
}
/**
* Whether the reference is readable.
* @function Reference#isRead
* @returns {boolean} read
*/
isRead() {
return !!(this.flag & Reference.READ);
}
/**
* Whether the reference is read-only.
* @function Reference#isReadOnly
* @returns {boolean} read only
*/
isReadOnly() {
return this.flag === Reference.READ;
}
/**
* Whether the reference is write-only.
* @function Reference#isWriteOnly
* @returns {boolean} write only
*/
isWriteOnly() {
return this.flag === Reference.WRITE;
}
/**
* Whether the reference is read-write.
* @function Reference#isReadWrite
* @returns {boolean} read write
*/
isReadWrite() {
return this.flag === Reference.RW;
}
}
/**
* @constant Reference.READ
*/
Reference.READ = READ;
/**
* @constant Reference.WRITE
*/
Reference.WRITE = WRITE;
/**
* @constant Reference.RW
*/
Reference.RW = RW;
export default Reference;
/* vim: set sw=4 ts=4 et tw=80 : */
@@ -0,0 +1 @@
{"version":3,"names":["_setPrototypeOf","o","p","exports","default","Object","setPrototypeOf","bind","__proto__"],"sources":["../../src/helpers/setPrototypeOf.ts"],"sourcesContent":["/* @minVersion 7.0.0-beta.0 */\n\nexport default function _setPrototypeOf(o: object, p: object) {\n // @ts-expect-error - assigning to function\n _setPrototypeOf = Object.setPrototypeOf\n ? // @ts-expect-error - intentionally omitted argument\n Object.setPrototypeOf.bind(/* undefined */)\n : function _setPrototypeOf(o: object, p: object) {\n (o as any).__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}\n"],"mappings":";;;;;;AAEe,SAASA,eAAeA,CAACC,CAAS,EAAEC,CAAS,EAAE;EAE5DC,OAAA,CAAAC,OAAA,GAAAJ,eAAe,GAAGK,MAAM,CAACC,cAAc,GAEnCD,MAAM,CAACC,cAAc,CAACC,IAAI,CAAgB,CAAC,GAC3C,SAASP,eAAeA,CAACC,CAAS,EAAEC,CAAS,EAAE;IAC5CD,CAAC,CAASO,SAAS,GAAGN,CAAC;IACxB,OAAOD,CAAC;EACV,CAAC;EACL,OAAOD,eAAe,CAACC,CAAC,EAAEC,CAAC,CAAC;AAC9B","ignoreList":[]}