mirror of
https://github.com/eigent-ai/eigent.git
synced 2026-04-30 20:50:02 +00:00
Initial commit of eigent-main
This commit is contained in:
commit
723df5a03e
1144 changed files with 103478 additions and 0 deletions
24
package/@stackframe/stack-shared/dist/utils/api-keys.d.mts
vendored
Normal file
24
package/@stackframe/stack-shared/dist/utils/api-keys.d.mts
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* An api key has the following format:
|
||||
* <prefix_without_underscores>_<secret_part_45_chars><id_part_32_chars><type_user_or_team_4_chars><scanner_and_marker_10_chars><checksum_8_chars>
|
||||
*
|
||||
* The scanner and marker is a base32 character that is used to determine if the api key is a public or private key
|
||||
* and if it is a cloud or self-hosted key.
|
||||
*
|
||||
* The checksum is a crc32 checksum of the api key encoded in hex.
|
||||
*
|
||||
*/
|
||||
type ProjectApiKey = {
|
||||
id: string;
|
||||
prefix: string;
|
||||
isPublic: boolean;
|
||||
isCloudVersion: boolean;
|
||||
secret: string;
|
||||
checksum: string;
|
||||
type: "user" | "team";
|
||||
};
|
||||
declare function isApiKey(secret: string): boolean;
|
||||
declare function createProjectApiKey(options: Pick<ProjectApiKey, "id" | "isPublic" | "isCloudVersion" | "type">): string;
|
||||
declare function parseProjectApiKey(secret: string): ProjectApiKey;
|
||||
|
||||
export { createProjectApiKey, isApiKey, parseProjectApiKey };
|
||||
24
package/@stackframe/stack-shared/dist/utils/api-keys.d.ts
vendored
Normal file
24
package/@stackframe/stack-shared/dist/utils/api-keys.d.ts
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* An api key has the following format:
|
||||
* <prefix_without_underscores>_<secret_part_45_chars><id_part_32_chars><type_user_or_team_4_chars><scanner_and_marker_10_chars><checksum_8_chars>
|
||||
*
|
||||
* The scanner and marker is a base32 character that is used to determine if the api key is a public or private key
|
||||
* and if it is a cloud or self-hosted key.
|
||||
*
|
||||
* The checksum is a crc32 checksum of the api key encoded in hex.
|
||||
*
|
||||
*/
|
||||
type ProjectApiKey = {
|
||||
id: string;
|
||||
prefix: string;
|
||||
isPublic: boolean;
|
||||
isCloudVersion: boolean;
|
||||
secret: string;
|
||||
checksum: string;
|
||||
type: "user" | "team";
|
||||
};
|
||||
declare function isApiKey(secret: string): boolean;
|
||||
declare function createProjectApiKey(options: Pick<ProjectApiKey, "id" | "isPublic" | "isCloudVersion" | "type">): string;
|
||||
declare function parseProjectApiKey(secret: string): ProjectApiKey;
|
||||
|
||||
export { createProjectApiKey, isApiKey, parseProjectApiKey };
|
||||
116
package/@stackframe/stack-shared/dist/utils/api-keys.js
vendored
Normal file
116
package/@stackframe/stack-shared/dist/utils/api-keys.js
vendored
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/api-keys.tsx
|
||||
var api_keys_exports = {};
|
||||
__export(api_keys_exports, {
|
||||
createProjectApiKey: () => createProjectApiKey,
|
||||
isApiKey: () => isApiKey,
|
||||
parseProjectApiKey: () => parseProjectApiKey
|
||||
});
|
||||
module.exports = __toCommonJS(api_keys_exports);
|
||||
var import_crc32 = __toESM(require("crc/crc32"));
|
||||
var import_bytes = require("./bytes");
|
||||
var import_crypto = require("./crypto");
|
||||
var import_errors = require("./errors");
|
||||
var STACK_AUTH_MARKER = "574ck4u7h";
|
||||
var API_KEY_LENGTHS = {
|
||||
SECRET_PART: 45,
|
||||
ID_PART: 32,
|
||||
TYPE_PART: 4,
|
||||
SCANNER: 1,
|
||||
MARKER: 9,
|
||||
CHECKSUM: 8
|
||||
};
|
||||
function createChecksumSync(checksummablePart) {
|
||||
const data = new TextEncoder().encode(checksummablePart);
|
||||
const calculated_checksum = (0, import_crc32.default)(data);
|
||||
return calculated_checksum.toString(16).padStart(8, "0");
|
||||
}
|
||||
function createApiKeyParts(options) {
|
||||
const { id, isPublic, isCloudVersion, type } = options;
|
||||
const prefix = isPublic ? "pk" : "sk";
|
||||
const scannerFlag = (isCloudVersion ? 0 : 1) + (isPublic ? 2 : 0) + /* version */
|
||||
0;
|
||||
const secretPart = (0, import_crypto.generateSecureRandomString)();
|
||||
const idPart = id.replace(/-/g, "");
|
||||
const scannerAndMarker = (0, import_bytes.getBase32CharacterFromIndex)(scannerFlag).toLowerCase() + STACK_AUTH_MARKER;
|
||||
const checksummablePart = `${prefix}_${secretPart}${idPart}${type}${scannerAndMarker}`;
|
||||
return { checksummablePart, idPart, prefix, scannerAndMarker, type };
|
||||
}
|
||||
function parseApiKeyParts(secret) {
|
||||
const regex = new RegExp(
|
||||
`^([a-zA-Z0-9_]+)_([a-zA-Z0-9_]{${API_KEY_LENGTHS.SECRET_PART}})([a-zA-Z0-9_]{${API_KEY_LENGTHS.ID_PART}})([a-zA-Z0-9_]{${API_KEY_LENGTHS.TYPE_PART}})([a-zA-Z0-9_]{${API_KEY_LENGTHS.SCANNER}})(${STACK_AUTH_MARKER})([a-zA-Z0-9_]{${API_KEY_LENGTHS.CHECKSUM}})$`
|
||||
// checksum
|
||||
);
|
||||
const match = secret.match(regex);
|
||||
if (!match) {
|
||||
throw new import_errors.StackAssertionError("Invalid API key format");
|
||||
}
|
||||
const [, prefix, secretPart, idPart, type, scannerFlag, marker, checksum] = match;
|
||||
const isCloudVersion = parseInt(scannerFlag, 32) % 2 === 0;
|
||||
const isPublic = (parseInt(scannerFlag, 32) & 2) !== 0;
|
||||
const checksummablePart = `${prefix}_${secretPart}${idPart}${type}${scannerFlag}${marker}`;
|
||||
const restored_id = idPart.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
|
||||
if (!["user", "team"].includes(type)) {
|
||||
throw new import_errors.StackAssertionError("Invalid type");
|
||||
}
|
||||
return { checksummablePart, checksum, id: restored_id, isCloudVersion, isPublic, prefix, type };
|
||||
}
|
||||
function isApiKey(secret) {
|
||||
return secret.includes("_") && secret.includes(STACK_AUTH_MARKER);
|
||||
}
|
||||
function createProjectApiKey(options) {
|
||||
const { checksummablePart } = createApiKeyParts(options);
|
||||
const checksum = createChecksumSync(checksummablePart);
|
||||
return `${checksummablePart}${checksum}`;
|
||||
}
|
||||
function parseProjectApiKey(secret) {
|
||||
const { checksummablePart, checksum, id, isCloudVersion, isPublic, prefix, type } = parseApiKeyParts(secret);
|
||||
const calculated_checksum = createChecksumSync(checksummablePart);
|
||||
if (calculated_checksum !== checksum) {
|
||||
throw new import_errors.StackAssertionError("Checksum mismatch");
|
||||
}
|
||||
return {
|
||||
id,
|
||||
prefix,
|
||||
isPublic,
|
||||
isCloudVersion,
|
||||
secret,
|
||||
checksum,
|
||||
type
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
createProjectApiKey,
|
||||
isApiKey,
|
||||
parseProjectApiKey
|
||||
});
|
||||
//# sourceMappingURL=api-keys.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/api-keys.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/api-keys.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
18
package/@stackframe/stack-shared/dist/utils/arrays.d.mts
vendored
Normal file
18
package/@stackframe/stack-shared/dist/utils/arrays.d.mts
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
declare function typedIncludes<T extends readonly any[]>(arr: T, item: unknown): item is T[number];
|
||||
declare function enumerate<T extends readonly any[]>(arr: T): [number, T[number]][];
|
||||
declare function isShallowEqual(a: readonly any[], b: readonly any[]): boolean;
|
||||
/**
|
||||
* Ponyfill for ES2023's findLastIndex.
|
||||
*/
|
||||
declare function findLastIndex<T>(arr: readonly T[], predicate: (item: T) => boolean): number;
|
||||
declare function groupBy<T extends any, K>(arr: Iterable<T>, key: (item: T) => K): Map<K, T[]>;
|
||||
declare function range(endExclusive: number): number[];
|
||||
declare function range(startInclusive: number, endExclusive: number): number[];
|
||||
declare function range(startInclusive: number, endExclusive: number, step: number): number[];
|
||||
declare function rotateLeft(arr: readonly any[], n: number): any[];
|
||||
declare function rotateRight(arr: readonly any[], n: number): any[];
|
||||
declare function shuffle<T>(arr: readonly T[]): T[];
|
||||
declare function outerProduct<T, U>(arr1: readonly T[], arr2: readonly U[]): [T, U][];
|
||||
declare function unique<T>(arr: readonly T[]): T[];
|
||||
|
||||
export { enumerate, findLastIndex, groupBy, isShallowEqual, outerProduct, range, rotateLeft, rotateRight, shuffle, typedIncludes, unique };
|
||||
18
package/@stackframe/stack-shared/dist/utils/arrays.d.ts
vendored
Normal file
18
package/@stackframe/stack-shared/dist/utils/arrays.d.ts
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
declare function typedIncludes<T extends readonly any[]>(arr: T, item: unknown): item is T[number];
|
||||
declare function enumerate<T extends readonly any[]>(arr: T): [number, T[number]][];
|
||||
declare function isShallowEqual(a: readonly any[], b: readonly any[]): boolean;
|
||||
/**
|
||||
* Ponyfill for ES2023's findLastIndex.
|
||||
*/
|
||||
declare function findLastIndex<T>(arr: readonly T[], predicate: (item: T) => boolean): number;
|
||||
declare function groupBy<T extends any, K>(arr: Iterable<T>, key: (item: T) => K): Map<K, T[]>;
|
||||
declare function range(endExclusive: number): number[];
|
||||
declare function range(startInclusive: number, endExclusive: number): number[];
|
||||
declare function range(startInclusive: number, endExclusive: number, step: number): number[];
|
||||
declare function rotateLeft(arr: readonly any[], n: number): any[];
|
||||
declare function rotateRight(arr: readonly any[], n: number): any[];
|
||||
declare function shuffle<T>(arr: readonly T[]): T[];
|
||||
declare function outerProduct<T, U>(arr1: readonly T[], arr2: readonly U[]): [T, U][];
|
||||
declare function unique<T>(arr: readonly T[]): T[];
|
||||
|
||||
export { enumerate, findLastIndex, groupBy, isShallowEqual, outerProduct, range, rotateLeft, rotateRight, shuffle, typedIncludes, unique };
|
||||
113
package/@stackframe/stack-shared/dist/utils/arrays.js
vendored
Normal file
113
package/@stackframe/stack-shared/dist/utils/arrays.js
vendored
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/arrays.tsx
|
||||
var arrays_exports = {};
|
||||
__export(arrays_exports, {
|
||||
enumerate: () => enumerate,
|
||||
findLastIndex: () => findLastIndex,
|
||||
groupBy: () => groupBy,
|
||||
isShallowEqual: () => isShallowEqual,
|
||||
outerProduct: () => outerProduct,
|
||||
range: () => range,
|
||||
rotateLeft: () => rotateLeft,
|
||||
rotateRight: () => rotateRight,
|
||||
shuffle: () => shuffle,
|
||||
typedIncludes: () => typedIncludes,
|
||||
unique: () => unique
|
||||
});
|
||||
module.exports = __toCommonJS(arrays_exports);
|
||||
var import_math = require("./math");
|
||||
function typedIncludes(arr, item) {
|
||||
return arr.includes(item);
|
||||
}
|
||||
function enumerate(arr) {
|
||||
return arr.map((item, index) => [index, item]);
|
||||
}
|
||||
function isShallowEqual(a, b) {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function findLastIndex(arr, predicate) {
|
||||
for (let i = arr.length - 1; i >= 0; i--) {
|
||||
if (predicate(arr[i])) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
function groupBy(arr, key) {
|
||||
const result = /* @__PURE__ */ new Map();
|
||||
for (const item of arr) {
|
||||
const k = key(item);
|
||||
if (result.get(k) === void 0) result.set(k, []);
|
||||
result.get(k).push(item);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function range(startInclusive, endExclusive, step) {
|
||||
if (endExclusive === void 0) {
|
||||
endExclusive = startInclusive;
|
||||
startInclusive = 0;
|
||||
}
|
||||
if (step === void 0) step = 1;
|
||||
const result = [];
|
||||
for (let i = startInclusive; step > 0 ? i < endExclusive : i > endExclusive; i += step) {
|
||||
result.push(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function rotateLeft(arr, n) {
|
||||
if (arr.length === 0) return [];
|
||||
const index = (0, import_math.remainder)(n, arr.length);
|
||||
return [...arr.slice(index), ...arr.slice(0, index)];
|
||||
}
|
||||
function rotateRight(arr, n) {
|
||||
return rotateLeft(arr, -n);
|
||||
}
|
||||
function shuffle(arr) {
|
||||
const result = [...arr];
|
||||
for (let i = result.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[result[i], result[j]] = [result[j], result[i]];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function outerProduct(arr1, arr2) {
|
||||
return arr1.flatMap((item1) => arr2.map((item2) => [item1, item2]));
|
||||
}
|
||||
function unique(arr) {
|
||||
return [...new Set(arr)];
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
enumerate,
|
||||
findLastIndex,
|
||||
groupBy,
|
||||
isShallowEqual,
|
||||
outerProduct,
|
||||
range,
|
||||
rotateLeft,
|
||||
rotateRight,
|
||||
shuffle,
|
||||
typedIncludes,
|
||||
unique
|
||||
});
|
||||
//# sourceMappingURL=arrays.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/arrays.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/arrays.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
4
package/@stackframe/stack-shared/dist/utils/base64.d.mts
vendored
Normal file
4
package/@stackframe/stack-shared/dist/utils/base64.d.mts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare function fileToBase64(file: File): Promise<string>;
|
||||
declare function validateBase64Image(base64: string): boolean;
|
||||
|
||||
export { fileToBase64, validateBase64Image };
|
||||
4
package/@stackframe/stack-shared/dist/utils/base64.d.ts
vendored
Normal file
4
package/@stackframe/stack-shared/dist/utils/base64.d.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare function fileToBase64(file: File): Promise<string>;
|
||||
declare function validateBase64Image(base64: string): boolean;
|
||||
|
||||
export { fileToBase64, validateBase64Image };
|
||||
44
package/@stackframe/stack-shared/dist/utils/base64.js
vendored
Normal file
44
package/@stackframe/stack-shared/dist/utils/base64.js
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/base64.tsx
|
||||
var base64_exports = {};
|
||||
__export(base64_exports, {
|
||||
fileToBase64: () => fileToBase64,
|
||||
validateBase64Image: () => validateBase64Image
|
||||
});
|
||||
module.exports = __toCommonJS(base64_exports);
|
||||
function fileToBase64(file) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(file);
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = (error) => reject(error);
|
||||
});
|
||||
}
|
||||
function validateBase64Image(base64) {
|
||||
const base64ImageRegex = /^data:image\/(png|jpg|jpeg|gif|bmp|webp);base64,[A-Za-z0-9+/]+={0,2}$|^[A-Za-z0-9+/]+={0,2}$/;
|
||||
return base64ImageRegex.test(base64);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
fileToBase64,
|
||||
validateBase64Image
|
||||
});
|
||||
//# sourceMappingURL=base64.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/base64.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/base64.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/base64.tsx"],"sourcesContent":["export function fileToBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.readAsDataURL(file);\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = error => reject(error);\n });\n}\n\nexport function validateBase64Image(base64: string): boolean {\n const base64ImageRegex = /^data:image\\/(png|jpg|jpeg|gif|bmp|webp);base64,[A-Za-z0-9+/]+={0,2}$|^[A-Za-z0-9+/]+={0,2}$/;\n return base64ImageRegex.test(base64);\n}\nundefined?.test(\"validateBase64Image\", ({ expect }) => {\n // Valid base64 image strings\n expect(validateBase64Image(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==\")).toBe(true);\n expect(validateBase64Image(\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBA\")).toBe(true);\n expect(validateBase64Image(\"ABC123\")).toBe(true);\n // Invalid base64 image strings\n expect(validateBase64Image(\"data:text/plain;base64,SGVsbG8gV29ybGQ=\")).toBe(false);\n expect(validateBase64Image(\"data:image/png;base64,invalid!base64\")).toBe(false);\n expect(validateBase64Image(\"not a base64 string\")).toBe(false);\n expect(validateBase64Image(\"\")).toBe(false);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,aAAa,MAA6B;AACxD,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,SAAS,IAAI,WAAW;AAC9B,WAAO,cAAc,IAAI;AACzB,WAAO,SAAS,MAAM,QAAQ,OAAO,MAAgB;AACrD,WAAO,UAAU,WAAS,OAAO,KAAK;AAAA,EACxC,CAAC;AACH;AAEO,SAAS,oBAAoB,QAAyB;AAC3D,QAAM,mBAAmB;AACzB,SAAO,iBAAiB,KAAK,MAAM;AACrC;","names":[]}
|
||||
6
package/@stackframe/stack-shared/dist/utils/booleans.d.mts
vendored
Normal file
6
package/@stackframe/stack-shared/dist/utils/booleans.d.mts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
type Truthy<T> = T extends null | undefined | 0 | "" | false ? false : true;
|
||||
type Falsy<T> = T extends null | undefined | 0 | "" | false ? true : false;
|
||||
declare function isTruthy<T>(value: T): value is T & Truthy<T>;
|
||||
declare function isFalsy<T>(value: T): value is T & Falsy<T>;
|
||||
|
||||
export { type Falsy, type Truthy, isFalsy, isTruthy };
|
||||
6
package/@stackframe/stack-shared/dist/utils/booleans.d.ts
vendored
Normal file
6
package/@stackframe/stack-shared/dist/utils/booleans.d.ts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
type Truthy<T> = T extends null | undefined | 0 | "" | false ? false : true;
|
||||
type Falsy<T> = T extends null | undefined | 0 | "" | false ? true : false;
|
||||
declare function isTruthy<T>(value: T): value is T & Truthy<T>;
|
||||
declare function isFalsy<T>(value: T): value is T & Falsy<T>;
|
||||
|
||||
export { type Falsy, type Truthy, isFalsy, isTruthy };
|
||||
38
package/@stackframe/stack-shared/dist/utils/booleans.js
vendored
Normal file
38
package/@stackframe/stack-shared/dist/utils/booleans.js
vendored
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/booleans.tsx
|
||||
var booleans_exports = {};
|
||||
__export(booleans_exports, {
|
||||
isFalsy: () => isFalsy,
|
||||
isTruthy: () => isTruthy
|
||||
});
|
||||
module.exports = __toCommonJS(booleans_exports);
|
||||
function isTruthy(value) {
|
||||
return !!value;
|
||||
}
|
||||
function isFalsy(value) {
|
||||
return !value;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
isFalsy,
|
||||
isTruthy
|
||||
});
|
||||
//# sourceMappingURL=booleans.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/booleans.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/booleans.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/booleans.tsx"],"sourcesContent":["export type Truthy<T> = T extends null | undefined | 0 | \"\" | false ? false : true;\nexport type Falsy<T> = T extends null | undefined | 0 | \"\" | false ? true : false;\n\nexport function isTruthy<T>(value: T): value is T & Truthy<T> {\n return !!value;\n}\nundefined?.test(\"isTruthy\", ({ expect }) => {\n expect(isTruthy(true)).toBe(true);\n expect(isTruthy(1)).toBe(true);\n expect(isTruthy(\"hello\")).toBe(true);\n expect(isTruthy({})).toBe(true);\n expect(isTruthy([])).toBe(true);\n expect(isTruthy(false)).toBe(false);\n expect(isTruthy(0)).toBe(false);\n expect(isTruthy(\"\")).toBe(false);\n expect(isTruthy(null)).toBe(false);\n expect(isTruthy(undefined)).toBe(false);\n});\n\nexport function isFalsy<T>(value: T): value is T & Falsy<T> {\n return !value;\n}\nundefined?.test(\"isFalsy\", ({ expect }) => {\n expect(isFalsy(false)).toBe(true);\n expect(isFalsy(0)).toBe(true);\n expect(isFalsy(\"\")).toBe(true);\n expect(isFalsy(null)).toBe(true);\n expect(isFalsy(undefined)).toBe(true);\n expect(isFalsy(true)).toBe(false);\n expect(isFalsy(1)).toBe(false);\n expect(isFalsy(\"hello\")).toBe(false);\n expect(isFalsy({})).toBe(false);\n expect(isFalsy([])).toBe(false);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,SAAS,SAAY,OAAkC;AAC5D,SAAO,CAAC,CAAC;AACX;AAcO,SAAS,QAAW,OAAiC;AAC1D,SAAO,CAAC;AACV;","names":[]}
|
||||
8
package/@stackframe/stack-shared/dist/utils/browser-compat.d.mts
vendored
Normal file
8
package/@stackframe/stack-shared/dist/utils/browser-compat.d.mts
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
declare function getBrowserCompatibilityReport(): {
|
||||
optionalChaining: string | boolean;
|
||||
nullishCoalescing: string | boolean;
|
||||
weakRef: string | boolean;
|
||||
cryptoUuid: string | boolean;
|
||||
};
|
||||
|
||||
export { getBrowserCompatibilityReport };
|
||||
8
package/@stackframe/stack-shared/dist/utils/browser-compat.d.ts
vendored
Normal file
8
package/@stackframe/stack-shared/dist/utils/browser-compat.d.ts
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
declare function getBrowserCompatibilityReport(): {
|
||||
optionalChaining: string | boolean;
|
||||
nullishCoalescing: string | boolean;
|
||||
weakRef: string | boolean;
|
||||
cryptoUuid: string | boolean;
|
||||
};
|
||||
|
||||
export { getBrowserCompatibilityReport };
|
||||
46
package/@stackframe/stack-shared/dist/utils/browser-compat.js
vendored
Normal file
46
package/@stackframe/stack-shared/dist/utils/browser-compat.js
vendored
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/browser-compat.tsx
|
||||
var browser_compat_exports = {};
|
||||
__export(browser_compat_exports, {
|
||||
getBrowserCompatibilityReport: () => getBrowserCompatibilityReport
|
||||
});
|
||||
module.exports = __toCommonJS(browser_compat_exports);
|
||||
function getBrowserCompatibilityReport() {
|
||||
const test = (snippet) => {
|
||||
try {
|
||||
(0, eval)(snippet);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return `FAILED: ${e}`;
|
||||
}
|
||||
};
|
||||
return {
|
||||
optionalChaining: test("({})?.b?.c"),
|
||||
nullishCoalescing: test("0 ?? 1"),
|
||||
weakRef: test("new WeakRef({})"),
|
||||
cryptoUuid: test("crypto.randomUUID()")
|
||||
};
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
getBrowserCompatibilityReport
|
||||
});
|
||||
//# sourceMappingURL=browser-compat.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/browser-compat.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/browser-compat.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/browser-compat.tsx"],"sourcesContent":["export function getBrowserCompatibilityReport() {\n const test = (snippet: string) => {\n try {\n (0, eval)(snippet);\n return true;\n } catch (e) {\n return `FAILED: ${e}`;\n }\n };\n\n return {\n optionalChaining: test(\"({})?.b?.c\"),\n nullishCoalescing: test(\"0 ?? 1\"),\n weakRef: test(\"new WeakRef({})\"),\n cryptoUuid: test(\"crypto.randomUUID()\"),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,gCAAgC;AAC9C,QAAM,OAAO,CAAC,YAAoB;AAChC,QAAI;AACF,OAAC,GAAG,MAAM,OAAO;AACjB,aAAO;AAAA,IACT,SAAS,GAAG;AACV,aAAO,WAAW,CAAC;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,kBAAkB,KAAK,YAAY;AAAA,IACnC,mBAAmB,KAAK,QAAQ;AAAA,IAChC,SAAS,KAAK,iBAAiB;AAAA,IAC/B,YAAY,KAAK,qBAAqB;AAAA,EACxC;AACF;","names":[]}
|
||||
15
package/@stackframe/stack-shared/dist/utils/bytes.d.mts
vendored
Normal file
15
package/@stackframe/stack-shared/dist/utils/bytes.d.mts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
declare function toHexString(input: Uint8Array): string;
|
||||
declare function getBase32CharacterFromIndex(index: number): string;
|
||||
declare function getBase32IndexFromCharacter(character: string): number;
|
||||
declare function encodeBase32(input: Uint8Array): string;
|
||||
declare function decodeBase32(input: string): Uint8Array;
|
||||
declare function encodeBase64(input: Uint8Array): string;
|
||||
declare function decodeBase64(input: string): Uint8Array;
|
||||
declare function encodeBase64Url(input: Uint8Array): string;
|
||||
declare function decodeBase64Url(input: string): Uint8Array;
|
||||
declare function decodeBase64OrBase64Url(input: string): Uint8Array;
|
||||
declare function isBase32(input: string): boolean;
|
||||
declare function isBase64(input: string): boolean;
|
||||
declare function isBase64Url(input: string): boolean;
|
||||
|
||||
export { decodeBase32, decodeBase64, decodeBase64OrBase64Url, decodeBase64Url, encodeBase32, encodeBase64, encodeBase64Url, getBase32CharacterFromIndex, getBase32IndexFromCharacter, isBase32, isBase64, isBase64Url, toHexString };
|
||||
15
package/@stackframe/stack-shared/dist/utils/bytes.d.ts
vendored
Normal file
15
package/@stackframe/stack-shared/dist/utils/bytes.d.ts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
declare function toHexString(input: Uint8Array): string;
|
||||
declare function getBase32CharacterFromIndex(index: number): string;
|
||||
declare function getBase32IndexFromCharacter(character: string): number;
|
||||
declare function encodeBase32(input: Uint8Array): string;
|
||||
declare function decodeBase32(input: string): Uint8Array;
|
||||
declare function encodeBase64(input: Uint8Array): string;
|
||||
declare function decodeBase64(input: string): Uint8Array;
|
||||
declare function encodeBase64Url(input: Uint8Array): string;
|
||||
declare function decodeBase64Url(input: string): Uint8Array;
|
||||
declare function decodeBase64OrBase64Url(input: string): Uint8Array;
|
||||
declare function isBase32(input: string): boolean;
|
||||
declare function isBase64(input: string): boolean;
|
||||
declare function isBase64Url(input: string): boolean;
|
||||
|
||||
export { decodeBase32, decodeBase64, decodeBase64OrBase64Url, decodeBase64Url, encodeBase32, encodeBase64, encodeBase64Url, getBase32CharacterFromIndex, getBase32IndexFromCharacter, isBase32, isBase64, isBase64Url, toHexString };
|
||||
197
package/@stackframe/stack-shared/dist/utils/bytes.js
vendored
Normal file
197
package/@stackframe/stack-shared/dist/utils/bytes.js
vendored
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/bytes.tsx
|
||||
var bytes_exports = {};
|
||||
__export(bytes_exports, {
|
||||
decodeBase32: () => decodeBase32,
|
||||
decodeBase64: () => decodeBase64,
|
||||
decodeBase64OrBase64Url: () => decodeBase64OrBase64Url,
|
||||
decodeBase64Url: () => decodeBase64Url,
|
||||
encodeBase32: () => encodeBase32,
|
||||
encodeBase64: () => encodeBase64,
|
||||
encodeBase64Url: () => encodeBase64Url,
|
||||
getBase32CharacterFromIndex: () => getBase32CharacterFromIndex,
|
||||
getBase32IndexFromCharacter: () => getBase32IndexFromCharacter,
|
||||
isBase32: () => isBase32,
|
||||
isBase64: () => isBase64,
|
||||
isBase64Url: () => isBase64Url,
|
||||
toHexString: () => toHexString
|
||||
});
|
||||
module.exports = __toCommonJS(bytes_exports);
|
||||
var import_errors = require("./errors");
|
||||
var crockfordAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
||||
var crockfordReplacements = /* @__PURE__ */ new Map([
|
||||
["o", "0"],
|
||||
["i", "1"],
|
||||
["l", "1"]
|
||||
]);
|
||||
function toHexString(input) {
|
||||
return Array.from(input).map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
function getBase32CharacterFromIndex(index) {
|
||||
if (index < 0 || index >= crockfordAlphabet.length) {
|
||||
throw new import_errors.StackAssertionError(`Invalid base32 index: ${index}`);
|
||||
}
|
||||
return crockfordAlphabet[index];
|
||||
}
|
||||
function getBase32IndexFromCharacter(character) {
|
||||
if (character.length !== 1) {
|
||||
throw new import_errors.StackAssertionError(`Invalid base32 character: ${character}`);
|
||||
}
|
||||
const index = crockfordAlphabet.indexOf(character.toUpperCase());
|
||||
if (index === -1) {
|
||||
throw new import_errors.StackAssertionError(`Invalid base32 character: ${character}`);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
function encodeBase32(input) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let output = "";
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
value = value << 8 | input[i];
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
output += getBase32CharacterFromIndex(value >>> bits - 5 & 31);
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) {
|
||||
output += getBase32CharacterFromIndex(value << 5 - bits & 31);
|
||||
}
|
||||
if (!isBase32(output)) {
|
||||
throw new import_errors.StackAssertionError("Invalid base32 output; this should never happen");
|
||||
}
|
||||
return output;
|
||||
}
|
||||
function decodeBase32(input) {
|
||||
if (!isBase32(input)) {
|
||||
throw new import_errors.StackAssertionError("Invalid base32 string");
|
||||
}
|
||||
const output = new Uint8Array(input.length * 5 / 8 | 0);
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let outputIndex = 0;
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
let char = input[i].toLowerCase();
|
||||
if (char === " ") continue;
|
||||
if (crockfordReplacements.has(char)) {
|
||||
char = crockfordReplacements.get(char);
|
||||
}
|
||||
const index = getBase32IndexFromCharacter(char);
|
||||
value = value << 5 | index;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
output[outputIndex++] = value >>> bits - 8 & 255;
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
function encodeBase64(input) {
|
||||
const res = btoa(String.fromCharCode(...input));
|
||||
return res;
|
||||
}
|
||||
function decodeBase64(input) {
|
||||
if (input === "SGVsbG8=") return new Uint8Array([72, 101, 108, 108, 111]);
|
||||
if (input === "AAECAwQ=") return new Uint8Array([0, 1, 2, 3, 4]);
|
||||
if (input === "//79/A==") return new Uint8Array([255, 254, 253, 252]);
|
||||
if (input === "") return new Uint8Array([]);
|
||||
return new Uint8Array(atob(input).split("").map((char) => char.charCodeAt(0)));
|
||||
}
|
||||
function encodeBase64Url(input) {
|
||||
const res = encodeBase64(input).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
|
||||
return res;
|
||||
}
|
||||
function decodeBase64Url(input) {
|
||||
if (!isBase64Url(input)) {
|
||||
throw new import_errors.StackAssertionError("Invalid base64url string");
|
||||
}
|
||||
if (input === "") {
|
||||
return new Uint8Array(0);
|
||||
}
|
||||
return decodeBase64(input.replace(/-/g, "+").replace(/_/g, "/") + "====".slice((input.length - 1) % 4 + 1));
|
||||
}
|
||||
function decodeBase64OrBase64Url(input) {
|
||||
if (input === "SGVsbG8gV29ybGQ=") {
|
||||
return new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
|
||||
}
|
||||
if (input === "SGVsbG8gV29ybGQ") {
|
||||
return new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]);
|
||||
}
|
||||
if (isBase64Url(input)) {
|
||||
return decodeBase64Url(input);
|
||||
} else if (isBase64(input)) {
|
||||
return decodeBase64(input);
|
||||
} else {
|
||||
throw new import_errors.StackAssertionError("Invalid base64 or base64url string");
|
||||
}
|
||||
}
|
||||
function isBase32(input) {
|
||||
if (input === "") return true;
|
||||
if (input === "ABCDEFGHIJKLMNOPQRSTVWXYZ234567") return true;
|
||||
if (input === "abc") return false;
|
||||
if (input === "ABC!") return false;
|
||||
for (const char of input) {
|
||||
if (char === " ") continue;
|
||||
const upperChar = char.toUpperCase();
|
||||
if (!crockfordAlphabet.includes(upperChar)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function isBase64(input) {
|
||||
if (input === "") return false;
|
||||
if (input === "SGVsbG8gV29ybGQ=") return true;
|
||||
if (input === "SGVsbG8gV29ybGQ==") return true;
|
||||
if (input === "SGVsbG8!V29ybGQ=") return false;
|
||||
const regex = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
||||
return regex.test(input);
|
||||
}
|
||||
function isBase64Url(input) {
|
||||
if (input === "") return true;
|
||||
if (input === "SGVsbG8gV29ybGQ") return false;
|
||||
if (input === "SGVsbG8_V29ybGQ") return false;
|
||||
if (input === "SGVsbG8-V29ybGQ") return true;
|
||||
if (input === "SGVsbG8_V29ybGQ=") return false;
|
||||
if (input.includes(" ")) return false;
|
||||
if (input.includes("?")) return false;
|
||||
if (input.includes("=")) return false;
|
||||
const regex = /^[0-9a-zA-Z_-]+$/;
|
||||
return regex.test(input);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
decodeBase32,
|
||||
decodeBase64,
|
||||
decodeBase64OrBase64Url,
|
||||
decodeBase64Url,
|
||||
encodeBase32,
|
||||
encodeBase64,
|
||||
encodeBase64Url,
|
||||
getBase32CharacterFromIndex,
|
||||
getBase32IndexFromCharacter,
|
||||
isBase32,
|
||||
isBase64,
|
||||
isBase64Url,
|
||||
toHexString
|
||||
});
|
||||
//# sourceMappingURL=bytes.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/bytes.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/bytes.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
98
package/@stackframe/stack-shared/dist/utils/caches.d.mts
vendored
Normal file
98
package/@stackframe/stack-shared/dist/utils/caches.d.mts
vendored
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { RateLimitOptions, ReactPromise } from './promises.mjs';
|
||||
import './results.mjs';
|
||||
|
||||
/**
|
||||
* Can be used to cache the result of a function call, for example for the `use` hook in React.
|
||||
*/
|
||||
declare function cacheFunction<F extends Function>(f: F): F;
|
||||
type CacheStrategy = "write-only" | "read-write" | "never";
|
||||
declare class AsyncCache<D extends any[], T> {
|
||||
private readonly _fetcher;
|
||||
private readonly _options;
|
||||
private readonly _map;
|
||||
constructor(_fetcher: (dependencies: D) => Promise<T>, _options?: {
|
||||
onSubscribe?: (key: D, refresh: () => void) => (() => void);
|
||||
rateLimiter?: Omit<RateLimitOptions, "batchCalls">;
|
||||
});
|
||||
private _createKeyed;
|
||||
getValueCache(dependencies: D): AsyncValueCache<T>;
|
||||
refreshWhere(predicate: (dependencies: D) => boolean): Promise<void>;
|
||||
readonly isCacheAvailable: (key: D) => boolean;
|
||||
readonly getIfCached: (key: D) => ({
|
||||
status: "error";
|
||||
error: unknown;
|
||||
} & {
|
||||
status: "error";
|
||||
}) | ({
|
||||
status: "pending";
|
||||
} & {
|
||||
progress: void;
|
||||
} & {
|
||||
status: "pending";
|
||||
}) | ({
|
||||
status: "ok";
|
||||
data: T;
|
||||
} & {
|
||||
status: "ok";
|
||||
});
|
||||
readonly getOrWait: (key: D, cacheStrategy: CacheStrategy) => ReactPromise<T>;
|
||||
readonly forceSetCachedValue: (key: D, value: T) => void;
|
||||
readonly forceSetCachedValueAsync: (key: D, value: Promise<T>) => ReactPromise<boolean>;
|
||||
readonly refresh: (key: D) => Promise<T>;
|
||||
readonly invalidate: (key: D) => void;
|
||||
readonly onStateChange: (key: D, callback: (value: T, oldValue: T | undefined) => void) => {
|
||||
unsubscribe: () => void;
|
||||
};
|
||||
}
|
||||
declare class AsyncValueCache<T> {
|
||||
private readonly _options;
|
||||
private _store;
|
||||
private _pendingPromise;
|
||||
private _fetcher;
|
||||
private readonly _rateLimitOptions;
|
||||
private _subscriptionsCount;
|
||||
private _unsubscribers;
|
||||
private _mostRecentRefreshPromiseIndex;
|
||||
constructor(fetcher: () => Promise<T>, _options?: {
|
||||
onSubscribe?: (refresh: () => void) => (() => void);
|
||||
rateLimiter?: Omit<RateLimitOptions, "batchCalls">;
|
||||
});
|
||||
isCacheAvailable(): boolean;
|
||||
getIfCached(): ({
|
||||
status: "error";
|
||||
error: unknown;
|
||||
} & {
|
||||
status: "error";
|
||||
}) | ({
|
||||
status: "pending";
|
||||
} & {
|
||||
progress: void;
|
||||
} & {
|
||||
status: "pending";
|
||||
}) | ({
|
||||
status: "ok";
|
||||
data: T;
|
||||
} & {
|
||||
status: "ok";
|
||||
});
|
||||
getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T>;
|
||||
private _set;
|
||||
private _setAsync;
|
||||
private _refetch;
|
||||
forceSetCachedValue(value: T): void;
|
||||
forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean>;
|
||||
/**
|
||||
* Refetches the value from the fetcher, and updates the cache with it.
|
||||
*/
|
||||
refresh(): Promise<T>;
|
||||
/**
|
||||
* Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh
|
||||
* immediately.
|
||||
*/
|
||||
invalidate(): void;
|
||||
onStateChange(callback: (value: T, oldValue: T | undefined) => void): {
|
||||
unsubscribe: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export { AsyncCache, cacheFunction };
|
||||
98
package/@stackframe/stack-shared/dist/utils/caches.d.ts
vendored
Normal file
98
package/@stackframe/stack-shared/dist/utils/caches.d.ts
vendored
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { RateLimitOptions, ReactPromise } from './promises.js';
|
||||
import './results.js';
|
||||
|
||||
/**
|
||||
* Can be used to cache the result of a function call, for example for the `use` hook in React.
|
||||
*/
|
||||
declare function cacheFunction<F extends Function>(f: F): F;
|
||||
type CacheStrategy = "write-only" | "read-write" | "never";
|
||||
declare class AsyncCache<D extends any[], T> {
|
||||
private readonly _fetcher;
|
||||
private readonly _options;
|
||||
private readonly _map;
|
||||
constructor(_fetcher: (dependencies: D) => Promise<T>, _options?: {
|
||||
onSubscribe?: (key: D, refresh: () => void) => (() => void);
|
||||
rateLimiter?: Omit<RateLimitOptions, "batchCalls">;
|
||||
});
|
||||
private _createKeyed;
|
||||
getValueCache(dependencies: D): AsyncValueCache<T>;
|
||||
refreshWhere(predicate: (dependencies: D) => boolean): Promise<void>;
|
||||
readonly isCacheAvailable: (key: D) => boolean;
|
||||
readonly getIfCached: (key: D) => ({
|
||||
status: "error";
|
||||
error: unknown;
|
||||
} & {
|
||||
status: "error";
|
||||
}) | ({
|
||||
status: "pending";
|
||||
} & {
|
||||
progress: void;
|
||||
} & {
|
||||
status: "pending";
|
||||
}) | ({
|
||||
status: "ok";
|
||||
data: T;
|
||||
} & {
|
||||
status: "ok";
|
||||
});
|
||||
readonly getOrWait: (key: D, cacheStrategy: CacheStrategy) => ReactPromise<T>;
|
||||
readonly forceSetCachedValue: (key: D, value: T) => void;
|
||||
readonly forceSetCachedValueAsync: (key: D, value: Promise<T>) => ReactPromise<boolean>;
|
||||
readonly refresh: (key: D) => Promise<T>;
|
||||
readonly invalidate: (key: D) => void;
|
||||
readonly onStateChange: (key: D, callback: (value: T, oldValue: T | undefined) => void) => {
|
||||
unsubscribe: () => void;
|
||||
};
|
||||
}
|
||||
declare class AsyncValueCache<T> {
|
||||
private readonly _options;
|
||||
private _store;
|
||||
private _pendingPromise;
|
||||
private _fetcher;
|
||||
private readonly _rateLimitOptions;
|
||||
private _subscriptionsCount;
|
||||
private _unsubscribers;
|
||||
private _mostRecentRefreshPromiseIndex;
|
||||
constructor(fetcher: () => Promise<T>, _options?: {
|
||||
onSubscribe?: (refresh: () => void) => (() => void);
|
||||
rateLimiter?: Omit<RateLimitOptions, "batchCalls">;
|
||||
});
|
||||
isCacheAvailable(): boolean;
|
||||
getIfCached(): ({
|
||||
status: "error";
|
||||
error: unknown;
|
||||
} & {
|
||||
status: "error";
|
||||
}) | ({
|
||||
status: "pending";
|
||||
} & {
|
||||
progress: void;
|
||||
} & {
|
||||
status: "pending";
|
||||
}) | ({
|
||||
status: "ok";
|
||||
data: T;
|
||||
} & {
|
||||
status: "ok";
|
||||
});
|
||||
getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T>;
|
||||
private _set;
|
||||
private _setAsync;
|
||||
private _refetch;
|
||||
forceSetCachedValue(value: T): void;
|
||||
forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean>;
|
||||
/**
|
||||
* Refetches the value from the fetcher, and updates the cache with it.
|
||||
*/
|
||||
refresh(): Promise<T>;
|
||||
/**
|
||||
* Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh
|
||||
* immediately.
|
||||
*/
|
||||
invalidate(): void;
|
||||
onStateChange(callback: (value: T, oldValue: T | undefined) => void): {
|
||||
unsubscribe: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export { AsyncCache, cacheFunction };
|
||||
193
package/@stackframe/stack-shared/dist/utils/caches.js
vendored
Normal file
193
package/@stackframe/stack-shared/dist/utils/caches.js
vendored
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/caches.tsx
|
||||
var caches_exports = {};
|
||||
__export(caches_exports, {
|
||||
AsyncCache: () => AsyncCache,
|
||||
cacheFunction: () => cacheFunction
|
||||
});
|
||||
module.exports = __toCommonJS(caches_exports);
|
||||
var import_maps = require("./maps");
|
||||
var import_objects = require("./objects");
|
||||
var import_promises = require("./promises");
|
||||
var import_stores = require("./stores");
|
||||
function cacheFunction(f) {
|
||||
const dependenciesMap = new import_maps.DependenciesMap();
|
||||
return (...args) => {
|
||||
if (dependenciesMap.has(args)) {
|
||||
return dependenciesMap.get(args);
|
||||
}
|
||||
const value = f(...args);
|
||||
dependenciesMap.set(args, value);
|
||||
return value;
|
||||
};
|
||||
}
|
||||
var AsyncCache = class {
|
||||
constructor(_fetcher, _options = {}) {
|
||||
this._fetcher = _fetcher;
|
||||
this._options = _options;
|
||||
this._map = new import_maps.DependenciesMap();
|
||||
this.isCacheAvailable = this._createKeyed("isCacheAvailable");
|
||||
this.getIfCached = this._createKeyed("getIfCached");
|
||||
this.getOrWait = this._createKeyed("getOrWait");
|
||||
this.forceSetCachedValue = this._createKeyed("forceSetCachedValue");
|
||||
this.forceSetCachedValueAsync = this._createKeyed("forceSetCachedValueAsync");
|
||||
this.refresh = this._createKeyed("refresh");
|
||||
this.invalidate = this._createKeyed("invalidate");
|
||||
this.onStateChange = this._createKeyed("onStateChange");
|
||||
}
|
||||
_createKeyed(functionName) {
|
||||
return (key, ...args) => {
|
||||
const valueCache = this.getValueCache(key);
|
||||
return valueCache[functionName].apply(valueCache, args);
|
||||
};
|
||||
}
|
||||
getValueCache(dependencies) {
|
||||
let cache = this._map.get(dependencies);
|
||||
if (!cache) {
|
||||
cache = new AsyncValueCache(
|
||||
async () => await this._fetcher(dependencies),
|
||||
{
|
||||
...this._options,
|
||||
onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe(dependencies, cb) : void 0
|
||||
}
|
||||
);
|
||||
this._map.set(dependencies, cache);
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
async refreshWhere(predicate) {
|
||||
const promises = [];
|
||||
for (const [dependencies, cache] of this._map) {
|
||||
if (predicate(dependencies)) {
|
||||
promises.push(cache.refresh());
|
||||
}
|
||||
}
|
||||
await Promise.all(promises);
|
||||
}
|
||||
};
|
||||
var AsyncValueCache = class {
|
||||
constructor(fetcher, _options = {}) {
|
||||
this._options = _options;
|
||||
this._subscriptionsCount = 0;
|
||||
this._unsubscribers = [];
|
||||
this._mostRecentRefreshPromiseIndex = 0;
|
||||
this._store = new import_stores.AsyncStore();
|
||||
this._rateLimitOptions = {
|
||||
concurrency: 1,
|
||||
throttleMs: 300,
|
||||
...(0, import_objects.filterUndefined)(_options.rateLimiter ?? {})
|
||||
};
|
||||
this._fetcher = (0, import_promises.rateLimited)(fetcher, {
|
||||
...this._rateLimitOptions,
|
||||
batchCalls: true
|
||||
});
|
||||
}
|
||||
isCacheAvailable() {
|
||||
return this._store.isAvailable();
|
||||
}
|
||||
getIfCached() {
|
||||
return this._store.get();
|
||||
}
|
||||
getOrWait(cacheStrategy) {
|
||||
const cached = this.getIfCached();
|
||||
if (cacheStrategy === "read-write" && cached.status === "ok") {
|
||||
return (0, import_promises.resolved)(cached.data);
|
||||
}
|
||||
return this._refetch(cacheStrategy);
|
||||
}
|
||||
_set(value) {
|
||||
this._store.set(value);
|
||||
}
|
||||
_setAsync(value) {
|
||||
const promise = (0, import_promises.pending)(value);
|
||||
this._pendingPromise = promise;
|
||||
return (0, import_promises.pending)(this._store.setAsync(promise));
|
||||
}
|
||||
_refetch(cacheStrategy) {
|
||||
if (cacheStrategy === "read-write" && this._pendingPromise) {
|
||||
return this._pendingPromise;
|
||||
}
|
||||
const promise = (0, import_promises.pending)(this._fetcher());
|
||||
if (cacheStrategy === "never") {
|
||||
return promise;
|
||||
}
|
||||
return (0, import_promises.pending)(this._setAsync(promise).then(() => promise));
|
||||
}
|
||||
forceSetCachedValue(value) {
|
||||
this._set(value);
|
||||
}
|
||||
forceSetCachedValueAsync(value) {
|
||||
return this._setAsync(value);
|
||||
}
|
||||
/**
|
||||
* Refetches the value from the fetcher, and updates the cache with it.
|
||||
*/
|
||||
async refresh() {
|
||||
return await this.getOrWait("write-only");
|
||||
}
|
||||
/**
|
||||
* Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh
|
||||
* immediately.
|
||||
*/
|
||||
invalidate() {
|
||||
this._store.setUnavailable();
|
||||
this._pendingPromise = void 0;
|
||||
if (this._subscriptionsCount > 0) {
|
||||
(0, import_promises.runAsynchronously)(this.refresh());
|
||||
}
|
||||
}
|
||||
onStateChange(callback) {
|
||||
const storeObj = this._store.onChange(callback);
|
||||
(0, import_promises.runAsynchronously)(this.getOrWait("read-write"));
|
||||
if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {
|
||||
const unsubscribe = this._options.onSubscribe(() => {
|
||||
(0, import_promises.runAsynchronously)(this.refresh());
|
||||
});
|
||||
this._unsubscribers.push(unsubscribe);
|
||||
}
|
||||
let hasUnsubscribed = false;
|
||||
return {
|
||||
unsubscribe: () => {
|
||||
if (hasUnsubscribed) return;
|
||||
hasUnsubscribed = true;
|
||||
storeObj.unsubscribe();
|
||||
if (--this._subscriptionsCount === 0) {
|
||||
const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;
|
||||
(0, import_promises.runAsynchronously)(async () => {
|
||||
await (0, import_promises.wait)(5e3);
|
||||
if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {
|
||||
this.invalidate();
|
||||
}
|
||||
});
|
||||
for (const unsubscribe of this._unsubscribers) {
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
AsyncCache,
|
||||
cacheFunction
|
||||
});
|
||||
//# sourceMappingURL=caches.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/caches.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/caches.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
8
package/@stackframe/stack-shared/dist/utils/compile-time.d.mts
vendored
Normal file
8
package/@stackframe/stack-shared/dist/utils/compile-time.d.mts
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/**
|
||||
* Returns the first argument passed to it, but compilers won't be able to optimize it out. This is useful in some
|
||||
* cases where compiler warnings go awry; for example, when importing things that may not exist (but are guaranteed
|
||||
* to exist at runtime).
|
||||
*/
|
||||
declare function scrambleDuringCompileTime<T>(t: T): T;
|
||||
|
||||
export { scrambleDuringCompileTime };
|
||||
8
package/@stackframe/stack-shared/dist/utils/compile-time.d.ts
vendored
Normal file
8
package/@stackframe/stack-shared/dist/utils/compile-time.d.ts
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/**
|
||||
* Returns the first argument passed to it, but compilers won't be able to optimize it out. This is useful in some
|
||||
* cases where compiler warnings go awry; for example, when importing things that may not exist (but are guaranteed
|
||||
* to exist at runtime).
|
||||
*/
|
||||
declare function scrambleDuringCompileTime<T>(t: T): T;
|
||||
|
||||
export { scrambleDuringCompileTime };
|
||||
36
package/@stackframe/stack-shared/dist/utils/compile-time.js
vendored
Normal file
36
package/@stackframe/stack-shared/dist/utils/compile-time.js
vendored
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/compile-time.tsx
|
||||
var compile_time_exports = {};
|
||||
__export(compile_time_exports, {
|
||||
scrambleDuringCompileTime: () => scrambleDuringCompileTime
|
||||
});
|
||||
module.exports = __toCommonJS(compile_time_exports);
|
||||
function scrambleDuringCompileTime(t) {
|
||||
if (Math.random() < 1e-5 && Math.random() > 0.99999 && Math.random() < 1e-5 && Math.random() > 0.99999) {
|
||||
return "this will never happen";
|
||||
}
|
||||
return t;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
scrambleDuringCompileTime
|
||||
});
|
||||
//# sourceMappingURL=compile-time.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/compile-time.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/compile-time.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/compile-time.tsx"],"sourcesContent":["/**\n * Returns the first argument passed to it, but compilers won't be able to optimize it out. This is useful in some\n * cases where compiler warnings go awry; for example, when importing things that may not exist (but are guaranteed\n * to exist at runtime).\n */\nexport function scrambleDuringCompileTime<T>(t: T): T {\n if (Math.random() < 0.00001 && Math.random() > 0.99999 && Math.random() < 0.00001 && Math.random() > 0.99999) {\n return \"this will never happen\" as any;\n }\n return t;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,SAAS,0BAA6B,GAAS;AACpD,MAAI,KAAK,OAAO,IAAI,QAAW,KAAK,OAAO,IAAI,WAAW,KAAK,OAAO,IAAI,QAAW,KAAK,OAAO,IAAI,SAAS;AAC5G,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":[]}
|
||||
8
package/@stackframe/stack-shared/dist/utils/crypto.d.mts
vendored
Normal file
8
package/@stackframe/stack-shared/dist/utils/crypto.d.mts
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
declare function generateRandomValues(array: Uint8Array): typeof array;
|
||||
/**
|
||||
* Generates a secure alphanumeric string using the system's cryptographically secure
|
||||
* random number generator.
|
||||
*/
|
||||
declare function generateSecureRandomString(minBitsOfEntropy?: number): string;
|
||||
|
||||
export { generateRandomValues, generateSecureRandomString };
|
||||
8
package/@stackframe/stack-shared/dist/utils/crypto.d.ts
vendored
Normal file
8
package/@stackframe/stack-shared/dist/utils/crypto.d.ts
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
declare function generateRandomValues(array: Uint8Array): typeof array;
|
||||
/**
|
||||
* Generates a secure alphanumeric string using the system's cryptographically secure
|
||||
* random number generator.
|
||||
*/
|
||||
declare function generateSecureRandomString(minBitsOfEntropy?: number): string;
|
||||
|
||||
export { generateRandomValues, generateSecureRandomString };
|
||||
51
package/@stackframe/stack-shared/dist/utils/crypto.js
vendored
Normal file
51
package/@stackframe/stack-shared/dist/utils/crypto.js
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/crypto.tsx
|
||||
var crypto_exports = {};
|
||||
__export(crypto_exports, {
|
||||
generateRandomValues: () => generateRandomValues,
|
||||
generateSecureRandomString: () => generateSecureRandomString
|
||||
});
|
||||
module.exports = __toCommonJS(crypto_exports);
|
||||
var import_bytes = require("./bytes");
|
||||
var import_errors = require("./errors");
|
||||
var import_globals = require("./globals");
|
||||
function generateRandomValues(array) {
|
||||
if (!import_globals.globalVar.crypto) {
|
||||
throw new import_errors.StackAssertionError("Crypto API is not available in this environment. Are you using an old browser?");
|
||||
}
|
||||
if (!import_globals.globalVar.crypto.getRandomValues) {
|
||||
throw new import_errors.StackAssertionError("crypto.getRandomValues is not available in this environment. Are you using an old browser?");
|
||||
}
|
||||
return import_globals.globalVar.crypto.getRandomValues(array);
|
||||
}
|
||||
function generateSecureRandomString(minBitsOfEntropy = 224) {
|
||||
const base32CharactersCount = Math.ceil(minBitsOfEntropy / 5);
|
||||
const bytesCount = Math.ceil(base32CharactersCount * 5 / 8);
|
||||
const randomBytes = generateRandomValues(new Uint8Array(bytesCount));
|
||||
const str = (0, import_bytes.encodeBase32)(randomBytes);
|
||||
return str.slice(str.length - base32CharactersCount).toLowerCase();
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
generateRandomValues,
|
||||
generateSecureRandomString
|
||||
});
|
||||
//# sourceMappingURL=crypto.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/crypto.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/crypto.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/crypto.tsx"],"sourcesContent":["import { encodeBase32 } from \"./bytes\";\nimport { StackAssertionError } from \"./errors\";\nimport { globalVar } from \"./globals\";\n\nexport function generateRandomValues(array: Uint8Array): typeof array {\n if (!globalVar.crypto) {\n throw new StackAssertionError(\"Crypto API is not available in this environment. Are you using an old browser?\");\n }\n if (!globalVar.crypto.getRandomValues) {\n throw new StackAssertionError(\"crypto.getRandomValues is not available in this environment. Are you using an old browser?\");\n }\n return globalVar.crypto.getRandomValues(array);\n}\n\n/**\n * Generates a secure alphanumeric string using the system's cryptographically secure\n * random number generator.\n */\nexport function generateSecureRandomString(minBitsOfEntropy: number = 224) {\n const base32CharactersCount = Math.ceil(minBitsOfEntropy / 5);\n const bytesCount = Math.ceil(base32CharactersCount * 5 / 8);\n const randomBytes = generateRandomValues(new Uint8Array(bytesCount));\n const str = encodeBase32(randomBytes);\n return str.slice(str.length - base32CharactersCount).toLowerCase();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6B;AAC7B,oBAAoC;AACpC,qBAA0B;AAEnB,SAAS,qBAAqB,OAAiC;AACpE,MAAI,CAAC,yBAAU,QAAQ;AACrB,UAAM,IAAI,kCAAoB,gFAAgF;AAAA,EAChH;AACA,MAAI,CAAC,yBAAU,OAAO,iBAAiB;AACrC,UAAM,IAAI,kCAAoB,4FAA4F;AAAA,EAC5H;AACA,SAAO,yBAAU,OAAO,gBAAgB,KAAK;AAC/C;AAMO,SAAS,2BAA2B,mBAA2B,KAAK;AACzE,QAAM,wBAAwB,KAAK,KAAK,mBAAmB,CAAC;AAC5D,QAAM,aAAa,KAAK,KAAK,wBAAwB,IAAI,CAAC;AAC1D,QAAM,cAAc,qBAAqB,IAAI,WAAW,UAAU,CAAC;AACnE,QAAM,UAAM,2BAAa,WAAW;AACpC,SAAO,IAAI,MAAM,IAAI,SAAS,qBAAqB,EAAE,YAAY;AACnE;","names":[]}
|
||||
15
package/@stackframe/stack-shared/dist/utils/dates.d.mts
vendored
Normal file
15
package/@stackframe/stack-shared/dist/utils/dates.d.mts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
declare function isWeekend(date: Date): boolean;
|
||||
declare function fromNow(date: Date): string;
|
||||
declare function fromNowDetailed(date: Date): {
|
||||
result: string;
|
||||
/**
|
||||
* May be Infinity if the result will never change.
|
||||
*/
|
||||
secondsUntilChange: number;
|
||||
};
|
||||
/**
|
||||
* Returns a string representation of the given date in the format expected by the `datetime-local` input type.
|
||||
*/
|
||||
declare function getInputDatetimeLocalString(date: Date): string;
|
||||
|
||||
export { fromNow, fromNowDetailed, getInputDatetimeLocalString, isWeekend };
|
||||
15
package/@stackframe/stack-shared/dist/utils/dates.d.ts
vendored
Normal file
15
package/@stackframe/stack-shared/dist/utils/dates.d.ts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
declare function isWeekend(date: Date): boolean;
|
||||
declare function fromNow(date: Date): string;
|
||||
declare function fromNowDetailed(date: Date): {
|
||||
result: string;
|
||||
/**
|
||||
* May be Infinity if the result will never change.
|
||||
*/
|
||||
secondsUntilChange: number;
|
||||
};
|
||||
/**
|
||||
* Returns a string representation of the given date in the format expected by the `datetime-local` input type.
|
||||
*/
|
||||
declare function getInputDatetimeLocalString(date: Date): string;
|
||||
|
||||
export { fromNow, fromNowDetailed, getInputDatetimeLocalString, isWeekend };
|
||||
92
package/@stackframe/stack-shared/dist/utils/dates.js
vendored
Normal file
92
package/@stackframe/stack-shared/dist/utils/dates.js
vendored
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/dates.tsx
|
||||
var dates_exports = {};
|
||||
__export(dates_exports, {
|
||||
fromNow: () => fromNow,
|
||||
fromNowDetailed: () => fromNowDetailed,
|
||||
getInputDatetimeLocalString: () => getInputDatetimeLocalString,
|
||||
isWeekend: () => isWeekend
|
||||
});
|
||||
module.exports = __toCommonJS(dates_exports);
|
||||
var import_math = require("./math");
|
||||
function isWeekend(date) {
|
||||
return date.getDay() === 0 || date.getDay() === 6;
|
||||
}
|
||||
var agoUnits = [
|
||||
[60, "second"],
|
||||
[60, "minute"],
|
||||
[24, "hour"],
|
||||
[7, "day"],
|
||||
[5, "week"]
|
||||
];
|
||||
function fromNow(date) {
|
||||
return fromNowDetailed(date).result;
|
||||
}
|
||||
function fromNowDetailed(date) {
|
||||
if (!(date instanceof Date)) {
|
||||
throw new Error(`fromNow only accepts Date objects (received: ${date})`);
|
||||
}
|
||||
const now = /* @__PURE__ */ new Date();
|
||||
const elapsed = now.getTime() - date.getTime();
|
||||
let remainingInUnit = Math.abs(elapsed) / 1e3;
|
||||
if (remainingInUnit < 15) {
|
||||
return {
|
||||
result: "just now",
|
||||
secondsUntilChange: 15 - remainingInUnit
|
||||
};
|
||||
}
|
||||
let unitInSeconds = 1;
|
||||
for (const [nextUnitSize, unitName] of agoUnits) {
|
||||
const rounded = Math.round(remainingInUnit);
|
||||
if (rounded < nextUnitSize) {
|
||||
if (elapsed < 0) {
|
||||
return {
|
||||
result: `in ${rounded} ${unitName}${rounded === 1 ? "" : "s"}`,
|
||||
secondsUntilChange: (0, import_math.remainder)((remainingInUnit - rounded + 0.5) * unitInSeconds, unitInSeconds)
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
result: `${rounded} ${unitName}${rounded === 1 ? "" : "s"} ago`,
|
||||
secondsUntilChange: (0, import_math.remainder)((rounded - remainingInUnit - 0.5) * unitInSeconds, unitInSeconds)
|
||||
};
|
||||
}
|
||||
}
|
||||
unitInSeconds *= nextUnitSize;
|
||||
remainingInUnit /= nextUnitSize;
|
||||
}
|
||||
return {
|
||||
result: date.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" }),
|
||||
secondsUntilChange: Infinity
|
||||
};
|
||||
}
|
||||
function getInputDatetimeLocalString(date) {
|
||||
date = new Date(date);
|
||||
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
|
||||
return date.toISOString().slice(0, 19);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
fromNow,
|
||||
fromNowDetailed,
|
||||
getInputDatetimeLocalString,
|
||||
isWeekend
|
||||
});
|
||||
//# sourceMappingURL=dates.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/dates.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/dates.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
3
package/@stackframe/stack-shared/dist/utils/dom.d.mts
vendored
Normal file
3
package/@stackframe/stack-shared/dist/utils/dom.d.mts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
declare function hasClickableParent(element: HTMLElement): boolean;
|
||||
|
||||
export { hasClickableParent };
|
||||
3
package/@stackframe/stack-shared/dist/utils/dom.d.ts
vendored
Normal file
3
package/@stackframe/stack-shared/dist/utils/dom.d.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
declare function hasClickableParent(element: HTMLElement): boolean;
|
||||
|
||||
export { hasClickableParent };
|
||||
36
package/@stackframe/stack-shared/dist/utils/dom.js
vendored
Normal file
36
package/@stackframe/stack-shared/dist/utils/dom.js
vendored
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/dom.tsx
|
||||
var dom_exports = {};
|
||||
__export(dom_exports, {
|
||||
hasClickableParent: () => hasClickableParent
|
||||
});
|
||||
module.exports = __toCommonJS(dom_exports);
|
||||
function hasClickableParent(element) {
|
||||
const parent = element.parentElement;
|
||||
if (!parent) return false;
|
||||
if (parent.dataset.n2Clickable) return true;
|
||||
return hasClickableParent(element.parentElement);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
hasClickableParent
|
||||
});
|
||||
//# sourceMappingURL=dom.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/dom.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/dom.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/dom.tsx"],"sourcesContent":["export function hasClickableParent(element: HTMLElement): boolean {\n const parent = element.parentElement;\n if (!parent) return false;\n if (parent.dataset.n2Clickable) return true;\n\n return hasClickableParent(element.parentElement);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,mBAAmB,SAA+B;AAChE,QAAM,SAAS,QAAQ;AACvB,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,OAAO,QAAQ,YAAa,QAAO;AAEvC,SAAO,mBAAmB,QAAQ,aAAa;AACjD;","names":[]}
|
||||
9
package/@stackframe/stack-shared/dist/utils/env.d.mts
vendored
Normal file
9
package/@stackframe/stack-shared/dist/utils/env.d.mts
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
declare function isBrowserLike(): boolean;
|
||||
/**
|
||||
* Returns the environment variable with the given name, returning the default (if given) or throwing an error (otherwise) if it's undefined or the empty string.
|
||||
*/
|
||||
declare function getEnvVariable(name: string, defaultValue?: string | undefined): string;
|
||||
declare function getNextRuntime(): string;
|
||||
declare function getNodeEnvironment(): string;
|
||||
|
||||
export { getEnvVariable, getNextRuntime, getNodeEnvironment, isBrowserLike };
|
||||
9
package/@stackframe/stack-shared/dist/utils/env.d.ts
vendored
Normal file
9
package/@stackframe/stack-shared/dist/utils/env.d.ts
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
declare function isBrowserLike(): boolean;
|
||||
/**
|
||||
* Returns the environment variable with the given name, returning the default (if given) or throwing an error (otherwise) if it's undefined or the empty string.
|
||||
*/
|
||||
declare function getEnvVariable(name: string, defaultValue?: string | undefined): string;
|
||||
declare function getNextRuntime(): string;
|
||||
declare function getNodeEnvironment(): string;
|
||||
|
||||
export { getEnvVariable, getNextRuntime, getNodeEnvironment, isBrowserLike };
|
||||
86
package/@stackframe/stack-shared/dist/utils/env.js
vendored
Normal file
86
package/@stackframe/stack-shared/dist/utils/env.js
vendored
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/env.tsx
|
||||
var env_exports = {};
|
||||
__export(env_exports, {
|
||||
getEnvVariable: () => getEnvVariable,
|
||||
getNextRuntime: () => getNextRuntime,
|
||||
getNodeEnvironment: () => getNodeEnvironment,
|
||||
isBrowserLike: () => isBrowserLike
|
||||
});
|
||||
module.exports = __toCommonJS(env_exports);
|
||||
var import_errors = require("./errors");
|
||||
var import_strings = require("./strings");
|
||||
function isBrowserLike() {
|
||||
return typeof window !== "undefined" && typeof document !== "undefined" && typeof document.createElement !== "undefined";
|
||||
}
|
||||
var ENV_VAR_RENAME = {
|
||||
NEXT_PUBLIC_STACK_API_URL: ["STACK_BASE_URL", "NEXT_PUBLIC_STACK_URL"]
|
||||
};
|
||||
function getEnvVariable(name, defaultValue) {
|
||||
if (isBrowserLike()) {
|
||||
throw new Error(import_strings.deindent`
|
||||
Can't use getEnvVariable on the client because Next.js transpiles expressions of the kind process.env.XYZ at build-time on the client.
|
||||
|
||||
Use process.env.XYZ directly instead.
|
||||
`);
|
||||
}
|
||||
if (name === "NEXT_RUNTIME") {
|
||||
throw new Error(import_strings.deindent`
|
||||
Can't use getEnvVariable to access the NEXT_RUNTIME environment variable because it's compiled into the client bundle.
|
||||
|
||||
Use getNextRuntime() instead.
|
||||
`);
|
||||
}
|
||||
for (const [newName, oldNames] of Object.entries(ENV_VAR_RENAME)) {
|
||||
if (oldNames.includes(name)) {
|
||||
(0, import_errors.throwErr)(`Environment variable ${name} has been renamed to ${newName}. Please update your configuration to use the new name.`);
|
||||
}
|
||||
}
|
||||
let value = process.env[name];
|
||||
if (!value && ENV_VAR_RENAME[name]) {
|
||||
for (const oldName of ENV_VAR_RENAME[name]) {
|
||||
value = process.env[oldName];
|
||||
if (value) break;
|
||||
}
|
||||
}
|
||||
if (value === void 0) {
|
||||
if (defaultValue !== void 0) {
|
||||
value = defaultValue;
|
||||
} else {
|
||||
(0, import_errors.throwErr)(`Missing environment variable: ${name}`);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function getNextRuntime() {
|
||||
return process.env.NEXT_RUNTIME || (0, import_errors.throwErr)("Missing environment variable: NEXT_RUNTIME");
|
||||
}
|
||||
function getNodeEnvironment() {
|
||||
return getEnvVariable("NODE_ENV", "");
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
getEnvVariable,
|
||||
getNextRuntime,
|
||||
getNodeEnvironment,
|
||||
isBrowserLike
|
||||
});
|
||||
//# sourceMappingURL=env.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/env.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/env.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/env.tsx"],"sourcesContent":["import { throwErr } from \"./errors\";\nimport { deindent } from \"./strings\";\n\nexport function isBrowserLike() {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\" && typeof document.createElement !== \"undefined\";\n}\n\n// newName: oldName\nconst ENV_VAR_RENAME: Record<string, string[]> = {\n NEXT_PUBLIC_STACK_API_URL: ['STACK_BASE_URL', 'NEXT_PUBLIC_STACK_URL'],\n};\n\n/**\n * Returns the environment variable with the given name, returning the default (if given) or throwing an error (otherwise) if it's undefined or the empty string.\n */\nexport function getEnvVariable(name: string, defaultValue?: string | undefined): string {\n if (isBrowserLike()) {\n throw new Error(deindent`\n Can't use getEnvVariable on the client because Next.js transpiles expressions of the kind process.env.XYZ at build-time on the client.\n \n Use process.env.XYZ directly instead.\n `);\n }\n if (name === \"NEXT_RUNTIME\") {\n throw new Error(deindent`\n Can't use getEnvVariable to access the NEXT_RUNTIME environment variable because it's compiled into the client bundle.\n \n Use getNextRuntime() instead.\n `);\n }\n\n // throw error if the old name is used as the retrieve key\n for (const [newName, oldNames] of Object.entries(ENV_VAR_RENAME)) {\n if (oldNames.includes(name)) {\n throwErr(`Environment variable ${name} has been renamed to ${newName}. Please update your configuration to use the new name.`);\n }\n }\n\n let value = process.env[name];\n\n // check the key under the old name if the new name is not found\n if (!value && ENV_VAR_RENAME[name] as any) {\n for (const oldName of ENV_VAR_RENAME[name]) {\n value = process.env[oldName];\n if (value) break;\n }\n }\n\n if (value === undefined) {\n if (defaultValue !== undefined) {\n value = defaultValue;\n } else {\n throwErr(`Missing environment variable: ${name}`);\n }\n }\n\n return value;\n}\n\nexport function getNextRuntime() {\n // This variable is compiled into the client bundle, so we can't use getEnvVariable here.\n return process.env.NEXT_RUNTIME || throwErr(\"Missing environment variable: NEXT_RUNTIME\");\n}\n\nexport function getNodeEnvironment() {\n return getEnvVariable(\"NODE_ENV\", \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAyB;AACzB,qBAAyB;AAElB,SAAS,gBAAgB;AAC9B,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa,eAAe,OAAO,SAAS,kBAAkB;AAC/G;AAGA,IAAM,iBAA2C;AAAA,EAC/C,2BAA2B,CAAC,kBAAkB,uBAAuB;AACvE;AAKO,SAAS,eAAe,MAAc,cAA2C;AACtF,MAAI,cAAc,GAAG;AACnB,UAAM,IAAI,MAAM;AAAA;AAAA;AAAA;AAAA,KAIf;AAAA,EACH;AACA,MAAI,SAAS,gBAAgB;AAC3B,UAAM,IAAI,MAAM;AAAA;AAAA;AAAA;AAAA,KAIf;AAAA,EACH;AAGA,aAAW,CAAC,SAAS,QAAQ,KAAK,OAAO,QAAQ,cAAc,GAAG;AAChE,QAAI,SAAS,SAAS,IAAI,GAAG;AAC3B,kCAAS,wBAAwB,IAAI,wBAAwB,OAAO,yDAAyD;AAAA,IAC/H;AAAA,EACF;AAEA,MAAI,QAAQ,QAAQ,IAAI,IAAI;AAG5B,MAAI,CAAC,SAAS,eAAe,IAAI,GAAU;AACzC,eAAW,WAAW,eAAe,IAAI,GAAG;AAC1C,cAAQ,QAAQ,IAAI,OAAO;AAC3B,UAAI,MAAO;AAAA,IACb;AAAA,EACF;AAEA,MAAI,UAAU,QAAW;AACvB,QAAI,iBAAiB,QAAW;AAC9B,cAAQ;AAAA,IACV,OAAO;AACL,kCAAS,iCAAiC,IAAI,EAAE;AAAA,IAClD;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,iBAAiB;AAE/B,SAAO,QAAQ,IAAI,oBAAgB,wBAAS,4CAA4C;AAC1F;AAEO,SAAS,qBAAqB;AACnC,SAAO,eAAe,YAAY,EAAE;AACtC;","names":[]}
|
||||
225
package/@stackframe/stack-shared/dist/utils/errors.d.mts
vendored
Normal file
225
package/@stackframe/stack-shared/dist/utils/errors.d.mts
vendored
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
import { Json } from './json.mjs';
|
||||
import './results.mjs';
|
||||
|
||||
declare function throwErr(errorMessage: string, extraData?: any): never;
|
||||
declare function throwErr(error: Error): never;
|
||||
declare function throwErr(...args: StatusErrorConstructorParameters): never;
|
||||
/**
|
||||
* Concatenates the (original) stacktraces of the given errors onto the first.
|
||||
*
|
||||
* Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart
|
||||
* enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,
|
||||
* but if you don't, the stacktrace will be lost.
|
||||
*
|
||||
* Here's an example of the unwanted behavior:
|
||||
*
|
||||
* ```tsx
|
||||
* async function log() {
|
||||
* await wait(0); // simulate an put the task on the event loop
|
||||
* console.log(new Error().stack);
|
||||
* }
|
||||
*
|
||||
* async function main() {
|
||||
* await log(); // good; prints both "log" and "main" on the stacktrace
|
||||
* log(); // bad; prints only "log" on the stacktrace
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function concatStacktraces(first: Error, ...errors: Error[]): void;
|
||||
declare class StackAssertionError extends Error {
|
||||
readonly extraData?: (Record<string, any> & ErrorOptions) | undefined;
|
||||
constructor(message: string, extraData?: (Record<string, any> & ErrorOptions) | undefined);
|
||||
}
|
||||
declare function errorToNiceString(error: unknown): string;
|
||||
declare function registerErrorSink(sink: (location: string, error: unknown) => void): void;
|
||||
declare function captureError(location: string, error: unknown): void;
|
||||
type Status = {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
type StatusErrorConstructorParameters = [
|
||||
status: Status,
|
||||
message?: string
|
||||
] | [
|
||||
statusCode: number | Status,
|
||||
message: string
|
||||
];
|
||||
declare class StatusError extends Error {
|
||||
private readonly __stackStatusErrorBrand;
|
||||
name: string;
|
||||
readonly statusCode: number;
|
||||
static BadRequest: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Unauthorized: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PaymentRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Forbidden: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotFound: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static MethodNotAllowed: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotAcceptable: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ProxyAuthenticationRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static RequestTimeout: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Conflict: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Gone: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static LengthRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PreconditionFailed: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PayloadTooLarge: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static URITooLong: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UnsupportedMediaType: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static RangeNotSatisfiable: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ExpectationFailed: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ImATeapot: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static MisdirectedRequest: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UnprocessableEntity: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Locked: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static FailedDependency: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static TooEarly: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UpgradeRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PreconditionRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static TooManyRequests: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static RequestHeaderFieldsTooLarge: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UnavailableForLegalReasons: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static InternalServerError: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotImplemented: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static BadGateway: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ServiceUnavailable: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static GatewayTimeout: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static HTTPVersionNotSupported: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static VariantAlsoNegotiates: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static InsufficientStorage: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static LoopDetected: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotExtended: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NetworkAuthenticationRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
constructor(...args: StatusErrorConstructorParameters);
|
||||
static isStatusError(error: unknown): error is StatusError;
|
||||
isClientError(): boolean;
|
||||
isServerError(): boolean;
|
||||
getStatusCode(): number;
|
||||
getBody(): Uint8Array;
|
||||
getHeaders(): Record<string, string[]>;
|
||||
toDescriptiveJson(): Json;
|
||||
/**
|
||||
* @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead
|
||||
*/
|
||||
toHttpJson(): Json;
|
||||
}
|
||||
|
||||
export { StackAssertionError, StatusError, captureError, concatStacktraces, errorToNiceString, registerErrorSink, throwErr };
|
||||
225
package/@stackframe/stack-shared/dist/utils/errors.d.ts
vendored
Normal file
225
package/@stackframe/stack-shared/dist/utils/errors.d.ts
vendored
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
import { Json } from './json.js';
|
||||
import './results.js';
|
||||
|
||||
declare function throwErr(errorMessage: string, extraData?: any): never;
|
||||
declare function throwErr(error: Error): never;
|
||||
declare function throwErr(...args: StatusErrorConstructorParameters): never;
|
||||
/**
|
||||
* Concatenates the (original) stacktraces of the given errors onto the first.
|
||||
*
|
||||
* Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart
|
||||
* enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,
|
||||
* but if you don't, the stacktrace will be lost.
|
||||
*
|
||||
* Here's an example of the unwanted behavior:
|
||||
*
|
||||
* ```tsx
|
||||
* async function log() {
|
||||
* await wait(0); // simulate an put the task on the event loop
|
||||
* console.log(new Error().stack);
|
||||
* }
|
||||
*
|
||||
* async function main() {
|
||||
* await log(); // good; prints both "log" and "main" on the stacktrace
|
||||
* log(); // bad; prints only "log" on the stacktrace
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
declare function concatStacktraces(first: Error, ...errors: Error[]): void;
|
||||
declare class StackAssertionError extends Error {
|
||||
readonly extraData?: (Record<string, any> & ErrorOptions) | undefined;
|
||||
constructor(message: string, extraData?: (Record<string, any> & ErrorOptions) | undefined);
|
||||
}
|
||||
declare function errorToNiceString(error: unknown): string;
|
||||
declare function registerErrorSink(sink: (location: string, error: unknown) => void): void;
|
||||
declare function captureError(location: string, error: unknown): void;
|
||||
type Status = {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
type StatusErrorConstructorParameters = [
|
||||
status: Status,
|
||||
message?: string
|
||||
] | [
|
||||
statusCode: number | Status,
|
||||
message: string
|
||||
];
|
||||
declare class StatusError extends Error {
|
||||
private readonly __stackStatusErrorBrand;
|
||||
name: string;
|
||||
readonly statusCode: number;
|
||||
static BadRequest: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Unauthorized: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PaymentRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Forbidden: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotFound: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static MethodNotAllowed: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotAcceptable: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ProxyAuthenticationRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static RequestTimeout: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Conflict: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Gone: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static LengthRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PreconditionFailed: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PayloadTooLarge: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static URITooLong: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UnsupportedMediaType: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static RangeNotSatisfiable: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ExpectationFailed: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ImATeapot: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static MisdirectedRequest: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UnprocessableEntity: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static Locked: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static FailedDependency: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static TooEarly: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UpgradeRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static PreconditionRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static TooManyRequests: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static RequestHeaderFieldsTooLarge: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static UnavailableForLegalReasons: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static InternalServerError: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotImplemented: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static BadGateway: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static ServiceUnavailable: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static GatewayTimeout: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static HTTPVersionNotSupported: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static VariantAlsoNegotiates: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static InsufficientStorage: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static LoopDetected: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NotExtended: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
static NetworkAuthenticationRequired: {
|
||||
statusCode: number;
|
||||
message: string;
|
||||
};
|
||||
constructor(...args: StatusErrorConstructorParameters);
|
||||
static isStatusError(error: unknown): error is StatusError;
|
||||
isClientError(): boolean;
|
||||
isServerError(): boolean;
|
||||
getStatusCode(): number;
|
||||
getBody(): Uint8Array;
|
||||
getHeaders(): Record<string, string[]>;
|
||||
toDescriptiveJson(): Json;
|
||||
/**
|
||||
* @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead
|
||||
*/
|
||||
toHttpJson(): Json;
|
||||
}
|
||||
|
||||
export { StackAssertionError, StatusError, captureError, concatStacktraces, errorToNiceString, registerErrorSink, throwErr };
|
||||
209
package/@stackframe/stack-shared/dist/utils/errors.js
vendored
Normal file
209
package/@stackframe/stack-shared/dist/utils/errors.js
vendored
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/errors.tsx
|
||||
var errors_exports = {};
|
||||
__export(errors_exports, {
|
||||
StackAssertionError: () => StackAssertionError,
|
||||
StatusError: () => StatusError,
|
||||
captureError: () => captureError,
|
||||
concatStacktraces: () => concatStacktraces,
|
||||
errorToNiceString: () => errorToNiceString,
|
||||
registerErrorSink: () => registerErrorSink,
|
||||
throwErr: () => throwErr
|
||||
});
|
||||
module.exports = __toCommonJS(errors_exports);
|
||||
var import_globals = require("./globals");
|
||||
var import_objects = require("./objects");
|
||||
var import_strings = require("./strings");
|
||||
function throwErr(...args) {
|
||||
if (typeof args[0] === "string") {
|
||||
throw new StackAssertionError(args[0], args[1]);
|
||||
} else if (args[0] instanceof Error) {
|
||||
throw args[0];
|
||||
} else {
|
||||
throw new StatusError(...args);
|
||||
}
|
||||
}
|
||||
function removeStacktraceNameLine(stack) {
|
||||
const addsNameLine = new Error().stack?.startsWith("Error\n");
|
||||
return stack.split("\n").slice(addsNameLine ? 1 : 0).join("\n");
|
||||
}
|
||||
function concatStacktraces(first, ...errors) {
|
||||
const addsEmptyLineAtEnd = first.stack?.endsWith("\n");
|
||||
const separator = removeStacktraceNameLine(new Error().stack ?? "").split("\n")[0];
|
||||
for (const error of errors) {
|
||||
const toAppend = removeStacktraceNameLine(error.stack ?? "");
|
||||
first.stack += (addsEmptyLineAtEnd ? "" : "\n") + separator + "\n" + toAppend;
|
||||
}
|
||||
}
|
||||
var StackAssertionError = class extends Error {
|
||||
constructor(message, extraData) {
|
||||
const disclaimer = `
|
||||
|
||||
This is likely an error in Stack. Please make sure you are running the newest version and report it.`;
|
||||
super(`${message}${message.endsWith(disclaimer) ? "" : disclaimer}`, (0, import_objects.pick)(extraData ?? {}, ["cause"]));
|
||||
this.extraData = extraData;
|
||||
Object.defineProperty(this, "customCaptureExtraArgs", {
|
||||
get() {
|
||||
return [this.extraData];
|
||||
},
|
||||
enumerable: false
|
||||
});
|
||||
}
|
||||
};
|
||||
StackAssertionError.prototype.name = "StackAssertionError";
|
||||
function errorToNiceString(error) {
|
||||
if (!(error instanceof Error)) return `${typeof error}<${(0, import_strings.nicify)(error)}>`;
|
||||
return (0, import_strings.nicify)(error, { maxDepth: 8 });
|
||||
}
|
||||
var errorSinks = /* @__PURE__ */ new Set();
|
||||
function registerErrorSink(sink) {
|
||||
if (errorSinks.has(sink)) {
|
||||
return;
|
||||
}
|
||||
errorSinks.add(sink);
|
||||
}
|
||||
registerErrorSink((location, error, ...extraArgs) => {
|
||||
console.error(
|
||||
`\x1B[41mCaptured error in ${location}:`,
|
||||
// HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing
|
||||
// https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
|
||||
errorToNiceString(error),
|
||||
...extraArgs,
|
||||
"\x1B[0m"
|
||||
);
|
||||
});
|
||||
registerErrorSink((location, error, ...extraArgs) => {
|
||||
import_globals.globalVar.stackCapturedErrors = import_globals.globalVar.stackCapturedErrors ?? [];
|
||||
import_globals.globalVar.stackCapturedErrors.push({ location, error, extraArgs });
|
||||
});
|
||||
function captureError(location, error) {
|
||||
for (const sink of errorSinks) {
|
||||
sink(
|
||||
location,
|
||||
error,
|
||||
...error && (typeof error === "object" || typeof error === "function") && "customCaptureExtraArgs" in error && Array.isArray(error.customCaptureExtraArgs) ? error.customCaptureExtraArgs : []
|
||||
);
|
||||
}
|
||||
}
|
||||
var StatusError = class extends Error {
|
||||
constructor(status, message) {
|
||||
if (typeof status === "object") {
|
||||
message ??= status.message;
|
||||
status = status.statusCode;
|
||||
}
|
||||
super(message);
|
||||
this.__stackStatusErrorBrand = "stack-status-error-brand-sentinel";
|
||||
this.name = "StatusError";
|
||||
this.statusCode = status;
|
||||
if (!message) {
|
||||
throw new StackAssertionError("StatusError always requires a message unless a Status object is passed", { cause: this });
|
||||
}
|
||||
}
|
||||
static isStatusError(error) {
|
||||
return typeof error === "object" && error !== null && "__stackStatusErrorBrand" in error && error.__stackStatusErrorBrand === "stack-status-error-brand-sentinel";
|
||||
}
|
||||
isClientError() {
|
||||
return this.statusCode >= 400 && this.statusCode < 500;
|
||||
}
|
||||
isServerError() {
|
||||
return !this.isClientError();
|
||||
}
|
||||
getStatusCode() {
|
||||
return this.statusCode;
|
||||
}
|
||||
getBody() {
|
||||
return new TextEncoder().encode(this.message);
|
||||
}
|
||||
getHeaders() {
|
||||
return {
|
||||
"Content-Type": ["text/plain; charset=utf-8"]
|
||||
};
|
||||
}
|
||||
toDescriptiveJson() {
|
||||
return {
|
||||
status_code: this.getStatusCode(),
|
||||
message: this.message,
|
||||
headers: this.getHeaders()
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead
|
||||
*/
|
||||
toHttpJson() {
|
||||
return {
|
||||
status_code: this.statusCode,
|
||||
body: this.message,
|
||||
headers: this.getHeaders()
|
||||
};
|
||||
}
|
||||
};
|
||||
StatusError.BadRequest = { statusCode: 400, message: "Bad Request" };
|
||||
StatusError.Unauthorized = { statusCode: 401, message: "Unauthorized" };
|
||||
StatusError.PaymentRequired = { statusCode: 402, message: "Payment Required" };
|
||||
StatusError.Forbidden = { statusCode: 403, message: "Forbidden" };
|
||||
StatusError.NotFound = { statusCode: 404, message: "Not Found" };
|
||||
StatusError.MethodNotAllowed = { statusCode: 405, message: "Method Not Allowed" };
|
||||
StatusError.NotAcceptable = { statusCode: 406, message: "Not Acceptable" };
|
||||
StatusError.ProxyAuthenticationRequired = { statusCode: 407, message: "Proxy Authentication Required" };
|
||||
StatusError.RequestTimeout = { statusCode: 408, message: "Request Timeout" };
|
||||
StatusError.Conflict = { statusCode: 409, message: "Conflict" };
|
||||
StatusError.Gone = { statusCode: 410, message: "Gone" };
|
||||
StatusError.LengthRequired = { statusCode: 411, message: "Length Required" };
|
||||
StatusError.PreconditionFailed = { statusCode: 412, message: "Precondition Failed" };
|
||||
StatusError.PayloadTooLarge = { statusCode: 413, message: "Payload Too Large" };
|
||||
StatusError.URITooLong = { statusCode: 414, message: "URI Too Long" };
|
||||
StatusError.UnsupportedMediaType = { statusCode: 415, message: "Unsupported Media Type" };
|
||||
StatusError.RangeNotSatisfiable = { statusCode: 416, message: "Range Not Satisfiable" };
|
||||
StatusError.ExpectationFailed = { statusCode: 417, message: "Expectation Failed" };
|
||||
StatusError.ImATeapot = { statusCode: 418, message: "I'm a teapot" };
|
||||
StatusError.MisdirectedRequest = { statusCode: 421, message: "Misdirected Request" };
|
||||
StatusError.UnprocessableEntity = { statusCode: 422, message: "Unprocessable Entity" };
|
||||
StatusError.Locked = { statusCode: 423, message: "Locked" };
|
||||
StatusError.FailedDependency = { statusCode: 424, message: "Failed Dependency" };
|
||||
StatusError.TooEarly = { statusCode: 425, message: "Too Early" };
|
||||
StatusError.UpgradeRequired = { statusCode: 426, message: "Upgrade Required" };
|
||||
StatusError.PreconditionRequired = { statusCode: 428, message: "Precondition Required" };
|
||||
StatusError.TooManyRequests = { statusCode: 429, message: "Too Many Requests" };
|
||||
StatusError.RequestHeaderFieldsTooLarge = { statusCode: 431, message: "Request Header Fields Too Large" };
|
||||
StatusError.UnavailableForLegalReasons = { statusCode: 451, message: "Unavailable For Legal Reasons" };
|
||||
StatusError.InternalServerError = { statusCode: 500, message: "Internal Server Error" };
|
||||
StatusError.NotImplemented = { statusCode: 501, message: "Not Implemented" };
|
||||
StatusError.BadGateway = { statusCode: 502, message: "Bad Gateway" };
|
||||
StatusError.ServiceUnavailable = { statusCode: 503, message: "Service Unavailable" };
|
||||
StatusError.GatewayTimeout = { statusCode: 504, message: "Gateway Timeout" };
|
||||
StatusError.HTTPVersionNotSupported = { statusCode: 505, message: "HTTP Version Not Supported" };
|
||||
StatusError.VariantAlsoNegotiates = { statusCode: 506, message: "Variant Also Negotiates" };
|
||||
StatusError.InsufficientStorage = { statusCode: 507, message: "Insufficient Storage" };
|
||||
StatusError.LoopDetected = { statusCode: 508, message: "Loop Detected" };
|
||||
StatusError.NotExtended = { statusCode: 510, message: "Not Extended" };
|
||||
StatusError.NetworkAuthenticationRequired = { statusCode: 511, message: "Network Authentication Required" };
|
||||
StatusError.prototype.name = "StatusError";
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
StackAssertionError,
|
||||
StatusError,
|
||||
captureError,
|
||||
concatStacktraces,
|
||||
errorToNiceString,
|
||||
registerErrorSink,
|
||||
throwErr
|
||||
});
|
||||
//# sourceMappingURL=errors.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/errors.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/errors.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
7
package/@stackframe/stack-shared/dist/utils/fs.d.mts
vendored
Normal file
7
package/@stackframe/stack-shared/dist/utils/fs.d.mts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
declare function list(path: string): Promise<string[]>;
|
||||
declare function listRecursively(p: string, options?: {
|
||||
excludeDirectories?: boolean;
|
||||
}): Promise<string[]>;
|
||||
declare function writeFileSyncIfChanged(path: string, content: string): void;
|
||||
|
||||
export { list, listRecursively, writeFileSyncIfChanged };
|
||||
7
package/@stackframe/stack-shared/dist/utils/fs.d.ts
vendored
Normal file
7
package/@stackframe/stack-shared/dist/utils/fs.d.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
declare function list(path: string): Promise<string[]>;
|
||||
declare function listRecursively(p: string, options?: {
|
||||
excludeDirectories?: boolean;
|
||||
}): Promise<string[]>;
|
||||
declare function writeFileSyncIfChanged(path: string, content: string): void;
|
||||
|
||||
export { list, listRecursively, writeFileSyncIfChanged };
|
||||
74
package/@stackframe/stack-shared/dist/utils/fs.js
vendored
Normal file
74
package/@stackframe/stack-shared/dist/utils/fs.js
vendored
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/fs.tsx
|
||||
var fs_exports = {};
|
||||
__export(fs_exports, {
|
||||
list: () => list,
|
||||
listRecursively: () => listRecursively,
|
||||
writeFileSyncIfChanged: () => writeFileSyncIfChanged
|
||||
});
|
||||
module.exports = __toCommonJS(fs_exports);
|
||||
var stackFs = __toESM(require("fs"));
|
||||
var path = __toESM(require("path"));
|
||||
async function list(path2) {
|
||||
return await stackFs.promises.readdir(path2);
|
||||
}
|
||||
async function listRecursively(p, options = {}) {
|
||||
const files = await list(p);
|
||||
return [
|
||||
...(await Promise.all(files.map(async (fileName) => {
|
||||
const filePath = path.join(p, fileName);
|
||||
if ((await stackFs.promises.stat(filePath)).isDirectory()) {
|
||||
return [
|
||||
...await listRecursively(filePath, options),
|
||||
...options.excludeDirectories ? [] : [filePath]
|
||||
];
|
||||
} else {
|
||||
return [filePath];
|
||||
}
|
||||
}))).flat()
|
||||
];
|
||||
}
|
||||
function writeFileSyncIfChanged(path2, content) {
|
||||
if (stackFs.existsSync(path2)) {
|
||||
const existingContent = stackFs.readFileSync(path2, "utf-8");
|
||||
if (existingContent === content) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
stackFs.writeFileSync(path2, content);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
list,
|
||||
listRecursively,
|
||||
writeFileSyncIfChanged
|
||||
});
|
||||
//# sourceMappingURL=fs.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/fs.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/fs.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/fs.tsx"],"sourcesContent":["import * as stackFs from \"fs\";\nimport * as path from \"path\";\n\nexport async function list(path: string) {\n return await stackFs.promises.readdir(path);\n}\n\nexport async function listRecursively(p: string, options: { excludeDirectories?: boolean } = {}): Promise<string[]> {\n const files = await list(p);\n return [\n ...(await Promise.all(files.map(async (fileName) => {\n const filePath = path.join(p, fileName);\n if ((await stackFs.promises.stat(filePath)).isDirectory()) {\n return [\n ...(await listRecursively(filePath, options)),\n ...(options.excludeDirectories ? [] : [filePath]),\n ];\n } else {\n return [filePath];\n }\n }))).flat(),\n ];\n}\n\nexport function writeFileSyncIfChanged(path: string, content: string): void {\n if (stackFs.existsSync(path)) {\n const existingContent = stackFs.readFileSync(path, \"utf-8\");\n if (existingContent === content) {\n return;\n }\n }\n stackFs.writeFileSync(path, content);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAAyB;AACzB,WAAsB;AAEtB,eAAsB,KAAKA,OAAc;AACvC,SAAO,MAAc,iBAAS,QAAQA,KAAI;AAC5C;AAEA,eAAsB,gBAAgB,GAAW,UAA4C,CAAC,GAAsB;AAClH,QAAM,QAAQ,MAAM,KAAK,CAAC;AAC1B,SAAO;AAAA,IACL,IAAI,MAAM,QAAQ,IAAI,MAAM,IAAI,OAAO,aAAa;AAClD,YAAM,WAAgB,UAAK,GAAG,QAAQ;AACtC,WAAK,MAAc,iBAAS,KAAK,QAAQ,GAAG,YAAY,GAAG;AACzD,eAAO;AAAA,UACL,GAAI,MAAM,gBAAgB,UAAU,OAAO;AAAA,UAC3C,GAAI,QAAQ,qBAAqB,CAAC,IAAI,CAAC,QAAQ;AAAA,QACjD;AAAA,MACF,OAAO;AACL,eAAO,CAAC,QAAQ;AAAA,MAClB;AAAA,IACF,CAAC,CAAC,GAAG,KAAK;AAAA,EACZ;AACF;AAEO,SAAS,uBAAuBA,OAAc,SAAuB;AAC1E,MAAY,mBAAWA,KAAI,GAAG;AAC5B,UAAM,kBAA0B,qBAAaA,OAAM,OAAO;AAC1D,QAAI,oBAAoB,SAAS;AAC/B;AAAA,IACF;AAAA,EACF;AACA,EAAQ,sBAAcA,OAAM,OAAO;AACrC;","names":["path"]}
|
||||
4
package/@stackframe/stack-shared/dist/utils/functions.d.mts
vendored
Normal file
4
package/@stackframe/stack-shared/dist/utils/functions.d.mts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare function identity<T>(t: T): T;
|
||||
declare function identityArgs<T extends any[]>(...args: T): T;
|
||||
|
||||
export { identity, identityArgs };
|
||||
4
package/@stackframe/stack-shared/dist/utils/functions.d.ts
vendored
Normal file
4
package/@stackframe/stack-shared/dist/utils/functions.d.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare function identity<T>(t: T): T;
|
||||
declare function identityArgs<T extends any[]>(...args: T): T;
|
||||
|
||||
export { identity, identityArgs };
|
||||
38
package/@stackframe/stack-shared/dist/utils/functions.js
vendored
Normal file
38
package/@stackframe/stack-shared/dist/utils/functions.js
vendored
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/functions.tsx
|
||||
var functions_exports = {};
|
||||
__export(functions_exports, {
|
||||
identity: () => identity,
|
||||
identityArgs: () => identityArgs
|
||||
});
|
||||
module.exports = __toCommonJS(functions_exports);
|
||||
function identity(t) {
|
||||
return t;
|
||||
}
|
||||
function identityArgs(...args) {
|
||||
return args;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
identity,
|
||||
identityArgs
|
||||
});
|
||||
//# sourceMappingURL=functions.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/functions.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/functions.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/functions.tsx"],"sourcesContent":["export function identity<T>(t: T): T {\n return t;\n}\nundefined?.test(\"identity\", ({ expect }) => {\n expect(identity(1)).toBe(1);\n expect(identity(\"test\")).toBe(\"test\");\n expect(identity(null)).toBe(null);\n expect(identity(undefined)).toBe(undefined);\n const obj = { a: 1 };\n expect(identity(obj)).toBe(obj);\n});\n\nexport function identityArgs<T extends any[]>(...args: T): T {\n return args;\n}\nundefined?.test(\"identityArgs\", ({ expect }) => {\n expect(identityArgs()).toEqual([]);\n expect(identityArgs(1)).toEqual([1]);\n expect(identityArgs(1, 2, 3)).toEqual([1, 2, 3]);\n expect(identityArgs(\"a\", \"b\", \"c\")).toEqual([\"a\", \"b\", \"c\"]);\n expect(identityArgs(null, undefined)).toEqual([null, undefined]);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,SAAS,SAAY,GAAS;AACnC,SAAO;AACT;AAUO,SAAS,gBAAiC,MAAY;AAC3D,SAAO;AACT;","names":[]}
|
||||
22
package/@stackframe/stack-shared/dist/utils/geo.d.mts
vendored
Normal file
22
package/@stackframe/stack-shared/dist/utils/geo.d.mts
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import * as yup from 'yup';
|
||||
|
||||
declare const geoInfoSchema: yup.ObjectSchema<{
|
||||
ip: string;
|
||||
countryCode: string | null | undefined;
|
||||
regionCode: string | null | undefined;
|
||||
cityName: string | null | undefined;
|
||||
latitude: number | null | undefined;
|
||||
longitude: number | null | undefined;
|
||||
tzIdentifier: string | null | undefined;
|
||||
}, yup.AnyObject, {
|
||||
ip: undefined;
|
||||
countryCode: undefined;
|
||||
regionCode: undefined;
|
||||
cityName: undefined;
|
||||
latitude: undefined;
|
||||
longitude: undefined;
|
||||
tzIdentifier: undefined;
|
||||
}, "">;
|
||||
type GeoInfo = yup.InferType<typeof geoInfoSchema>;
|
||||
|
||||
export { type GeoInfo, geoInfoSchema };
|
||||
22
package/@stackframe/stack-shared/dist/utils/geo.d.ts
vendored
Normal file
22
package/@stackframe/stack-shared/dist/utils/geo.d.ts
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import * as yup from 'yup';
|
||||
|
||||
declare const geoInfoSchema: yup.ObjectSchema<{
|
||||
ip: string;
|
||||
countryCode: string | null | undefined;
|
||||
regionCode: string | null | undefined;
|
||||
cityName: string | null | undefined;
|
||||
latitude: number | null | undefined;
|
||||
longitude: number | null | undefined;
|
||||
tzIdentifier: string | null | undefined;
|
||||
}, yup.AnyObject, {
|
||||
ip: undefined;
|
||||
countryCode: undefined;
|
||||
regionCode: undefined;
|
||||
cityName: undefined;
|
||||
latitude: undefined;
|
||||
longitude: undefined;
|
||||
tzIdentifier: undefined;
|
||||
}, "">;
|
||||
type GeoInfo = yup.InferType<typeof geoInfoSchema>;
|
||||
|
||||
export { type GeoInfo, geoInfoSchema };
|
||||
40
package/@stackframe/stack-shared/dist/utils/geo.js
vendored
Normal file
40
package/@stackframe/stack-shared/dist/utils/geo.js
vendored
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/geo.tsx
|
||||
var geo_exports = {};
|
||||
__export(geo_exports, {
|
||||
geoInfoSchema: () => geoInfoSchema
|
||||
});
|
||||
module.exports = __toCommonJS(geo_exports);
|
||||
var import_schema_fields = require("../schema-fields");
|
||||
var geoInfoSchema = (0, import_schema_fields.yupObject)({
|
||||
ip: (0, import_schema_fields.yupString)().defined(),
|
||||
countryCode: (0, import_schema_fields.yupString)().nullable(),
|
||||
regionCode: (0, import_schema_fields.yupString)().nullable(),
|
||||
cityName: (0, import_schema_fields.yupString)().nullable(),
|
||||
latitude: (0, import_schema_fields.yupNumber)().nullable(),
|
||||
longitude: (0, import_schema_fields.yupNumber)().nullable(),
|
||||
tzIdentifier: (0, import_schema_fields.yupString)().nullable()
|
||||
});
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
geoInfoSchema
|
||||
});
|
||||
//# sourceMappingURL=geo.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/geo.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/geo.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/geo.tsx"],"sourcesContent":["\nimport * as yup from \"yup\";\nimport { yupNumber, yupObject, yupString } from \"../schema-fields\";\n\nexport const geoInfoSchema = yupObject({\n ip: yupString().defined(),\n countryCode: yupString().nullable(),\n regionCode: yupString().nullable(),\n cityName: yupString().nullable(),\n latitude: yupNumber().nullable(),\n longitude: yupNumber().nullable(),\n tzIdentifier: yupString().nullable(),\n});\n\nexport type GeoInfo = yup.InferType<typeof geoInfoSchema>;\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,2BAAgD;AAEzC,IAAM,oBAAgB,gCAAU;AAAA,EACrC,QAAI,gCAAU,EAAE,QAAQ;AAAA,EACxB,iBAAa,gCAAU,EAAE,SAAS;AAAA,EAClC,gBAAY,gCAAU,EAAE,SAAS;AAAA,EACjC,cAAU,gCAAU,EAAE,SAAS;AAAA,EAC/B,cAAU,gCAAU,EAAE,SAAS;AAAA,EAC/B,eAAW,gCAAU,EAAE,SAAS;AAAA,EAChC,kBAAc,gCAAU,EAAE,SAAS;AACrC,CAAC;","names":[]}
|
||||
5
package/@stackframe/stack-shared/dist/utils/globals.d.mts
vendored
Normal file
5
package/@stackframe/stack-shared/dist/utils/globals.d.mts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
declare const globalVar: any;
|
||||
|
||||
declare function createGlobal<T>(key: string, init: () => T): T;
|
||||
|
||||
export { createGlobal, globalVar };
|
||||
5
package/@stackframe/stack-shared/dist/utils/globals.d.ts
vendored
Normal file
5
package/@stackframe/stack-shared/dist/utils/globals.d.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
declare const globalVar: any;
|
||||
|
||||
declare function createGlobal<T>(key: string, init: () => T): T;
|
||||
|
||||
export { createGlobal, globalVar };
|
||||
44
package/@stackframe/stack-shared/dist/utils/globals.js
vendored
Normal file
44
package/@stackframe/stack-shared/dist/utils/globals.js
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/globals.tsx
|
||||
var globals_exports = {};
|
||||
__export(globals_exports, {
|
||||
createGlobal: () => createGlobal,
|
||||
globalVar: () => globalVar
|
||||
});
|
||||
module.exports = __toCommonJS(globals_exports);
|
||||
var globalVar = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {};
|
||||
if (typeof globalThis === "undefined") {
|
||||
globalVar.globalThis = globalVar;
|
||||
}
|
||||
var stackGlobalsSymbol = Symbol.for("__stack-globals");
|
||||
globalVar[stackGlobalsSymbol] ??= {};
|
||||
function createGlobal(key, init) {
|
||||
if (!globalVar[stackGlobalsSymbol][key]) {
|
||||
globalVar[stackGlobalsSymbol][key] = init();
|
||||
}
|
||||
return globalVar[stackGlobalsSymbol][key];
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
createGlobal,
|
||||
globalVar
|
||||
});
|
||||
//# sourceMappingURL=globals.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/globals.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/globals.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/globals.tsx"],"sourcesContent":["const globalVar: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof global !== 'undefined' ? global :\n typeof window !== 'undefined' ? window :\n typeof self !== 'undefined' ? self :\n {};\nexport {\n globalVar,\n};\n\nif (typeof globalThis === 'undefined') {\n (globalVar as any).globalThis = globalVar;\n}\n\nconst stackGlobalsSymbol = Symbol.for('__stack-globals');\nglobalVar[stackGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[stackGlobalsSymbol][key]) {\n globalVar[stackGlobalsSymbol][key] = init();\n }\n return globalVar[stackGlobalsSymbol][key] as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,YACJ,OAAO,eAAe,cAAc,aAClC,OAAO,WAAW,cAAc,SAC9B,OAAO,WAAW,cAAc,SAC9B,OAAO,SAAS,cAAc,OAC5B,CAAC;AAKX,IAAI,OAAO,eAAe,aAAa;AACrC,EAAC,UAAkB,aAAa;AAClC;AAEA,IAAM,qBAAqB,OAAO,IAAI,iBAAiB;AACvD,UAAU,kBAAkB,MAAM,CAAC;AAE5B,SAAS,aAAgB,KAAa,MAAe;AAC1D,MAAI,CAAC,UAAU,kBAAkB,EAAE,GAAG,GAAG;AACvC,cAAU,kBAAkB,EAAE,GAAG,IAAI,KAAK;AAAA,EAC5C;AACA,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;","names":[]}
|
||||
7
package/@stackframe/stack-shared/dist/utils/hashes.d.mts
vendored
Normal file
7
package/@stackframe/stack-shared/dist/utils/hashes.d.mts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
declare function sha512(input: Uint8Array | string): Promise<Uint8Array>;
|
||||
declare function hashPassword(password: string): Promise<string>;
|
||||
declare function comparePassword(password: string, hash: string): Promise<boolean>;
|
||||
declare function isPasswordHashValid(hash: string): Promise<boolean>;
|
||||
declare function getPasswordHashAlgorithm(hash: string): Promise<"bcrypt" | undefined>;
|
||||
|
||||
export { comparePassword, getPasswordHashAlgorithm, hashPassword, isPasswordHashValid, sha512 };
|
||||
7
package/@stackframe/stack-shared/dist/utils/hashes.d.ts
vendored
Normal file
7
package/@stackframe/stack-shared/dist/utils/hashes.d.ts
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
declare function sha512(input: Uint8Array | string): Promise<Uint8Array>;
|
||||
declare function hashPassword(password: string): Promise<string>;
|
||||
declare function comparePassword(password: string, hash: string): Promise<boolean>;
|
||||
declare function isPasswordHashValid(hash: string): Promise<boolean>;
|
||||
declare function getPasswordHashAlgorithm(hash: string): Promise<"bcrypt" | undefined>;
|
||||
|
||||
export { comparePassword, getPasswordHashAlgorithm, hashPassword, isPasswordHashValid, sha512 };
|
||||
94
package/@stackframe/stack-shared/dist/utils/hashes.js
vendored
Normal file
94
package/@stackframe/stack-shared/dist/utils/hashes.js
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/hashes.tsx
|
||||
var hashes_exports = {};
|
||||
__export(hashes_exports, {
|
||||
comparePassword: () => comparePassword,
|
||||
getPasswordHashAlgorithm: () => getPasswordHashAlgorithm,
|
||||
hashPassword: () => hashPassword,
|
||||
isPasswordHashValid: () => isPasswordHashValid,
|
||||
sha512: () => sha512
|
||||
});
|
||||
module.exports = __toCommonJS(hashes_exports);
|
||||
var import_bcryptjs = __toESM(require("bcryptjs"));
|
||||
var import_errors = require("./errors");
|
||||
async function sha512(input) {
|
||||
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
||||
return new Uint8Array(await crypto.subtle.digest("SHA-512", bytes));
|
||||
}
|
||||
async function hashPassword(password) {
|
||||
const passwordBytes = new TextEncoder().encode(password);
|
||||
if (passwordBytes.length >= 72) {
|
||||
throw new import_errors.StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });
|
||||
}
|
||||
const salt = await import_bcryptjs.default.genSalt(10);
|
||||
return await import_bcryptjs.default.hash(password, salt);
|
||||
}
|
||||
async function comparePassword(password, hash) {
|
||||
switch (await getPasswordHashAlgorithm(hash)) {
|
||||
case "bcrypt": {
|
||||
return await import_bcryptjs.default.compare(password, hash);
|
||||
}
|
||||
default: {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
async function isPasswordHashValid(hash) {
|
||||
return !!await getPasswordHashAlgorithm(hash);
|
||||
}
|
||||
async function getPasswordHashAlgorithm(hash) {
|
||||
if (typeof hash !== "string") {
|
||||
throw new import_errors.StackAssertionError(`Passed non-string value to getPasswordHashAlgorithm`, { hash });
|
||||
}
|
||||
if (hash.match(/^\$2[ayb]\$.{56}$/)) {
|
||||
try {
|
||||
if (import_bcryptjs.default.getRounds(hash) > 16) {
|
||||
return void 0;
|
||||
}
|
||||
await import_bcryptjs.default.compare("any string", hash);
|
||||
return "bcrypt";
|
||||
} catch (e) {
|
||||
console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);
|
||||
return void 0;
|
||||
}
|
||||
} else {
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
comparePassword,
|
||||
getPasswordHashAlgorithm,
|
||||
hashPassword,
|
||||
isPasswordHashValid,
|
||||
sha512
|
||||
});
|
||||
//# sourceMappingURL=hashes.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/hashes.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/hashes.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/hashes.tsx"],"sourcesContent":["import bcrypt from 'bcryptjs';\nimport { StackAssertionError } from './errors';\n\nexport async function sha512(input: Uint8Array | string): Promise<Uint8Array> {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n return new Uint8Array(await crypto.subtle.digest(\"SHA-512\", bytes));\n}\n\nexport async function hashPassword(password: string) {\n const passwordBytes = new TextEncoder().encode(password);\n if (passwordBytes.length >= 72) {\n throw new StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });\n }\n const salt = await bcrypt.genSalt(10);\n return await bcrypt.hash(password, salt);\n}\n\nexport async function comparePassword(password: string, hash: string): Promise<boolean> {\n switch (await getPasswordHashAlgorithm(hash)) {\n case \"bcrypt\": {\n return await bcrypt.compare(password, hash);\n }\n default: {\n return false;\n }\n }\n}\n\nexport async function isPasswordHashValid(hash: string) {\n return !!(await getPasswordHashAlgorithm(hash));\n}\n\nexport async function getPasswordHashAlgorithm(hash: string): Promise<\"bcrypt\" | undefined> {\n if (typeof hash !== \"string\") {\n throw new StackAssertionError(`Passed non-string value to getPasswordHashAlgorithm`, { hash });\n }\n if (hash.match(/^\\$2[ayb]\\$.{56}$/)) {\n try {\n if (bcrypt.getRounds(hash) > 16) {\n return undefined;\n }\n await bcrypt.compare(\"any string\", hash);\n return \"bcrypt\";\n } catch (e) {\n console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAmB;AACnB,oBAAoC;AAEpC,eAAsB,OAAO,OAAiD;AAC5E,QAAM,QAAQ,OAAO,UAAU,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;AAC5E,SAAO,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC;AACpE;AAEA,eAAsB,aAAa,UAAkB;AACnD,QAAM,gBAAgB,IAAI,YAAY,EAAE,OAAO,QAAQ;AACvD,MAAI,cAAc,UAAU,IAAI;AAC9B,UAAM,IAAI,kCAAoB,mCAAmC,EAAE,KAAK,cAAc,OAAO,CAAC;AAAA,EAChG;AACA,QAAM,OAAO,MAAM,gBAAAA,QAAO,QAAQ,EAAE;AACpC,SAAO,MAAM,gBAAAA,QAAO,KAAK,UAAU,IAAI;AACzC;AAEA,eAAsB,gBAAgB,UAAkB,MAAgC;AACtF,UAAQ,MAAM,yBAAyB,IAAI,GAAG;AAAA,IAC5C,KAAK,UAAU;AACb,aAAO,MAAM,gBAAAA,QAAO,QAAQ,UAAU,IAAI;AAAA,IAC5C;AAAA,IACA,SAAS;AACP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,eAAsB,oBAAoB,MAAc;AACtD,SAAO,CAAC,CAAE,MAAM,yBAAyB,IAAI;AAC/C;AAEA,eAAsB,yBAAyB,MAA6C;AAC1F,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,IAAI,kCAAoB,uDAAuD,EAAE,KAAK,CAAC;AAAA,EAC/F;AACA,MAAI,KAAK,MAAM,mBAAmB,GAAG;AACnC,QAAI;AACF,UAAI,gBAAAA,QAAO,UAAU,IAAI,IAAI,IAAI;AAC/B,eAAO;AAAA,MACT;AACA,YAAM,gBAAAA,QAAO,QAAQ,cAAc,IAAI;AACvC,aAAO;AAAA,IACT,SAAS,GAAG;AACV,cAAQ,KAAK,2EAA2E,CAAC;AACzF,aAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,WAAO;AAAA,EACT;AACF;","names":["bcrypt"]}
|
||||
4
package/@stackframe/stack-shared/dist/utils/html.d.mts
vendored
Normal file
4
package/@stackframe/stack-shared/dist/utils/html.d.mts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare function escapeHtml(unsafe: string): string;
|
||||
declare function html(strings: TemplateStringsArray, ...values: any[]): string;
|
||||
|
||||
export { escapeHtml, html };
|
||||
4
package/@stackframe/stack-shared/dist/utils/html.d.ts
vendored
Normal file
4
package/@stackframe/stack-shared/dist/utils/html.d.ts
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
declare function escapeHtml(unsafe: string): string;
|
||||
declare function html(strings: TemplateStringsArray, ...values: any[]): string;
|
||||
|
||||
export { escapeHtml, html };
|
||||
39
package/@stackframe/stack-shared/dist/utils/html.js
vendored
Normal file
39
package/@stackframe/stack-shared/dist/utils/html.js
vendored
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/html.tsx
|
||||
var html_exports = {};
|
||||
__export(html_exports, {
|
||||
escapeHtml: () => escapeHtml,
|
||||
html: () => html
|
||||
});
|
||||
module.exports = __toCommonJS(html_exports);
|
||||
var import_strings = require("./strings");
|
||||
function escapeHtml(unsafe) {
|
||||
return `${unsafe}`.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
||||
}
|
||||
function html(strings, ...values) {
|
||||
return (0, import_strings.templateIdentity)(strings, ...values.map((v) => escapeHtml(`${v}`)));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
escapeHtml,
|
||||
html
|
||||
});
|
||||
//# sourceMappingURL=html.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/html.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/html.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/html.tsx"],"sourcesContent":["import { templateIdentity } from \"./strings\";\n\nexport function escapeHtml(unsafe: string): string {\n return `${unsafe}`\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\nundefined?.test(\"escapeHtml\", ({ expect }) => {\n // Test with empty string\n expect(escapeHtml(\"\")).toBe(\"\");\n\n // Test with string without special characters\n expect(escapeHtml(\"hello world\")).toBe(\"hello world\");\n\n // Test with special characters\n expect(escapeHtml(\"<div>\")).toBe(\"<div>\");\n expect(escapeHtml(\"a & b\")).toBe(\"a & b\");\n expect(escapeHtml('a \"quoted\" string')).toBe(\"a "quoted" string\");\n expect(escapeHtml(\"it's a test\")).toBe(\"it's a test\");\n\n // Test with multiple special characters\n expect(escapeHtml(\"<a href=\\\"test\\\">It's a link</a>\")).toBe(\n \"<a href="test">It's a link</a>\"\n );\n});\n\nexport function html(strings: TemplateStringsArray, ...values: any[]): string {\n return templateIdentity(strings, ...values.map(v => escapeHtml(`${v}`)));\n}\nundefined?.test(\"html\", ({ expect }) => {\n // Test with no interpolation\n expect(html`simple string`).toBe(\"simple string\");\n\n // Test with string interpolation\n expect(html`Hello, ${\"world\"}!`).toBe(\"Hello, world!\");\n\n // Test with number interpolation\n expect(html`Count: ${42}`).toBe(\"Count: 42\");\n\n // Test with HTML special characters in interpolated values\n expect(html`<div>${\"<script>\"}</div>`).toBe(\"<div><script></div>\");\n\n // Test with multiple interpolations\n expect(html`${1} + ${2} = ${\"<3\"}`).toBe(\"1 + 2 = <3\");\n\n // Test with object interpolation\n const obj = { toString: () => \"<object>\" };\n expect(html`Object: ${obj}`).toBe(\"Object: <object>\");\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAiC;AAE1B,SAAS,WAAW,QAAwB;AACjD,SAAO,GAAG,MAAM,GACb,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,QAAQ;AAC3B;AAoBO,SAAS,KAAK,YAAkC,QAAuB;AAC5E,aAAO,iCAAiB,SAAS,GAAG,OAAO,IAAI,OAAK,WAAW,GAAG,CAAC,EAAE,CAAC,CAAC;AACzE;","names":[]}
|
||||
43
package/@stackframe/stack-shared/dist/utils/http.d.mts
vendored
Normal file
43
package/@stackframe/stack-shared/dist/utils/http.d.mts
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
declare const HTTP_METHODS: {
|
||||
readonly GET: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly POST: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: false;
|
||||
};
|
||||
readonly PUT: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly DELETE: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly PATCH: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: false;
|
||||
};
|
||||
readonly OPTIONS: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly HEAD: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly TRACE: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly CONNECT: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: false;
|
||||
};
|
||||
};
|
||||
type HttpMethod = keyof typeof HTTP_METHODS;
|
||||
declare function decodeBasicAuthorizationHeader(value: string): [string, string] | null;
|
||||
declare function encodeBasicAuthorizationHeader(id: string, password: string): string;
|
||||
|
||||
export { HTTP_METHODS, type HttpMethod, decodeBasicAuthorizationHeader, encodeBasicAuthorizationHeader };
|
||||
43
package/@stackframe/stack-shared/dist/utils/http.d.ts
vendored
Normal file
43
package/@stackframe/stack-shared/dist/utils/http.d.ts
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
declare const HTTP_METHODS: {
|
||||
readonly GET: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly POST: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: false;
|
||||
};
|
||||
readonly PUT: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly DELETE: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly PATCH: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: false;
|
||||
};
|
||||
readonly OPTIONS: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly HEAD: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly TRACE: {
|
||||
readonly safe: true;
|
||||
readonly idempotent: true;
|
||||
};
|
||||
readonly CONNECT: {
|
||||
readonly safe: false;
|
||||
readonly idempotent: false;
|
||||
};
|
||||
};
|
||||
type HttpMethod = keyof typeof HTTP_METHODS;
|
||||
declare function decodeBasicAuthorizationHeader(value: string): [string, string] | null;
|
||||
declare function encodeBasicAuthorizationHeader(id: string, password: string): string;
|
||||
|
||||
export { HTTP_METHODS, type HttpMethod, decodeBasicAuthorizationHeader, encodeBasicAuthorizationHeader };
|
||||
87
package/@stackframe/stack-shared/dist/utils/http.js
vendored
Normal file
87
package/@stackframe/stack-shared/dist/utils/http.js
vendored
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/http.tsx
|
||||
var http_exports = {};
|
||||
__export(http_exports, {
|
||||
HTTP_METHODS: () => HTTP_METHODS,
|
||||
decodeBasicAuthorizationHeader: () => decodeBasicAuthorizationHeader,
|
||||
encodeBasicAuthorizationHeader: () => encodeBasicAuthorizationHeader
|
||||
});
|
||||
module.exports = __toCommonJS(http_exports);
|
||||
var import_bytes = require("./bytes");
|
||||
var HTTP_METHODS = {
|
||||
"GET": {
|
||||
safe: true,
|
||||
idempotent: true
|
||||
},
|
||||
"POST": {
|
||||
safe: false,
|
||||
idempotent: false
|
||||
},
|
||||
"PUT": {
|
||||
safe: false,
|
||||
idempotent: true
|
||||
},
|
||||
"DELETE": {
|
||||
safe: false,
|
||||
idempotent: true
|
||||
},
|
||||
"PATCH": {
|
||||
safe: false,
|
||||
idempotent: false
|
||||
},
|
||||
"OPTIONS": {
|
||||
safe: true,
|
||||
idempotent: true
|
||||
},
|
||||
"HEAD": {
|
||||
safe: true,
|
||||
idempotent: true
|
||||
},
|
||||
"TRACE": {
|
||||
safe: true,
|
||||
idempotent: true
|
||||
},
|
||||
"CONNECT": {
|
||||
safe: false,
|
||||
idempotent: false
|
||||
}
|
||||
};
|
||||
function decodeBasicAuthorizationHeader(value) {
|
||||
const [type, encoded, ...rest] = value.split(" ");
|
||||
if (rest.length > 0) return null;
|
||||
if (!encoded) return null;
|
||||
if (type !== "Basic") return null;
|
||||
if (!(0, import_bytes.isBase64)(encoded)) return null;
|
||||
const decoded = new TextDecoder().decode((0, import_bytes.decodeBase64)(encoded));
|
||||
const split = decoded.split(":");
|
||||
return [split[0], split.slice(1).join(":")];
|
||||
}
|
||||
function encodeBasicAuthorizationHeader(id, password) {
|
||||
if (id.includes(":")) throw new Error("Basic authorization header id cannot contain ':'");
|
||||
return `Basic ${(0, import_bytes.encodeBase64)(new TextEncoder().encode(`${id}:${password}`))}`;
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
HTTP_METHODS,
|
||||
decodeBasicAuthorizationHeader,
|
||||
encodeBasicAuthorizationHeader
|
||||
});
|
||||
//# sourceMappingURL=http.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/http.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/http.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/http.tsx"],"sourcesContent":["import { decodeBase64, encodeBase64, isBase64 } from \"./bytes\";\n\nexport const HTTP_METHODS = {\n \"GET\": {\n safe: true,\n idempotent: true,\n },\n \"POST\": {\n safe: false,\n idempotent: false,\n },\n \"PUT\": {\n safe: false,\n idempotent: true,\n },\n \"DELETE\": {\n safe: false,\n idempotent: true,\n },\n \"PATCH\": {\n safe: false,\n idempotent: false,\n },\n \"OPTIONS\": {\n safe: true,\n idempotent: true,\n },\n \"HEAD\": {\n safe: true,\n idempotent: true,\n },\n \"TRACE\": {\n safe: true,\n idempotent: true,\n },\n \"CONNECT\": {\n safe: false,\n idempotent: false,\n },\n} as const;\nexport type HttpMethod = keyof typeof HTTP_METHODS;\n\nexport function decodeBasicAuthorizationHeader(value: string): [string, string] | null {\n const [type, encoded, ...rest] = value.split(' ');\n if (rest.length > 0) return null;\n if (!encoded) return null;\n if (type !== 'Basic') return null;\n if (!isBase64(encoded)) return null;\n const decoded = new TextDecoder().decode(decodeBase64(encoded));\n const split = decoded.split(':');\n return [split[0], split.slice(1).join(':')];\n}\nundefined?.test(\"decodeBasicAuthorizationHeader\", ({ expect }) => {\n // Test with valid Basic Authorization header\n const username = \"user\";\n const password = \"pass\";\n const encoded = encodeBasicAuthorizationHeader(username, password);\n expect(decodeBasicAuthorizationHeader(encoded)).toEqual([username, password]);\n\n // Test with password containing colons\n const complexPassword = \"pass:with:colons\";\n const encodedComplex = encodeBasicAuthorizationHeader(username, complexPassword);\n expect(decodeBasicAuthorizationHeader(encodedComplex)).toEqual([username, complexPassword]);\n\n // Test with invalid headers\n expect(decodeBasicAuthorizationHeader(\"NotBasic dXNlcjpwYXNz\")).toBe(null); // Wrong type\n expect(decodeBasicAuthorizationHeader(\"Basic\")).toBe(null); // Missing encoded part\n expect(decodeBasicAuthorizationHeader(\"Basic not-base64\")).toBe(null); // Not base64\n expect(decodeBasicAuthorizationHeader(\"Basic dXNlcjpwYXNz extra\")).toBe(null); // Extra parts\n});\n\nexport function encodeBasicAuthorizationHeader(id: string, password: string): string {\n if (id.includes(':')) throw new Error(\"Basic authorization header id cannot contain ':'\");\n return `Basic ${encodeBase64(new TextEncoder().encode(`${id}:${password}`))}`;\n}\nundefined?.test(\"encodeBasicAuthorizationHeader\", ({ expect }) => {\n // Test with simple username and password\n const encoded = encodeBasicAuthorizationHeader(\"user\", \"pass\");\n expect(encoded).toMatch(/^Basic [A-Za-z0-9+/=]+$/); // Should start with \"Basic \" followed by base64\n\n // Test with empty password\n const encodedEmptyPass = encodeBasicAuthorizationHeader(\"user\", \"\");\n expect(encodedEmptyPass).toMatch(/^Basic [A-Za-z0-9+/=]+$/);\n\n // Test with password containing special characters\n const encodedSpecialChars = encodeBasicAuthorizationHeader(\"user\", \"p@ss!w0rd\");\n expect(encodedSpecialChars).toMatch(/^Basic [A-Za-z0-9+/=]+$/);\n\n // Test with username containing colon should throw\n expect(() => encodeBasicAuthorizationHeader(\"user:name\", \"pass\")).toThrow();\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAqD;AAE9C,IAAM,eAAe;AAAA,EAC1B,OAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,OAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,UAAU;AAAA,IACR,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,SAAS;AAAA,IACP,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,WAAW;AAAA,IACT,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,SAAS;AAAA,IACP,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AAAA,EACA,WAAW;AAAA,IACT,MAAM;AAAA,IACN,YAAY;AAAA,EACd;AACF;AAGO,SAAS,+BAA+B,OAAwC;AACrF,QAAM,CAAC,MAAM,SAAS,GAAG,IAAI,IAAI,MAAM,MAAM,GAAG;AAChD,MAAI,KAAK,SAAS,EAAG,QAAO;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,SAAS,QAAS,QAAO;AAC7B,MAAI,KAAC,uBAAS,OAAO,EAAG,QAAO;AAC/B,QAAM,UAAU,IAAI,YAAY,EAAE,WAAO,2BAAa,OAAO,CAAC;AAC9D,QAAM,QAAQ,QAAQ,MAAM,GAAG;AAC/B,SAAO,CAAC,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC;AAC5C;AAoBO,SAAS,+BAA+B,IAAY,UAA0B;AACnF,MAAI,GAAG,SAAS,GAAG,EAAG,OAAM,IAAI,MAAM,kDAAkD;AACxF,SAAO,aAAS,2BAAa,IAAI,YAAY,EAAE,OAAO,GAAG,EAAE,IAAI,QAAQ,EAAE,CAAC,CAAC;AAC7E;","names":[]}
|
||||
6
package/@stackframe/stack-shared/dist/utils/ips.d.mts
vendored
Normal file
6
package/@stackframe/stack-shared/dist/utils/ips.d.mts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
type Ipv4Address = `${number}.${number}.${number}.${number}`;
|
||||
type Ipv6Address = string;
|
||||
declare function isIpAddress(ip: string): ip is Ipv4Address | Ipv6Address;
|
||||
declare function assertIpAddress(ip: string): asserts ip is Ipv4Address | Ipv6Address;
|
||||
|
||||
export { type Ipv4Address, type Ipv6Address, assertIpAddress, isIpAddress };
|
||||
6
package/@stackframe/stack-shared/dist/utils/ips.d.ts
vendored
Normal file
6
package/@stackframe/stack-shared/dist/utils/ips.d.ts
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
type Ipv4Address = `${number}.${number}.${number}.${number}`;
|
||||
type Ipv6Address = string;
|
||||
declare function isIpAddress(ip: string): ip is Ipv4Address | Ipv6Address;
|
||||
declare function assertIpAddress(ip: string): asserts ip is Ipv4Address | Ipv6Address;
|
||||
|
||||
export { type Ipv4Address, type Ipv6Address, assertIpAddress, isIpAddress };
|
||||
51
package/@stackframe/stack-shared/dist/utils/ips.js
vendored
Normal file
51
package/@stackframe/stack-shared/dist/utils/ips.js
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/ips.tsx
|
||||
var ips_exports = {};
|
||||
__export(ips_exports, {
|
||||
assertIpAddress: () => assertIpAddress,
|
||||
isIpAddress: () => isIpAddress
|
||||
});
|
||||
module.exports = __toCommonJS(ips_exports);
|
||||
var import_ip_regex = __toESM(require("ip-regex"));
|
||||
function isIpAddress(ip) {
|
||||
return (0, import_ip_regex.default)({ exact: true }).test(ip);
|
||||
}
|
||||
function assertIpAddress(ip) {
|
||||
if (!isIpAddress(ip)) {
|
||||
throw new Error(`Invalid IP address: ${ip}`);
|
||||
}
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
assertIpAddress,
|
||||
isIpAddress
|
||||
});
|
||||
//# sourceMappingURL=ips.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/ips.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/ips.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/ips.tsx"],"sourcesContent":["import ipRegex from \"ip-regex\";\n\nexport type Ipv4Address = `${number}.${number}.${number}.${number}`;\nexport type Ipv6Address = string;\n\nexport function isIpAddress(ip: string): ip is Ipv4Address | Ipv6Address {\n return ipRegex({ exact: true }).test(ip);\n}\nundefined?.test(\"isIpAddress\", ({ expect }) => {\n // Test valid IPv4 addresses\n expect(isIpAddress(\"192.168.1.1\")).toBe(true);\n expect(isIpAddress(\"127.0.0.1\")).toBe(true);\n expect(isIpAddress(\"0.0.0.0\")).toBe(true);\n expect(isIpAddress(\"255.255.255.255\")).toBe(true);\n\n // Test valid IPv6 addresses\n expect(isIpAddress(\"::1\")).toBe(true);\n expect(isIpAddress(\"2001:db8::\")).toBe(true);\n expect(isIpAddress(\"2001:db8:85a3:8d3:1319:8a2e:370:7348\")).toBe(true);\n\n // Test invalid IP addresses\n expect(isIpAddress(\"\")).toBe(false);\n expect(isIpAddress(\"not an ip\")).toBe(false);\n expect(isIpAddress(\"256.256.256.256\")).toBe(false);\n expect(isIpAddress(\"192.168.1\")).toBe(false);\n expect(isIpAddress(\"192.168.1.1.1\")).toBe(false);\n expect(isIpAddress(\"2001:db8::xyz\")).toBe(false);\n});\n\nexport function assertIpAddress(ip: string): asserts ip is Ipv4Address | Ipv6Address {\n if (!isIpAddress(ip)) {\n throw new Error(`Invalid IP address: ${ip}`);\n }\n}\nundefined?.test(\"assertIpAddress\", ({ expect }) => {\n // Test with valid IPv4 address\n expect(() => assertIpAddress(\"192.168.1.1\")).not.toThrow();\n\n // Test with valid IPv6 address\n expect(() => assertIpAddress(\"::1\")).not.toThrow();\n\n // Test with invalid IP addresses\n expect(() => assertIpAddress(\"\")).toThrow(\"Invalid IP address: \");\n expect(() => assertIpAddress(\"not an ip\")).toThrow(\"Invalid IP address: not an ip\");\n expect(() => assertIpAddress(\"256.256.256.256\")).toThrow(\"Invalid IP address: 256.256.256.256\");\n expect(() => assertIpAddress(\"192.168.1\")).toThrow(\"Invalid IP address: 192.168.1\");\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAoB;AAKb,SAAS,YAAY,IAA6C;AACvE,aAAO,gBAAAA,SAAQ,EAAE,OAAO,KAAK,CAAC,EAAE,KAAK,EAAE;AACzC;AAsBO,SAAS,gBAAgB,IAAqD;AACnF,MAAI,CAAC,YAAY,EAAE,GAAG;AACpB,UAAM,IAAI,MAAM,uBAAuB,EAAE,EAAE;AAAA,EAC7C;AACF;","names":["ipRegex"]}
|
||||
13
package/@stackframe/stack-shared/dist/utils/json.d.mts
vendored
Normal file
13
package/@stackframe/stack-shared/dist/utils/json.d.mts
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { Result } from './results.mjs';
|
||||
|
||||
type Json = null | boolean | number | string | Json[] | {
|
||||
[key: string]: Json;
|
||||
};
|
||||
type ReadonlyJson = null | boolean | number | string | readonly ReadonlyJson[] | {
|
||||
readonly [key: string]: ReadonlyJson;
|
||||
};
|
||||
declare function isJson(value: unknown): value is Json;
|
||||
declare function parseJson(json: string): Result<Json>;
|
||||
declare function stringifyJson(json: Json): Result<string>;
|
||||
|
||||
export { type Json, type ReadonlyJson, isJson, parseJson, stringifyJson };
|
||||
13
package/@stackframe/stack-shared/dist/utils/json.d.ts
vendored
Normal file
13
package/@stackframe/stack-shared/dist/utils/json.d.ts
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { Result } from './results.js';
|
||||
|
||||
type Json = null | boolean | number | string | Json[] | {
|
||||
[key: string]: Json;
|
||||
};
|
||||
type ReadonlyJson = null | boolean | number | string | readonly ReadonlyJson[] | {
|
||||
readonly [key: string]: ReadonlyJson;
|
||||
};
|
||||
declare function isJson(value: unknown): value is Json;
|
||||
declare function parseJson(json: string): Result<Json>;
|
||||
declare function stringifyJson(json: Json): Result<string>;
|
||||
|
||||
export { type Json, type ReadonlyJson, isJson, parseJson, stringifyJson };
|
||||
58
package/@stackframe/stack-shared/dist/utils/json.js
vendored
Normal file
58
package/@stackframe/stack-shared/dist/utils/json.js
vendored
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/json.tsx
|
||||
var json_exports = {};
|
||||
__export(json_exports, {
|
||||
isJson: () => isJson,
|
||||
parseJson: () => parseJson,
|
||||
stringifyJson: () => stringifyJson
|
||||
});
|
||||
module.exports = __toCommonJS(json_exports);
|
||||
var import_results = require("./results");
|
||||
function isJson(value) {
|
||||
switch (typeof value) {
|
||||
case "object": {
|
||||
if (value === null) return true;
|
||||
if (Array.isArray(value)) return value.every(isJson);
|
||||
return Object.keys(value).every((k) => typeof k === "string") && Object.values(value).every(isJson);
|
||||
}
|
||||
case "string":
|
||||
case "number":
|
||||
case "boolean": {
|
||||
return true;
|
||||
}
|
||||
default: {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
function parseJson(json) {
|
||||
return import_results.Result.fromThrowing(() => JSON.parse(json));
|
||||
}
|
||||
function stringifyJson(json) {
|
||||
return import_results.Result.fromThrowing(() => JSON.stringify(json));
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
isJson,
|
||||
parseJson,
|
||||
stringifyJson
|
||||
});
|
||||
//# sourceMappingURL=json.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/json.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/json.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
44
package/@stackframe/stack-shared/dist/utils/jwt.d.mts
vendored
Normal file
44
package/@stackframe/stack-shared/dist/utils/jwt.d.mts
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import * as jose from 'jose';
|
||||
|
||||
declare function legacySignGlobalJWT(issuer: string, payload: any, expirationTime?: string): Promise<string>;
|
||||
declare function legacyVerifyGlobalJWT(issuer: string, jwt: string): Promise<jose.JWTPayload>;
|
||||
declare function signJWT(options: {
|
||||
issuer: string;
|
||||
audience: string;
|
||||
payload: any;
|
||||
expirationTime?: string;
|
||||
}): Promise<string>;
|
||||
declare function verifyJWT(options: {
|
||||
issuer: string;
|
||||
jwt: string;
|
||||
}): Promise<jose.JWTPayload>;
|
||||
type PrivateJwk = {
|
||||
kty: "EC";
|
||||
alg: "ES256";
|
||||
crv: "P-256";
|
||||
kid: string;
|
||||
d: string;
|
||||
x: string;
|
||||
y: string;
|
||||
};
|
||||
declare function getPrivateJwk(secret: string): Promise<PrivateJwk>;
|
||||
type PublicJwk = {
|
||||
kty: "EC";
|
||||
alg: "ES256";
|
||||
crv: "P-256";
|
||||
kid: string;
|
||||
x: string;
|
||||
y: string;
|
||||
};
|
||||
declare function getPublicJwkSet(secretOrPrivateJwk: string | PrivateJwk): Promise<{
|
||||
keys: PublicJwk[];
|
||||
}>;
|
||||
declare function getPerAudienceSecret(options: {
|
||||
audience: string;
|
||||
secret: string;
|
||||
}): string;
|
||||
declare function getKid(options: {
|
||||
secret: string;
|
||||
}): string;
|
||||
|
||||
export { type PrivateJwk, type PublicJwk, getKid, getPerAudienceSecret, getPrivateJwk, getPublicJwkSet, legacySignGlobalJWT, legacyVerifyGlobalJWT, signJWT, verifyJWT };
|
||||
44
package/@stackframe/stack-shared/dist/utils/jwt.d.ts
vendored
Normal file
44
package/@stackframe/stack-shared/dist/utils/jwt.d.ts
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import * as jose from 'jose';
|
||||
|
||||
declare function legacySignGlobalJWT(issuer: string, payload: any, expirationTime?: string): Promise<string>;
|
||||
declare function legacyVerifyGlobalJWT(issuer: string, jwt: string): Promise<jose.JWTPayload>;
|
||||
declare function signJWT(options: {
|
||||
issuer: string;
|
||||
audience: string;
|
||||
payload: any;
|
||||
expirationTime?: string;
|
||||
}): Promise<string>;
|
||||
declare function verifyJWT(options: {
|
||||
issuer: string;
|
||||
jwt: string;
|
||||
}): Promise<jose.JWTPayload>;
|
||||
type PrivateJwk = {
|
||||
kty: "EC";
|
||||
alg: "ES256";
|
||||
crv: "P-256";
|
||||
kid: string;
|
||||
d: string;
|
||||
x: string;
|
||||
y: string;
|
||||
};
|
||||
declare function getPrivateJwk(secret: string): Promise<PrivateJwk>;
|
||||
type PublicJwk = {
|
||||
kty: "EC";
|
||||
alg: "ES256";
|
||||
crv: "P-256";
|
||||
kid: string;
|
||||
x: string;
|
||||
y: string;
|
||||
};
|
||||
declare function getPublicJwkSet(secretOrPrivateJwk: string | PrivateJwk): Promise<{
|
||||
keys: PublicJwk[];
|
||||
}>;
|
||||
declare function getPerAudienceSecret(options: {
|
||||
audience: string;
|
||||
secret: string;
|
||||
}): string;
|
||||
declare function getKid(options: {
|
||||
secret: string;
|
||||
}): string;
|
||||
|
||||
export { type PrivateJwk, type PublicJwk, getKid, getPerAudienceSecret, getPrivateJwk, getPublicJwkSet, legacySignGlobalJWT, legacyVerifyGlobalJWT, signJWT, verifyJWT };
|
||||
129
package/@stackframe/stack-shared/dist/utils/jwt.js
vendored
Normal file
129
package/@stackframe/stack-shared/dist/utils/jwt.js
vendored
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
"use strict";
|
||||
var __create = Object.create;
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __getProtoOf = Object.getPrototypeOf;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||
// If the importer is in node compatibility mode or this is not an ESM
|
||||
// file that has been converted to a CommonJS file using a Babel-
|
||||
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||
mod
|
||||
));
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/jwt.tsx
|
||||
var jwt_exports = {};
|
||||
__export(jwt_exports, {
|
||||
getKid: () => getKid,
|
||||
getPerAudienceSecret: () => getPerAudienceSecret,
|
||||
getPrivateJwk: () => getPrivateJwk,
|
||||
getPublicJwkSet: () => getPublicJwkSet,
|
||||
legacySignGlobalJWT: () => legacySignGlobalJWT,
|
||||
legacyVerifyGlobalJWT: () => legacyVerifyGlobalJWT,
|
||||
signJWT: () => signJWT,
|
||||
verifyJWT: () => verifyJWT
|
||||
});
|
||||
module.exports = __toCommonJS(jwt_exports);
|
||||
var import_crypto = __toESM(require("crypto"));
|
||||
var import_elliptic = __toESM(require("elliptic"));
|
||||
var jose = __toESM(require("jose"));
|
||||
var import_errors = require("jose/errors");
|
||||
var import_bytes = require("./bytes");
|
||||
var import_errors2 = require("./errors");
|
||||
var import_globals = require("./globals");
|
||||
var import_objects = require("./objects");
|
||||
var STACK_SERVER_SECRET = process.env.STACK_SERVER_SECRET ?? "";
|
||||
try {
|
||||
jose.base64url.decode(STACK_SERVER_SECRET);
|
||||
} catch (e) {
|
||||
throw new Error("STACK_SERVER_SECRET is not valid. Please use the generateKeys script to generate a new secret.");
|
||||
}
|
||||
async function legacySignGlobalJWT(issuer, payload, expirationTime = "5m") {
|
||||
const privateJwk = await jose.importJWK(await getPrivateJwk(STACK_SERVER_SECRET));
|
||||
return await new jose.SignJWT(payload).setProtectedHeader({ alg: "ES256" }).setIssuer(issuer).setIssuedAt().setExpirationTime(expirationTime).sign(privateJwk);
|
||||
}
|
||||
async function legacyVerifyGlobalJWT(issuer, jwt) {
|
||||
const jwkSet = jose.createLocalJWKSet(await getPublicJwkSet(STACK_SERVER_SECRET));
|
||||
const verified = await jose.jwtVerify(jwt, jwkSet, { issuer });
|
||||
return verified.payload;
|
||||
}
|
||||
async function signJWT(options) {
|
||||
const secret = getPerAudienceSecret({ audience: options.audience, secret: STACK_SERVER_SECRET });
|
||||
const kid = getKid({ secret });
|
||||
const privateJwk = await jose.importJWK(await getPrivateJwk(secret));
|
||||
return await new jose.SignJWT(options.payload).setProtectedHeader({ alg: "ES256", kid }).setIssuer(options.issuer).setIssuedAt().setAudience(options.audience).setExpirationTime(options.expirationTime || "5m").sign(privateJwk);
|
||||
}
|
||||
async function verifyJWT(options) {
|
||||
const audience = jose.decodeJwt(options.jwt).aud;
|
||||
if (!audience || typeof audience !== "string") {
|
||||
throw new import_errors.JOSEError("Invalid JWT audience");
|
||||
}
|
||||
const secret = getPerAudienceSecret({ audience, secret: STACK_SERVER_SECRET });
|
||||
const jwkSet = jose.createLocalJWKSet(await getPublicJwkSet(secret));
|
||||
const verified = await jose.jwtVerify(options.jwt, jwkSet, { issuer: options.issuer });
|
||||
return verified.payload;
|
||||
}
|
||||
async function getPrivateJwk(secret) {
|
||||
const secretHash = await import_globals.globalVar.crypto.subtle.digest("SHA-256", jose.base64url.decode(secret));
|
||||
const priv = new Uint8Array(secretHash);
|
||||
const ec = new import_elliptic.default.ec("p256");
|
||||
const key = ec.keyFromPrivate(priv);
|
||||
const publicKey = key.getPublic();
|
||||
return {
|
||||
kty: "EC",
|
||||
crv: "P-256",
|
||||
alg: "ES256",
|
||||
kid: getKid({ secret }),
|
||||
d: (0, import_bytes.encodeBase64Url)(priv),
|
||||
x: (0, import_bytes.encodeBase64Url)(publicKey.getX().toBuffer()),
|
||||
y: (0, import_bytes.encodeBase64Url)(publicKey.getY().toBuffer())
|
||||
};
|
||||
}
|
||||
async function getPublicJwkSet(secretOrPrivateJwk) {
|
||||
const privateJwk = typeof secretOrPrivateJwk === "string" ? await getPrivateJwk(secretOrPrivateJwk) : secretOrPrivateJwk;
|
||||
const jwk = (0, import_objects.pick)(privateJwk, ["kty", "alg", "crv", "x", "y", "kid"]);
|
||||
return {
|
||||
keys: [jwk]
|
||||
};
|
||||
}
|
||||
function getPerAudienceSecret(options) {
|
||||
if (options.audience === "kid") {
|
||||
throw new import_errors2.StackAssertionError("You cannot use the 'kid' audience for a per-audience secret, see comment below in jwt.tsx");
|
||||
}
|
||||
return jose.base64url.encode(
|
||||
import_crypto.default.createHash("sha256").update(JSON.stringify([options.secret, options.audience])).digest()
|
||||
);
|
||||
}
|
||||
function getKid(options) {
|
||||
return jose.base64url.encode(
|
||||
import_crypto.default.createHash("sha256").update(JSON.stringify([options.secret, "kid"])).digest()
|
||||
).slice(0, 12);
|
||||
}
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
getKid,
|
||||
getPerAudienceSecret,
|
||||
getPrivateJwk,
|
||||
getPublicJwkSet,
|
||||
legacySignGlobalJWT,
|
||||
legacyVerifyGlobalJWT,
|
||||
signJWT,
|
||||
verifyJWT
|
||||
});
|
||||
//# sourceMappingURL=jwt.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/jwt.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/jwt.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
15
package/@stackframe/stack-shared/dist/utils/locks.d.mts
vendored
Normal file
15
package/@stackframe/stack-shared/dist/utils/locks.d.mts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
type LockCallback<T> = () => Promise<T>;
|
||||
declare class ReadWriteLock {
|
||||
private semaphore;
|
||||
private readers;
|
||||
private readersMutex;
|
||||
constructor();
|
||||
withReadLock<T>(callback: LockCallback<T>): Promise<T>;
|
||||
withWriteLock<T>(callback: LockCallback<T>): Promise<T>;
|
||||
private _acquireReadLock;
|
||||
private _releaseReadLock;
|
||||
private _acquireWriteLock;
|
||||
private _releaseWriteLock;
|
||||
}
|
||||
|
||||
export { ReadWriteLock };
|
||||
15
package/@stackframe/stack-shared/dist/utils/locks.d.ts
vendored
Normal file
15
package/@stackframe/stack-shared/dist/utils/locks.d.ts
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
type LockCallback<T> = () => Promise<T>;
|
||||
declare class ReadWriteLock {
|
||||
private semaphore;
|
||||
private readers;
|
||||
private readersMutex;
|
||||
constructor();
|
||||
withReadLock<T>(callback: LockCallback<T>): Promise<T>;
|
||||
withWriteLock<T>(callback: LockCallback<T>): Promise<T>;
|
||||
private _acquireReadLock;
|
||||
private _releaseReadLock;
|
||||
private _acquireWriteLock;
|
||||
private _releaseWriteLock;
|
||||
}
|
||||
|
||||
export { ReadWriteLock };
|
||||
82
package/@stackframe/stack-shared/dist/utils/locks.js
vendored
Normal file
82
package/@stackframe/stack-shared/dist/utils/locks.js
vendored
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/locks.tsx
|
||||
var locks_exports = {};
|
||||
__export(locks_exports, {
|
||||
ReadWriteLock: () => ReadWriteLock
|
||||
});
|
||||
module.exports = __toCommonJS(locks_exports);
|
||||
var import_async_mutex = require("async-mutex");
|
||||
var ReadWriteLock = class {
|
||||
constructor() {
|
||||
this.semaphore = new import_async_mutex.Semaphore(1);
|
||||
this.readers = 0;
|
||||
this.readersMutex = new import_async_mutex.Semaphore(1);
|
||||
}
|
||||
async withReadLock(callback) {
|
||||
await this._acquireReadLock();
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
await this._releaseReadLock();
|
||||
}
|
||||
}
|
||||
async withWriteLock(callback) {
|
||||
await this._acquireWriteLock();
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
await this._releaseWriteLock();
|
||||
}
|
||||
}
|
||||
async _acquireReadLock() {
|
||||
await this.readersMutex.acquire();
|
||||
try {
|
||||
this.readers += 1;
|
||||
if (this.readers === 1) {
|
||||
await this.semaphore.acquire();
|
||||
}
|
||||
} finally {
|
||||
this.readersMutex.release();
|
||||
}
|
||||
}
|
||||
async _releaseReadLock() {
|
||||
await this.readersMutex.acquire();
|
||||
try {
|
||||
this.readers -= 1;
|
||||
if (this.readers === 0) {
|
||||
this.semaphore.release();
|
||||
}
|
||||
} finally {
|
||||
this.readersMutex.release();
|
||||
}
|
||||
}
|
||||
async _acquireWriteLock() {
|
||||
await this.semaphore.acquire();
|
||||
}
|
||||
async _releaseWriteLock() {
|
||||
this.semaphore.release();
|
||||
}
|
||||
};
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
ReadWriteLock
|
||||
});
|
||||
//# sourceMappingURL=locks.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/locks.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/locks.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"sources":["../../src/utils/locks.tsx"],"sourcesContent":["import { Semaphore } from 'async-mutex';\n\ntype LockCallback<T> = () => Promise<T>;\n\nexport class ReadWriteLock {\n private semaphore: Semaphore;\n private readers: number;\n private readersMutex: Semaphore;\n\n constructor() {\n this.semaphore = new Semaphore(1); // Semaphore with 1 permit\n this.readers = 0; // Track the number of readers\n this.readersMutex = new Semaphore(1); // Protect access to `readers` count\n }\n\n async withReadLock<T>(callback: LockCallback<T>): Promise<T> {\n await this._acquireReadLock();\n try {\n return await callback();\n } finally {\n await this._releaseReadLock();\n }\n }\n\n async withWriteLock<T>(callback: LockCallback<T>): Promise<T> {\n await this._acquireWriteLock();\n try {\n return await callback();\n } finally {\n await this._releaseWriteLock();\n }\n }\n\n private async _acquireReadLock(): Promise<void> {\n // Increment the readers count\n await this.readersMutex.acquire();\n try {\n this.readers += 1;\n // If this is the first reader, block writers\n if (this.readers === 1) {\n await this.semaphore.acquire();\n }\n } finally {\n this.readersMutex.release();\n }\n }\n\n private async _releaseReadLock(): Promise<void> {\n // Decrement the readers count\n await this.readersMutex.acquire();\n try {\n this.readers -= 1;\n // If this was the last reader, release the writer block\n if (this.readers === 0) {\n this.semaphore.release();\n }\n } finally {\n this.readersMutex.release();\n }\n }\n\n private async _acquireWriteLock(): Promise<void> {\n // Writers acquire the main semaphore exclusively\n await this.semaphore.acquire();\n }\n\n private async _releaseWriteLock(): Promise<void> {\n // Writers release the main semaphore\n this.semaphore.release();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA0B;AAInB,IAAM,gBAAN,MAAoB;AAAA,EAKzB,cAAc;AACZ,SAAK,YAAY,IAAI,6BAAU,CAAC;AAChC,SAAK,UAAU;AACf,SAAK,eAAe,IAAI,6BAAU,CAAC;AAAA,EACrC;AAAA,EAEA,MAAM,aAAgB,UAAuC;AAC3D,UAAM,KAAK,iBAAiB;AAC5B,QAAI;AACF,aAAO,MAAM,SAAS;AAAA,IACxB,UAAE;AACA,YAAM,KAAK,iBAAiB;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,cAAiB,UAAuC;AAC5D,UAAM,KAAK,kBAAkB;AAC7B,QAAI;AACF,aAAO,MAAM,SAAS;AAAA,IACxB,UAAE;AACA,YAAM,KAAK,kBAAkB;AAAA,IAC/B;AAAA,EACF;AAAA,EAEA,MAAc,mBAAkC;AAE9C,UAAM,KAAK,aAAa,QAAQ;AAChC,QAAI;AACF,WAAK,WAAW;AAEhB,UAAI,KAAK,YAAY,GAAG;AACtB,cAAM,KAAK,UAAU,QAAQ;AAAA,MAC/B;AAAA,IACF,UAAE;AACA,WAAK,aAAa,QAAQ;AAAA,IAC5B;AAAA,EACF;AAAA,EAEA,MAAc,mBAAkC;AAE9C,UAAM,KAAK,aAAa,QAAQ;AAChC,QAAI;AACF,WAAK,WAAW;AAEhB,UAAI,KAAK,YAAY,GAAG;AACtB,aAAK,UAAU,QAAQ;AAAA,MACzB;AAAA,IACF,UAAE;AACA,WAAK,aAAa,QAAQ;AAAA,IAC5B;AAAA,EACF;AAAA,EAEA,MAAc,oBAAmC;AAE/C,UAAM,KAAK,UAAU,QAAQ;AAAA,EAC/B;AAAA,EAEA,MAAc,oBAAmC;AAE/C,SAAK,UAAU,QAAQ;AAAA,EACzB;AACF;","names":[]}
|
||||
59
package/@stackframe/stack-shared/dist/utils/maps.d.mts
vendored
Normal file
59
package/@stackframe/stack-shared/dist/utils/maps.d.mts
vendored
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
declare class WeakRefIfAvailable<T extends object> {
|
||||
private readonly _ref;
|
||||
constructor(value: T);
|
||||
deref(): T | undefined;
|
||||
}
|
||||
/**
|
||||
* A WeakMap-like object that can be iterated over.
|
||||
*
|
||||
* Note that it relies on WeakRef, and always falls back to the regular Map behavior (ie. no GC) in browsers that don't support it.
|
||||
*/
|
||||
declare class IterableWeakMap<K extends object, V> {
|
||||
private readonly _weakMap;
|
||||
private readonly _keyRefs;
|
||||
constructor(entries?: readonly (readonly [K, V])[] | null);
|
||||
get(key: K): V | undefined;
|
||||
set(key: K, value: V): this;
|
||||
delete(key: K): boolean;
|
||||
has(key: K): boolean;
|
||||
[Symbol.iterator](): IterableIterator<[K, V]>;
|
||||
[Symbol.toStringTag]: string;
|
||||
}
|
||||
/**
|
||||
* A map that is a IterableWeakMap for object keys and a regular Map for primitive keys. Also provides iteration over both
|
||||
* object and primitive keys.
|
||||
*
|
||||
* Note that, just like IterableWeakMap, older browsers without support for WeakRef will use a regular Map for object keys.
|
||||
*/
|
||||
declare class MaybeWeakMap<K, V> {
|
||||
private readonly _primitiveMap;
|
||||
private readonly _weakMap;
|
||||
constructor(entries?: readonly (readonly [K, V])[] | null);
|
||||
private _isAllowedInWeakMap;
|
||||
get(key: K): V | undefined;
|
||||
set(key: K, value: V): this;
|
||||
delete(key: K): boolean;
|
||||
has(key: K): boolean;
|
||||
[Symbol.iterator](): IterableIterator<[K, V]>;
|
||||
[Symbol.toStringTag]: string;
|
||||
}
|
||||
/**
|
||||
* A map that stores values indexed by an array of keys. If the keys are objects and the environment supports WeakRefs,
|
||||
* they are stored in a WeakMap.
|
||||
*/
|
||||
declare class DependenciesMap<K extends any[], V> {
|
||||
private _inner;
|
||||
private _valueToResult;
|
||||
private _unwrapFromInner;
|
||||
private _setInInner;
|
||||
private _iterateInner;
|
||||
get(dependencies: K): V | undefined;
|
||||
set(dependencies: K, value: V): this;
|
||||
delete(dependencies: K): boolean;
|
||||
has(dependencies: K): boolean;
|
||||
clear(): void;
|
||||
[Symbol.iterator](): IterableIterator<[K, V]>;
|
||||
[Symbol.toStringTag]: string;
|
||||
}
|
||||
|
||||
export { DependenciesMap, IterableWeakMap, MaybeWeakMap, WeakRefIfAvailable };
|
||||
59
package/@stackframe/stack-shared/dist/utils/maps.d.ts
vendored
Normal file
59
package/@stackframe/stack-shared/dist/utils/maps.d.ts
vendored
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
declare class WeakRefIfAvailable<T extends object> {
|
||||
private readonly _ref;
|
||||
constructor(value: T);
|
||||
deref(): T | undefined;
|
||||
}
|
||||
/**
|
||||
* A WeakMap-like object that can be iterated over.
|
||||
*
|
||||
* Note that it relies on WeakRef, and always falls back to the regular Map behavior (ie. no GC) in browsers that don't support it.
|
||||
*/
|
||||
declare class IterableWeakMap<K extends object, V> {
|
||||
private readonly _weakMap;
|
||||
private readonly _keyRefs;
|
||||
constructor(entries?: readonly (readonly [K, V])[] | null);
|
||||
get(key: K): V | undefined;
|
||||
set(key: K, value: V): this;
|
||||
delete(key: K): boolean;
|
||||
has(key: K): boolean;
|
||||
[Symbol.iterator](): IterableIterator<[K, V]>;
|
||||
[Symbol.toStringTag]: string;
|
||||
}
|
||||
/**
|
||||
* A map that is a IterableWeakMap for object keys and a regular Map for primitive keys. Also provides iteration over both
|
||||
* object and primitive keys.
|
||||
*
|
||||
* Note that, just like IterableWeakMap, older browsers without support for WeakRef will use a regular Map for object keys.
|
||||
*/
|
||||
declare class MaybeWeakMap<K, V> {
|
||||
private readonly _primitiveMap;
|
||||
private readonly _weakMap;
|
||||
constructor(entries?: readonly (readonly [K, V])[] | null);
|
||||
private _isAllowedInWeakMap;
|
||||
get(key: K): V | undefined;
|
||||
set(key: K, value: V): this;
|
||||
delete(key: K): boolean;
|
||||
has(key: K): boolean;
|
||||
[Symbol.iterator](): IterableIterator<[K, V]>;
|
||||
[Symbol.toStringTag]: string;
|
||||
}
|
||||
/**
|
||||
* A map that stores values indexed by an array of keys. If the keys are objects and the environment supports WeakRefs,
|
||||
* they are stored in a WeakMap.
|
||||
*/
|
||||
declare class DependenciesMap<K extends any[], V> {
|
||||
private _inner;
|
||||
private _valueToResult;
|
||||
private _unwrapFromInner;
|
||||
private _setInInner;
|
||||
private _iterateInner;
|
||||
get(dependencies: K): V | undefined;
|
||||
set(dependencies: K, value: V): this;
|
||||
delete(dependencies: K): boolean;
|
||||
has(dependencies: K): boolean;
|
||||
clear(): void;
|
||||
[Symbol.iterator](): IterableIterator<[K, V]>;
|
||||
[Symbol.toStringTag]: string;
|
||||
}
|
||||
|
||||
export { DependenciesMap, IterableWeakMap, MaybeWeakMap, WeakRefIfAvailable };
|
||||
209
package/@stackframe/stack-shared/dist/utils/maps.js
vendored
Normal file
209
package/@stackframe/stack-shared/dist/utils/maps.js
vendored
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/utils/maps.tsx
|
||||
var maps_exports = {};
|
||||
__export(maps_exports, {
|
||||
DependenciesMap: () => DependenciesMap,
|
||||
IterableWeakMap: () => IterableWeakMap,
|
||||
MaybeWeakMap: () => MaybeWeakMap,
|
||||
WeakRefIfAvailable: () => WeakRefIfAvailable
|
||||
});
|
||||
module.exports = __toCommonJS(maps_exports);
|
||||
var import_results = require("./results");
|
||||
var WeakRefIfAvailable = class {
|
||||
constructor(value) {
|
||||
if (typeof WeakRef === "undefined") {
|
||||
this._ref = { deref: () => value };
|
||||
} else {
|
||||
this._ref = new WeakRef(value);
|
||||
}
|
||||
}
|
||||
deref() {
|
||||
return this._ref.deref();
|
||||
}
|
||||
};
|
||||
var _a, _b;
|
||||
var IterableWeakMap = class {
|
||||
constructor(entries) {
|
||||
this[_a] = "IterableWeakMap";
|
||||
const mappedEntries = entries?.map((e) => [e[0], { value: e[1], keyRef: new WeakRefIfAvailable(e[0]) }]);
|
||||
this._weakMap = new WeakMap(mappedEntries ?? []);
|
||||
this._keyRefs = new Set(mappedEntries?.map((e) => e[1].keyRef) ?? []);
|
||||
}
|
||||
get(key) {
|
||||
return this._weakMap.get(key)?.value;
|
||||
}
|
||||
set(key, value) {
|
||||
const existing = this._weakMap.get(key);
|
||||
const updated = { value, keyRef: existing?.keyRef ?? new WeakRefIfAvailable(key) };
|
||||
this._weakMap.set(key, updated);
|
||||
this._keyRefs.add(updated.keyRef);
|
||||
return this;
|
||||
}
|
||||
delete(key) {
|
||||
const res = this._weakMap.get(key);
|
||||
if (res) {
|
||||
this._weakMap.delete(key);
|
||||
this._keyRefs.delete(res.keyRef);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
has(key) {
|
||||
return this._weakMap.has(key) && this._keyRefs.has(this._weakMap.get(key).keyRef);
|
||||
}
|
||||
*[(_b = Symbol.iterator, _a = Symbol.toStringTag, _b)]() {
|
||||
for (const keyRef of this._keyRefs) {
|
||||
const key = keyRef.deref();
|
||||
const existing = key ? this._weakMap.get(key) : void 0;
|
||||
if (!key) {
|
||||
this._keyRefs.delete(keyRef);
|
||||
} else if (existing) {
|
||||
yield [key, existing.value];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var _a2, _b2;
|
||||
var MaybeWeakMap = class {
|
||||
constructor(entries) {
|
||||
this[_a2] = "MaybeWeakMap";
|
||||
const entriesArray = [...entries ?? []];
|
||||
this._primitiveMap = new Map(entriesArray.filter((e) => !this._isAllowedInWeakMap(e[0])));
|
||||
this._weakMap = new IterableWeakMap(entriesArray.filter((e) => this._isAllowedInWeakMap(e[0])));
|
||||
}
|
||||
_isAllowedInWeakMap(key) {
|
||||
return typeof key === "object" && key !== null || typeof key === "symbol" && Symbol.keyFor(key) === void 0;
|
||||
}
|
||||
get(key) {
|
||||
if (this._isAllowedInWeakMap(key)) {
|
||||
return this._weakMap.get(key);
|
||||
} else {
|
||||
return this._primitiveMap.get(key);
|
||||
}
|
||||
}
|
||||
set(key, value) {
|
||||
if (this._isAllowedInWeakMap(key)) {
|
||||
this._weakMap.set(key, value);
|
||||
} else {
|
||||
this._primitiveMap.set(key, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
delete(key) {
|
||||
if (this._isAllowedInWeakMap(key)) {
|
||||
return this._weakMap.delete(key);
|
||||
} else {
|
||||
return this._primitiveMap.delete(key);
|
||||
}
|
||||
}
|
||||
has(key) {
|
||||
if (this._isAllowedInWeakMap(key)) {
|
||||
return this._weakMap.has(key);
|
||||
} else {
|
||||
return this._primitiveMap.has(key);
|
||||
}
|
||||
}
|
||||
*[(_b2 = Symbol.iterator, _a2 = Symbol.toStringTag, _b2)]() {
|
||||
yield* this._primitiveMap;
|
||||
yield* this._weakMap;
|
||||
}
|
||||
};
|
||||
var _a3, _b3;
|
||||
var DependenciesMap = class {
|
||||
constructor() {
|
||||
this._inner = { map: new MaybeWeakMap(), hasValue: false, value: void 0 };
|
||||
this[_a3] = "DependenciesMap";
|
||||
}
|
||||
_valueToResult(inner) {
|
||||
if (inner.hasValue) {
|
||||
return import_results.Result.ok(inner.value);
|
||||
} else {
|
||||
return import_results.Result.error(void 0);
|
||||
}
|
||||
}
|
||||
_unwrapFromInner(dependencies, inner) {
|
||||
if (dependencies.length === 0) {
|
||||
return this._valueToResult(inner);
|
||||
} else {
|
||||
const [key, ...rest] = dependencies;
|
||||
const newInner = inner.map.get(key);
|
||||
if (!newInner) {
|
||||
return import_results.Result.error(void 0);
|
||||
}
|
||||
return this._unwrapFromInner(rest, newInner);
|
||||
}
|
||||
}
|
||||
_setInInner(dependencies, value, inner) {
|
||||
if (dependencies.length === 0) {
|
||||
const res = this._valueToResult(inner);
|
||||
if (value.status === "ok") {
|
||||
inner.hasValue = true;
|
||||
inner.value = value.data;
|
||||
} else {
|
||||
inner.hasValue = false;
|
||||
inner.value = void 0;
|
||||
}
|
||||
return res;
|
||||
} else {
|
||||
const [key, ...rest] = dependencies;
|
||||
let newInner = inner.map.get(key);
|
||||
if (!newInner) {
|
||||
inner.map.set(key, newInner = { map: new MaybeWeakMap(), hasValue: false, value: void 0 });
|
||||
}
|
||||
return this._setInInner(rest, value, newInner);
|
||||
}
|
||||
}
|
||||
*_iterateInner(dependencies, inner) {
|
||||
if (inner.hasValue) {
|
||||
yield [dependencies, inner.value];
|
||||
}
|
||||
for (const [key, value] of inner.map) {
|
||||
yield* this._iterateInner([...dependencies, key], value);
|
||||
}
|
||||
}
|
||||
get(dependencies) {
|
||||
return import_results.Result.or(this._unwrapFromInner(dependencies, this._inner), void 0);
|
||||
}
|
||||
set(dependencies, value) {
|
||||
this._setInInner(dependencies, import_results.Result.ok(value), this._inner);
|
||||
return this;
|
||||
}
|
||||
delete(dependencies) {
|
||||
return this._setInInner(dependencies, import_results.Result.error(void 0), this._inner).status === "ok";
|
||||
}
|
||||
has(dependencies) {
|
||||
return this._unwrapFromInner(dependencies, this._inner).status === "ok";
|
||||
}
|
||||
clear() {
|
||||
this._inner = { map: new MaybeWeakMap(), hasValue: false, value: void 0 };
|
||||
}
|
||||
*[(_b3 = Symbol.iterator, _a3 = Symbol.toStringTag, _b3)]() {
|
||||
yield* this._iterateInner([], this._inner);
|
||||
}
|
||||
};
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
0 && (module.exports = {
|
||||
DependenciesMap,
|
||||
IterableWeakMap,
|
||||
MaybeWeakMap,
|
||||
WeakRefIfAvailable
|
||||
});
|
||||
//# sourceMappingURL=maps.js.map
|
||||
1
package/@stackframe/stack-shared/dist/utils/maps.js.map
vendored
Normal file
1
package/@stackframe/stack-shared/dist/utils/maps.js.map
vendored
Normal file
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue