@hexclave/shared 1.0.3 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/unified-prompts/reminders.js +4 -3
- package/dist/ai/unified-prompts/reminders.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts +3 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js +216 -29
- package/dist/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.js +1 -0
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-index.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts +18 -6
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js +23 -8
- package/dist/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js.map +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js +1 -1
- package/dist/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js.map +1 -1
- package/dist/config/schema.d.ts +1 -1
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +5 -5
- package/dist/config/schema.js.map +1 -1
- package/dist/config-authoring.d.ts +4 -4
- package/dist/config-authoring.d.ts.map +1 -1
- package/dist/config-authoring.js +2 -2
- package/dist/config-authoring.js.map +1 -1
- package/dist/config-rendering.d.ts +4 -4
- package/dist/config-rendering.d.ts.map +1 -1
- package/dist/config-rendering.js +19 -18
- package/dist/config-rendering.js.map +1 -1
- package/dist/esm/ai/unified-prompts/reminders.js +4 -3
- package/dist/esm/ai/unified-prompts/reminders.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts +3 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js +215 -30
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.d.ts.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.js +1 -0
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-index.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.d.ts +18 -6
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js +23 -8
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.js.map +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js +1 -1
- package/dist/esm/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.js.map +1 -1
- package/dist/esm/config/schema.d.ts +1 -1
- package/dist/esm/config/schema.d.ts.map +1 -1
- package/dist/esm/config/schema.js +5 -5
- package/dist/esm/config/schema.js.map +1 -1
- package/dist/esm/config-authoring.d.ts +4 -4
- package/dist/esm/config-authoring.d.ts.map +1 -1
- package/dist/esm/config-authoring.js +2 -2
- package/dist/esm/config-authoring.js.map +1 -1
- package/dist/esm/config-rendering.d.ts +4 -4
- package/dist/esm/config-rendering.d.ts.map +1 -1
- package/dist/esm/config-rendering.js +15 -14
- package/dist/esm/config-rendering.js.map +1 -1
- package/dist/esm/helpers/vault/client-side.d.ts.map +1 -1
- package/dist/esm/helpers/vault/client-side.js.map +1 -1
- package/dist/esm/helpers/vault/server-side.d.ts.map +1 -1
- package/dist/esm/helpers/vault/server-side.js.map +1 -1
- package/dist/esm/hexclave-config-file.d.ts +15 -0
- package/dist/esm/hexclave-config-file.d.ts.map +1 -0
- package/dist/esm/{stack-config-file.js → hexclave-config-file.js} +7 -7
- package/dist/esm/hexclave-config-file.js.map +1 -0
- package/dist/esm/interface/admin-metrics.d.ts +2 -2
- package/dist/esm/interface/admin-metrics.js.map +1 -1
- package/dist/esm/interface/client-interface.js +2 -2
- package/dist/esm/interface/client-interface.js.map +1 -1
- package/dist/esm/interface/conversations.d.ts +32 -32
- package/dist/esm/interface/crud/current-user.d.ts +7 -7
- package/dist/esm/interface/crud/email-outbox.d.ts +42 -42
- package/dist/esm/interface/crud/project-permissions.js +5 -5
- package/dist/esm/interface/crud/project-permissions.js.map +1 -1
- package/dist/esm/interface/crud/team-member-profiles.d.ts +18 -18
- package/dist/esm/interface/crud/team-permissions.js +5 -5
- package/dist/esm/interface/crud/team-permissions.js.map +1 -1
- package/dist/esm/interface/crud/users.d.ts +10 -10
- package/dist/esm/interface/page-component-versions.js +107 -107
- package/dist/esm/interface/page-component-versions.js.map +1 -1
- package/dist/esm/interface/webhooks.d.ts +2 -2
- package/dist/esm/known-errors.d.ts +1 -1
- package/dist/esm/known-errors.d.ts.map +1 -1
- package/dist/esm/known-errors.js +9 -5
- package/dist/esm/known-errors.js.map +1 -1
- package/dist/esm/schema-fields.d.ts +15 -5
- package/dist/esm/schema-fields.d.ts.map +1 -1
- package/dist/esm/schema-fields.js +26 -16
- package/dist/esm/schema-fields.js.map +1 -1
- package/dist/esm/utils/crypto.d.ts.map +1 -1
- package/dist/esm/utils/crypto.js.map +1 -1
- package/dist/esm/utils/currency-constants.d.ts +6 -0
- package/dist/esm/utils/currency-constants.d.ts.map +1 -1
- package/dist/esm/utils/currency-constants.js.map +1 -1
- package/dist/esm/utils/dev-env-state-path.d.ts +3 -3
- package/dist/esm/utils/dev-env-state-path.d.ts.map +1 -1
- package/dist/esm/utils/dev-env-state-path.js +4 -4
- package/dist/esm/utils/dev-env-state-path.js.map +1 -1
- package/dist/esm/utils/errors.js +2 -2
- package/dist/esm/utils/errors.js.map +1 -1
- package/dist/esm/utils/esbuild.d.ts.map +1 -1
- package/dist/esm/utils/esbuild.js +0 -1
- package/dist/esm/utils/esbuild.js.map +1 -1
- package/dist/esm/utils/featurebase.d.ts +3 -3
- package/dist/esm/utils/featurebase.d.ts.map +1 -1
- package/dist/esm/utils/featurebase.js +15 -15
- package/dist/esm/utils/featurebase.js.map +1 -1
- package/dist/esm/utils/fs.js +6 -6
- package/dist/esm/utils/fs.js.map +1 -1
- package/dist/esm/utils/globals.d.ts.map +1 -1
- package/dist/esm/utils/globals.js +10 -10
- package/dist/esm/utils/globals.js.map +1 -1
- package/dist/esm/utils/jwt.d.ts.map +1 -1
- package/dist/esm/utils/jwt.js +3 -3
- package/dist/esm/utils/jwt.js.map +1 -1
- package/dist/esm/utils/redirect-urls.d.ts +3 -3
- package/dist/esm/utils/redirect-urls.d.ts.map +1 -1
- package/dist/esm/utils/redirect-urls.js +5 -5
- package/dist/esm/utils/redirect-urls.js.map +1 -1
- package/dist/esm/utils/urls.js.map +1 -1
- package/dist/helpers/vault/client-side.d.ts.map +1 -1
- package/dist/helpers/vault/client-side.js.map +1 -1
- package/dist/helpers/vault/server-side.d.ts.map +1 -1
- package/dist/helpers/vault/server-side.js.map +1 -1
- package/dist/hexclave-config-file.d.ts +15 -0
- package/dist/hexclave-config-file.d.ts.map +1 -0
- package/dist/{stack-config-file.js → hexclave-config-file.js} +8 -8
- package/dist/hexclave-config-file.js.map +1 -0
- package/dist/interface/admin-metrics.d.ts +12 -12
- package/dist/interface/admin-metrics.js.map +1 -1
- package/dist/interface/client-interface.js +2 -2
- package/dist/interface/client-interface.js.map +1 -1
- package/dist/interface/conversations.d.ts +32 -32
- package/dist/interface/crud/current-user.d.ts +7 -7
- package/dist/interface/crud/email-outbox.d.ts +42 -42
- package/dist/interface/crud/project-permissions.js +5 -5
- package/dist/interface/crud/project-permissions.js.map +1 -1
- package/dist/interface/crud/team-member-profiles.d.ts +18 -18
- package/dist/interface/crud/team-permissions.js +5 -5
- package/dist/interface/crud/team-permissions.js.map +1 -1
- package/dist/interface/crud/users.d.ts +10 -10
- package/dist/interface/page-component-versions.js +107 -107
- package/dist/interface/page-component-versions.js.map +1 -1
- package/dist/interface/webhooks.d.ts +2 -2
- package/dist/known-errors.d.ts +1 -1
- package/dist/known-errors.d.ts.map +1 -1
- package/dist/known-errors.js +9 -5
- package/dist/known-errors.js.map +1 -1
- package/dist/schema-fields.d.ts +15 -5
- package/dist/schema-fields.d.ts.map +1 -1
- package/dist/schema-fields.js +26 -16
- package/dist/schema-fields.js.map +1 -1
- package/dist/utils/crypto.d.ts.map +1 -1
- package/dist/utils/crypto.js.map +1 -1
- package/dist/utils/currency-constants.d.ts +6 -0
- package/dist/utils/currency-constants.d.ts.map +1 -1
- package/dist/utils/currency-constants.js.map +1 -1
- package/dist/utils/dev-env-state-path.d.ts +3 -3
- package/dist/utils/dev-env-state-path.d.ts.map +1 -1
- package/dist/utils/dev-env-state-path.js +5 -5
- package/dist/utils/dev-env-state-path.js.map +1 -1
- package/dist/utils/errors.js +2 -2
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/esbuild.d.ts.map +1 -1
- package/dist/utils/esbuild.js +0 -1
- package/dist/utils/esbuild.js.map +1 -1
- package/dist/utils/featurebase.d.ts +3 -3
- package/dist/utils/featurebase.d.ts.map +1 -1
- package/dist/utils/featurebase.js +15 -15
- package/dist/utils/featurebase.js.map +1 -1
- package/dist/utils/fs.js.map +1 -1
- package/dist/utils/globals.d.ts.map +1 -1
- package/dist/utils/globals.js +10 -10
- package/dist/utils/globals.js.map +1 -1
- package/dist/utils/jwt.d.ts.map +1 -1
- package/dist/utils/jwt.js +3 -3
- package/dist/utils/jwt.js.map +1 -1
- package/dist/utils/redirect-urls.d.ts +3 -3
- package/dist/utils/redirect-urls.d.ts.map +1 -1
- package/dist/utils/redirect-urls.js +5 -5
- package/dist/utils/redirect-urls.js.map +1 -1
- package/dist/utils/urls.js.map +1 -1
- package/package.json +2 -1
- package/src/ai/image-limits.ts +62 -0
- package/src/ai/llms/llms.ts +36 -0
- package/src/ai/unified-prompts/reminders.ts +27 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/ai-setup-prompt.ts +1047 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/brain.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/cli-help.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/config-docs.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/custom-components-instructions.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/dashboard-instructions.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/docs-index.ts +80 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/docs-json.generated.ts +322 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/openapi-specs.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt-parts/sdk-interface-source.ts +5 -0
- package/src/ai/unified-prompts/skill-site-prompt.ts +72 -0
- package/src/apps/apps-config.ts +177 -0
- package/src/apps/apps-ui.tsx +112 -0
- package/src/config/README.md +154 -0
- package/src/config/db-sync-mappings.ts +2293 -0
- package/src/config/format.ts +388 -0
- package/src/config/migrate-catalogs-to-product-lines.ts +475 -0
- package/src/config/schema-fuzzer.test.ts +377 -0
- package/src/config/schema.ts +1507 -0
- package/src/config-authoring.test.ts +52 -0
- package/src/config-authoring.ts +37 -0
- package/src/config-rendering.ts +142 -0
- package/src/crud.tsx +275 -0
- package/src/global.d.ts +1 -0
- package/src/helpers/emails.ts +250 -0
- package/src/helpers/init-prompt.ts +39 -0
- package/src/helpers/password.ts +16 -0
- package/src/helpers/production-mode.ts +58 -0
- package/src/helpers/support-sla.test.ts +124 -0
- package/src/helpers/support-sla.ts +93 -0
- package/src/helpers/vault/client-side.ts +92 -0
- package/src/helpers/vault/server-side.ts +153 -0
- package/src/hexclave-config-file.ts +120 -0
- package/src/hooks/use-async-callback.tsx +43 -0
- package/src/hooks/use-async-external-store.tsx +24 -0
- package/src/hooks/use-hash.tsx +14 -0
- package/src/hooks/use-hover.tsx +88 -0
- package/src/hooks/use-strict-memo.tsx +157 -0
- package/src/index.ts +17 -0
- package/src/interface/admin-interface.ts +1043 -0
- package/src/interface/admin-metrics.ts +214 -0
- package/src/interface/client-interface.test.ts +765 -0
- package/src/interface/client-interface.ts +2586 -0
- package/src/interface/conversations.ts +109 -0
- package/src/interface/crud/analytics.ts +11 -0
- package/src/interface/crud/connected-accounts.ts +52 -0
- package/src/interface/crud/contact-channels.ts +74 -0
- package/src/interface/crud/current-user.ts +72 -0
- package/src/interface/crud/email-outbox.ts +263 -0
- package/src/interface/crud/email-templates.ts +50 -0
- package/src/interface/crud/emails.ts +22 -0
- package/src/interface/crud/internal-api-keys.ts +69 -0
- package/src/interface/crud/invoices.ts +36 -0
- package/src/interface/crud/items.ts +24 -0
- package/src/interface/crud/notification-preferences.ts +33 -0
- package/src/interface/crud/oauth-providers.ts +91 -0
- package/src/interface/crud/products.ts +42 -0
- package/src/interface/crud/project-api-keys.ts +100 -0
- package/src/interface/crud/project-permissions.ts +118 -0
- package/src/interface/crud/projects.ts +229 -0
- package/src/interface/crud/session-replays.ts +85 -0
- package/src/interface/crud/sessions.ts +66 -0
- package/src/interface/crud/sign-up-rules.ts +12 -0
- package/src/interface/crud/svix-token.ts +20 -0
- package/src/interface/crud/team-invitation-details.ts +22 -0
- package/src/interface/crud/team-invitation.ts +35 -0
- package/src/interface/crud/team-member-profiles.ts +61 -0
- package/src/interface/crud/team-memberships.ts +56 -0
- package/src/interface/crud/team-permissions.ts +119 -0
- package/src/interface/crud/teams.ts +142 -0
- package/src/interface/crud/transactions.ts +131 -0
- package/src/interface/crud/users.ts +185 -0
- package/src/interface/handler-urls.ts +74 -0
- package/src/interface/page-component-versions.ts +1702 -0
- package/src/interface/server-interface.ts +1146 -0
- package/src/interface/webhooks.ts +28 -0
- package/src/known-errors.tsx +2034 -0
- package/src/local-emulator.ts +5 -0
- package/src/payments/payment-methods.ts +167 -0
- package/src/payments/stripe-limits.ts +18 -0
- package/src/plans.ts +107 -0
- package/src/schema-fields.ts +944 -0
- package/src/sessions.ts +310 -0
- package/src/utils/api-keys.tsx +122 -0
- package/src/utils/arrays.tsx +248 -0
- package/src/utils/auth-methods.ts +8 -0
- package/src/utils/base64.tsx +24 -0
- package/src/utils/booleans.tsx +34 -0
- package/src/utils/browser-compat.tsx +17 -0
- package/src/utils/bytes.tsx +280 -0
- package/src/utils/caches.tsx +280 -0
- package/src/utils/cel-fields.ts +92 -0
- package/src/utils/cloud-hosts.tsx +92 -0
- package/src/utils/compile-time.tsx +11 -0
- package/src/utils/country-codes.ts +39 -0
- package/src/utils/crypto.tsx +174 -0
- package/src/utils/currencies.tsx +53 -0
- package/src/utils/currency-constants.tsx +51 -0
- package/src/utils/dates.tsx +246 -0
- package/src/utils/dev-env-state-path.ts +14 -0
- package/src/utils/dom.tsx +7 -0
- package/src/utils/env.tsx +117 -0
- package/src/utils/errors.tsx +284 -0
- package/src/utils/esbuild.tsx +235 -0
- package/src/utils/featurebase.tsx +247 -0
- package/src/utils/fs.tsx +33 -0
- package/src/utils/functions.tsx +22 -0
- package/src/utils/geo.tsx +16 -0
- package/src/utils/globals.tsx +48 -0
- package/src/utils/hashes.tsx +52 -0
- package/src/utils/html.tsx +60 -0
- package/src/utils/http.tsx +91 -0
- package/src/utils/ips.tsx +47 -0
- package/src/utils/json.tsx +200 -0
- package/src/utils/jsx-editable-transpiler.test.ts +156 -0
- package/src/utils/jsx-editable-transpiler.tsx +401 -0
- package/src/utils/jwt.tsx +170 -0
- package/src/utils/locks.tsx +71 -0
- package/src/utils/maps.tsx +407 -0
- package/src/utils/math.tsx +18 -0
- package/src/utils/monkey-patch.tsx +29 -0
- package/src/utils/node-http.tsx +47 -0
- package/src/utils/numbers.tsx +82 -0
- package/src/utils/oauth.tsx +9 -0
- package/src/utils/objects.tsx +581 -0
- package/src/utils/paginated-lists.test.ts +1039 -0
- package/src/utils/paginated-lists.tsx +479 -0
- package/src/utils/passkey.tsx +1 -0
- package/src/utils/promises.tsx +540 -0
- package/src/utils/proxies.tsx +212 -0
- package/src/utils/react.tsx +308 -0
- package/src/utils/redirect-urls.tsx +299 -0
- package/src/utils/regex.tsx +10 -0
- package/src/utils/results.tsx +411 -0
- package/src/utils/sentry.tsx +20 -0
- package/src/utils/stores.tsx +238 -0
- package/src/utils/strings.nicify.test.ts +253 -0
- package/src/utils/strings.tsx +723 -0
- package/src/utils/telemetry.tsx +37 -0
- package/src/utils/turnstile-browser.ts +106 -0
- package/src/utils/turnstile-flow.test.ts +101 -0
- package/src/utils/turnstile-flow.ts +266 -0
- package/src/utils/turnstile.ts +34 -0
- package/src/utils/typed-arrays.tsx +17 -0
- package/src/utils/types.tsx +208 -0
- package/src/utils/unicode.tsx +24 -0
- package/src/utils/urls.tsx +411 -0
- package/src/utils/uuids.tsx +47 -0
- package/dist/esm/stack-config-file.d.ts +0 -15
- package/dist/esm/stack-config-file.d.ts.map +0 -1
- package/dist/esm/stack-config-file.js.map +0 -1
- package/dist/stack-config-file.d.ts +0 -15
- package/dist/stack-config-file.d.ts.map +0 -1
- package/dist/stack-config-file.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.js","names":[],"sources":["../../../src/utils/crypto.tsx"],"sourcesContent":["import { encodeBase32, encodeBase64 } from \"./bytes\";\nimport { HexclaveAssertionError } from \"./errors\";\nimport { globalVar } from \"./globals\";\nimport { Result } from \"./results\";\nimport { toArrayBufferBacked } from \"./typed-arrays\";\n\nexport function generateRandomValues(array: Uint8Array): typeof array {\n if (!globalVar.crypto) {\n throw new HexclaveAssertionError(\"Crypto API is not available in this environment. Are you using an old browser?\");\n }\n if (!globalVar.crypto.getRandomValues) {\n throw new HexclaveAssertionError(\"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\nasync function getDerivedSymmetricKey(purpose: string, secret: string | Uint8Array, salt: Uint8Array) {\n const secretBytes = typeof secret === \"string\" ? new TextEncoder().encode(secret) : toArrayBufferBacked(secret);\n const originalSecretKey = await crypto.subtle.importKey(\"raw\", secretBytes, \"HKDF\", false, [\"deriveKey\"]);\n return await crypto.subtle.deriveKey(\n {\n name: \"HKDF\",\n salt: toArrayBufferBacked(salt),\n hash: \"SHA-256\",\n info: new TextEncoder().encode(JSON.stringify([\n \"stack-crypto-helper-derived-symmetric-key\",\n purpose,\n typeof secret === \"string\" ? \"string-key\" : \"binary-key\",\n encodeBase64(salt),\n ])),\n },\n originalSecretKey,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n}\n\nexport async function encrypt({ purpose, secret, value }: { purpose: string, secret: string | Uint8Array, value: Uint8Array }) {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const derivedSecretKey = await getDerivedSymmetricKey(purpose, secret, salt);\n\n const cipher = await crypto.subtle.encrypt({\n name: \"AES-GCM\",\n iv,\n }, derivedSecretKey, toArrayBufferBacked(value));\n\n const version = [0x01, 0x00];\n return new Uint8Array([...version, ...salt, ...iv, ...new Uint8Array(cipher)]);\n}\n\nexport async function decrypt({ purpose, secret, cipher }: { purpose: string, secret: string | Uint8Array, cipher: Uint8Array }) {\n const version = cipher.slice(0, 2);\n if (version[0] !== 0x01 || version[1] !== 0x00) throw new HexclaveAssertionError(\"Invalid ciphertext version in decrypt(...); expected 0x0100\", { purpose });\n const salt = cipher.slice(2, 18);\n const iv = cipher.slice(18, 30);\n const cipherBytes = cipher.slice(30);\n const derivedSecretKey = await getDerivedSymmetricKey(purpose, secret, salt);\n\n try {\n const plaintext = await crypto.subtle.decrypt({\n name: \"AES-GCM\",\n iv,\n }, derivedSecretKey, cipherBytes);\n return Result.ok(new Uint8Array(plaintext));\n } catch (e) {\n if (e instanceof DOMException && e.name === \"OperationError\") {\n return Result.error(new Error(\"Invalid ciphertext or secret when decrypting encrypted value\", { cause: e }));\n }\n throw e;\n }\n}\n\nimport.meta.vitest?.test(\"encrypt & decrypt\", async ({ expect }) => {\n const encryptAndDecrypt = async (encryptPurpose: string, decryptPurpose: string, encryptSecret: string | Uint8Array, decryptSecret: string | Uint8Array, value: Uint8Array) => {\n const encrypted = await encrypt({ purpose: encryptPurpose, secret: encryptSecret, value });\n const decrypted = await decrypt({ purpose: decryptPurpose, secret: decryptSecret, cipher: encrypted });\n return decrypted;\n };\n\n const exampleBytes = new TextEncoder().encode(\"hello\");\n\n const exampleKey1 = crypto.getRandomValues(new Uint8Array(32));\n const exampleKey2 = crypto.getRandomValues(new Uint8Array(32));\n\n expect(await encryptAndDecrypt(\"p\", \"p\", \"secret\", \"secret\", exampleBytes)).toEqual(Result.ok(exampleBytes));\n expect(await encryptAndDecrypt(\"p\", \"p\", exampleKey1, exampleKey1, exampleBytes)).toEqual(Result.ok(exampleBytes));\n expect(await encryptAndDecrypt(\"p\", \"p\", exampleKey1, \"secret\", exampleBytes)).toEqual(Result.error(expect.objectContaining({ message: \"Invalid ciphertext or secret when decrypting encrypted value\" })));\n expect(await encryptAndDecrypt(\"p\", \"p\", exampleKey1, exampleKey2, exampleBytes)).toEqual(Result.error(expect.objectContaining({ message: \"Invalid ciphertext or secret when decrypting encrypted value\" })));\n expect(await encryptAndDecrypt(\"p\", \"not-p\", exampleKey1, exampleKey1, exampleBytes)).toEqual(Result.error(expect.objectContaining({ message: \"Invalid ciphertext or secret when decrypting encrypted value\" })));\n});\n\nexport type HashOptions = {\n purpose: string,\n salt?: string | Uint8Array,\n extra?: string | Uint8Array,\n value: string | Uint8Array,\n};\n\nexport async function hash(options: HashOptions) {\n return await iteratedHash({ ...options, iterations: 1 });\n}\n\nexport async function iteratedHash(options: HashOptions & { iterations: number }) {\n const stringOrUint8ArrayToUint8Array = (value: string | Uint8Array) => typeof value === \"string\" ? new TextEncoder().encode(value) : toArrayBufferBacked(value);\n const stringOrUint8ArrayToBase64 = (value: string | Uint8Array) => encodeBase64(stringOrUint8ArrayToUint8Array(value));\n const input = await crypto.subtle.importKey(\n \"raw\",\n stringOrUint8ArrayToUint8Array(options.value),\n \"PBKDF2\",\n false,\n [\"deriveBits\"]\n );\n return new Uint8Array(await crypto.subtle.deriveBits({\n name: \"PBKDF2\",\n salt: new TextEncoder().encode(JSON.stringify([\n \"stack-crypto-helper-iterated-hash\",\n options.purpose,\n stringOrUint8ArrayToBase64(options.salt ?? \"\"),\n stringOrUint8ArrayToBase64(options.extra ?? \"\"),\n ])),\n iterations: options.iterations,\n hash: \"SHA-256\",\n }, input, 256));\n}\n\nimport.meta.vitest?.test(\"iteratedHash\", async ({ expect }) => {\n const valueBytes = new TextEncoder().encode(\"hello\");\n const incrementBytes = new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]);\n\n const hash = await iteratedHash({ purpose: \"purpose\", value: valueBytes, iterations: 100_000 });\n const hash2 = await iteratedHash({ purpose: \"purpose\", value: valueBytes, iterations: 100_000 });\n const hashWithDifferentPurpose = await iteratedHash({ purpose: \"different-purpose\", value: valueBytes, iterations: 100_000 });\n const hashWithEmptySalt = await iteratedHash({ purpose: \"purpose\", value: valueBytes, salt: new Uint8Array(0), iterations: 100_000 });\n const hashWithDifferentSalt = await iteratedHash({ purpose: \"purpose\", value: valueBytes, salt: incrementBytes, iterations: 100_000 });\n const hashWithEmptyExtra = await iteratedHash({ purpose: \"purpose\", value: valueBytes, extra: new Uint8Array(0), iterations: 100_000 });\n const hashWithDifferentExtra = await iteratedHash({ purpose: \"purpose\", value: valueBytes, extra: incrementBytes, iterations: 100_000 });\n const hashWithDifferentValue = await iteratedHash({ purpose: \"purpose\", value: new TextEncoder().encode(\"hello2\"), iterations: 100_000 });\n const hashWithDifferentSaltAndExtra = await iteratedHash({ purpose: \"purpose\", value: valueBytes, salt: incrementBytes, extra: incrementBytes, iterations: 100_000 });\n const hashWithDifferentIterations = await iteratedHash({ purpose: \"purpose\", value: valueBytes, iterations: 100_001 });\n\n\n expect(hash).toEqual(hash2);\n expect(hash).not.toEqual(hashWithDifferentPurpose);\n expect(hash).toEqual(hashWithEmptySalt);\n expect(hash).not.toEqual(hashWithDifferentSalt);\n expect(hash).toEqual(hashWithEmptyExtra);\n expect(hash).not.toEqual(hashWithDifferentExtra);\n expect(hash).not.toEqual(hashWithDifferentValue);\n expect(hash).not.toEqual(hashWithDifferentIterations);\n\n expect(hashWithDifferentSalt).not.toEqual(hashWithDifferentExtra);\n expect(hashWithDifferentSalt).not.toEqual(hashWithDifferentSaltAndExtra);\n expect(hashWithDifferentExtra).not.toEqual(hashWithDifferentSaltAndExtra);\n});\n"],"mappings":";;;;;;;AAMA,SAAgB,qBAAqB,OAAiC;AACpE,KAAI,CAAC,UAAU,OACb,OAAM,IAAI,uBAAuB,iFAAiF;AAEpH,KAAI,CAAC,UAAU,OAAO,gBACpB,OAAM,IAAI,uBAAuB,6FAA6F;AAEhI,QAAO,UAAU,OAAO,gBAAgB,MAAM;;;;;;AAOhD,SAAgB,2BAA2B,mBAA2B,KAAK;CACzE,MAAM,wBAAwB,KAAK,KAAK,mBAAmB,EAAE;CAC7D,MAAM,aAAa,KAAK,KAAK,wBAAwB,IAAI,EAAE;CAE3D,MAAM,MAAM,aADQ,qBAAqB,IAAI,WAAW,WAAW,CAAC,CAC/B;AACrC,QAAO,IAAI,MAAM,IAAI,SAAS,sBAAsB,CAAC,aAAa;;AAGpE,eAAe,uBAAuB,SAAiB,QAA6B,MAAkB;CACpG,MAAM,cAAc,OA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{"version":3,"file":"crypto.js","names":[],"sources":["../../../src/utils/crypto.tsx"],"sourcesContent":["import { encodeBase32, encodeBase64 } from \"./bytes\";\nimport { HexclaveAssertionError } from \"./errors\";\nimport { globalVar } from \"./globals\";\nimport { Result } from \"./results\";\nimport { toArrayBufferBacked } from \"./typed-arrays\";\n\nexport function generateRandomValues(array: Uint8Array): typeof array {\n if (!globalVar.crypto) {\n throw new HexclaveAssertionError(\"Crypto API is not available in this environment. Are you using an old browser?\");\n }\n if (!globalVar.crypto.getRandomValues) {\n throw new HexclaveAssertionError(\"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\nasync function getDerivedSymmetricKey(purpose: string, secret: string | Uint8Array, salt: Uint8Array) {\n const secretBytes = typeof secret === \"string\" ? new TextEncoder().encode(secret) : toArrayBufferBacked(secret);\n const originalSecretKey = await crypto.subtle.importKey(\"raw\", secretBytes, \"HKDF\", false, [\"deriveKey\"]);\n return await crypto.subtle.deriveKey(\n {\n name: \"HKDF\",\n salt: toArrayBufferBacked(salt),\n hash: \"SHA-256\",\n // NOTE (Hexclave rebrand): do NOT rename this \"stack-*\" literal. It is a domain-separation\n // tag baked into HKDF key derivation; changing it would derive different keys and make all\n // previously-encrypted data undecryptable. It is an internal constant, never user-visible.\n info: new TextEncoder().encode(JSON.stringify([\n \"stack-crypto-helper-derived-symmetric-key\",\n purpose,\n typeof secret === \"string\" ? \"string-key\" : \"binary-key\",\n encodeBase64(salt),\n ])),\n },\n originalSecretKey,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n}\n\nexport async function encrypt({ purpose, secret, value }: { purpose: string, secret: string | Uint8Array, value: Uint8Array }) {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const derivedSecretKey = await getDerivedSymmetricKey(purpose, secret, salt);\n\n const cipher = await crypto.subtle.encrypt({\n name: \"AES-GCM\",\n iv,\n }, derivedSecretKey, toArrayBufferBacked(value));\n\n const version = [0x01, 0x00];\n return new Uint8Array([...version, ...salt, ...iv, ...new Uint8Array(cipher)]);\n}\n\nexport async function decrypt({ purpose, secret, cipher }: { purpose: string, secret: string | Uint8Array, cipher: Uint8Array }) {\n const version = cipher.slice(0, 2);\n if (version[0] !== 0x01 || version[1] !== 0x00) throw new HexclaveAssertionError(\"Invalid ciphertext version in decrypt(...); expected 0x0100\", { purpose });\n const salt = cipher.slice(2, 18);\n const iv = cipher.slice(18, 30);\n const cipherBytes = cipher.slice(30);\n const derivedSecretKey = await getDerivedSymmetricKey(purpose, secret, salt);\n\n try {\n const plaintext = await crypto.subtle.decrypt({\n name: \"AES-GCM\",\n iv,\n }, derivedSecretKey, cipherBytes);\n return Result.ok(new Uint8Array(plaintext));\n } catch (e) {\n if (e instanceof DOMException && e.name === \"OperationError\") {\n return Result.error(new Error(\"Invalid ciphertext or secret when decrypting encrypted value\", { cause: e }));\n }\n throw e;\n }\n}\n\nimport.meta.vitest?.test(\"encrypt & decrypt\", async ({ expect }) => {\n const encryptAndDecrypt = async (encryptPurpose: string, decryptPurpose: string, encryptSecret: string | Uint8Array, decryptSecret: string | Uint8Array, value: Uint8Array) => {\n const encrypted = await encrypt({ purpose: encryptPurpose, secret: encryptSecret, value });\n const decrypted = await decrypt({ purpose: decryptPurpose, secret: decryptSecret, cipher: encrypted });\n return decrypted;\n };\n\n const exampleBytes = new TextEncoder().encode(\"hello\");\n\n const exampleKey1 = crypto.getRandomValues(new Uint8Array(32));\n const exampleKey2 = crypto.getRandomValues(new Uint8Array(32));\n\n expect(await encryptAndDecrypt(\"p\", \"p\", \"secret\", \"secret\", exampleBytes)).toEqual(Result.ok(exampleBytes));\n expect(await encryptAndDecrypt(\"p\", \"p\", exampleKey1, exampleKey1, exampleBytes)).toEqual(Result.ok(exampleBytes));\n expect(await encryptAndDecrypt(\"p\", \"p\", exampleKey1, \"secret\", exampleBytes)).toEqual(Result.error(expect.objectContaining({ message: \"Invalid ciphertext or secret when decrypting encrypted value\" })));\n expect(await encryptAndDecrypt(\"p\", \"p\", exampleKey1, exampleKey2, exampleBytes)).toEqual(Result.error(expect.objectContaining({ message: \"Invalid ciphertext or secret when decrypting encrypted value\" })));\n expect(await encryptAndDecrypt(\"p\", \"not-p\", exampleKey1, exampleKey1, exampleBytes)).toEqual(Result.error(expect.objectContaining({ message: \"Invalid ciphertext or secret when decrypting encrypted value\" })));\n});\n\nexport type HashOptions = {\n purpose: string,\n salt?: string | Uint8Array,\n extra?: string | Uint8Array,\n value: string | Uint8Array,\n};\n\nexport async function hash(options: HashOptions) {\n return await iteratedHash({ ...options, iterations: 1 });\n}\n\nexport async function iteratedHash(options: HashOptions & { iterations: number }) {\n const stringOrUint8ArrayToUint8Array = (value: string | Uint8Array) => typeof value === \"string\" ? new TextEncoder().encode(value) : toArrayBufferBacked(value);\n const stringOrUint8ArrayToBase64 = (value: string | Uint8Array) => encodeBase64(stringOrUint8ArrayToUint8Array(value));\n const input = await crypto.subtle.importKey(\n \"raw\",\n stringOrUint8ArrayToUint8Array(options.value),\n \"PBKDF2\",\n false,\n [\"deriveBits\"]\n );\n return new Uint8Array(await crypto.subtle.deriveBits({\n name: \"PBKDF2\",\n // NOTE (Hexclave rebrand): do NOT rename this \"stack-*\" literal. It is a domain-separation tag\n // mixed into the PBKDF2 salt; changing it would change every hash output and break verification\n // of all previously-hashed values. It is an internal constant, never user-visible.\n salt: new TextEncoder().encode(JSON.stringify([\n \"stack-crypto-helper-iterated-hash\",\n options.purpose,\n stringOrUint8ArrayToBase64(options.salt ?? \"\"),\n stringOrUint8ArrayToBase64(options.extra ?? \"\"),\n ])),\n iterations: options.iterations,\n hash: \"SHA-256\",\n }, input, 256));\n}\n\nimport.meta.vitest?.test(\"iteratedHash\", async ({ expect }) => {\n const valueBytes = new TextEncoder().encode(\"hello\");\n const incrementBytes = new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]);\n\n const hash = await iteratedHash({ purpose: \"purpose\", value: valueBytes, iterations: 100_000 });\n const hash2 = await iteratedHash({ purpose: \"purpose\", value: valueBytes, iterations: 100_000 });\n const hashWithDifferentPurpose = await iteratedHash({ purpose: \"different-purpose\", value: valueBytes, iterations: 100_000 });\n const hashWithEmptySalt = await iteratedHash({ purpose: \"purpose\", value: valueBytes, salt: new Uint8Array(0), iterations: 100_000 });\n const hashWithDifferentSalt = await iteratedHash({ purpose: \"purpose\", value: valueBytes, salt: incrementBytes, iterations: 100_000 });\n const hashWithEmptyExtra = await iteratedHash({ purpose: \"purpose\", value: valueBytes, extra: new Uint8Array(0), iterations: 100_000 });\n const hashWithDifferentExtra = await iteratedHash({ purpose: \"purpose\", value: valueBytes, extra: incrementBytes, iterations: 100_000 });\n const hashWithDifferentValue = await iteratedHash({ purpose: \"purpose\", value: new TextEncoder().encode(\"hello2\"), iterations: 100_000 });\n const hashWithDifferentSaltAndExtra = await iteratedHash({ purpose: \"purpose\", value: valueBytes, salt: incrementBytes, extra: incrementBytes, iterations: 100_000 });\n const hashWithDifferentIterations = await iteratedHash({ purpose: \"purpose\", value: valueBytes, iterations: 100_001 });\n\n\n expect(hash).toEqual(hash2);\n expect(hash).not.toEqual(hashWithDifferentPurpose);\n expect(hash).toEqual(hashWithEmptySalt);\n expect(hash).not.toEqual(hashWithDifferentSalt);\n expect(hash).toEqual(hashWithEmptyExtra);\n expect(hash).not.toEqual(hashWithDifferentExtra);\n expect(hash).not.toEqual(hashWithDifferentValue);\n expect(hash).not.toEqual(hashWithDifferentIterations);\n\n expect(hashWithDifferentSalt).not.toEqual(hashWithDifferentExtra);\n expect(hashWithDifferentSalt).not.toEqual(hashWithDifferentSaltAndExtra);\n expect(hashWithDifferentExtra).not.toEqual(hashWithDifferentSaltAndExtra);\n});\n"],"mappings":";;;;;;;AAMA,SAAgB,qBAAqB,OAAiC;AACpE,KAAI,CAAC,UAAU,OACb,OAAM,IAAI,uBAAuB,iFAAiF;AAEpH,KAAI,CAAC,UAAU,OAAO,gBACpB,OAAM,IAAI,uBAAuB,6FAA6F;AAEhI,QAAO,UAAU,OAAO,gBAAgB,MAAM;;;;;;AAOhD,SAAgB,2BAA2B,mBAA2B,KAAK;CACzE,MAAM,wBAAwB,KAAK,KAAK,mBAAmB,EAAE;CAC7D,MAAM,aAAa,KAAK,KAAK,wBAAwB,IAAI,EAAE;CAE3D,MAAM,MAAM,aADQ,qBAAqB,IAAI,WAAW,WAAW,CAAC,CAC/B;AACrC,QAAO,IAAI,MAAM,IAAI,SAAS,sBAAsB,CAAC,aAAa;;AAGpE,eAAe,uBAAuB,SAAiB,QAA6B,MAAkB;CACpG,MAAM,cAAc,OAAO,WAAW,WAAW,IAAI,aAAa,CAAC,OAAO,OAAO,GAAG,oBAAoB,OAAO;CAC/G,MAAM,oBAAoB,MAAM,OAAO,OAAO,UAAU,OAAO,aAAa,QAAQ,OAAO,CAAC,YAAY,CAAC;AACzG,QAAO,MAAM,OAAO,OAAO,UACzB;EACE,MAAM;EACN,MAAM,oBAAoB,KAAK;EAC/B,MAAM;EAIN,MAAM,IAAI,aAAa,CAAC,OAAO,KAAK,UAAU;GAC5C;GACA;GACA,OAAO,WAAW,WAAW,eAAe;GAC5C,aAAa,KAAK;GACnB,CAAC,CAAC;EACJ,EACD,mBACA;EAAE,MAAM;EAAW,QAAQ;EAAK,EAChC,OACA,CAAC,WAAW,UAAS,CACtB;;AAGH,eAAsB,QAAQ,EAAE,SAAS,QAAQ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a,CAAC,OAAO,SAAS;EAAE,YAAY;EAAS,CAAC;CACzI,MAAM,gCAAgC,MAAM,aAAa;EAAE,SAAS;EAAW,OAAO;EAAY,MAAM;EAAgB,OAAO;EAAgB,YAAY;EAAS,CAAC;CACrK,MAAM,8BAA8B,MAAM,aAAa;EAAE,SAAS;EAAW,OAAO;EAAY,YAAY;EAAS,CAAC;AAGtH,QAAO,KAAK,CAAC,QAAQ,MAAM;AAC3B,QAAO,KAAK,CAAC,IAAI,QAAQ,yBAAyB;AAClD,QAAO,KAAK,CAAC,QAAQ,kBAAkB;AACvC,QAAO,KAAK,CAAC,IAAI,QAAQ,sBAAsB;AAC/C,QAAO,KAAK,CAAC,QAAQ,mBAAmB;AACxC,QAAO,KAAK,CAAC,IAAI,QAAQ,uBAAuB;AAChD,QAAO,KAAK,CAAC,IAAI,QAAQ,uBAAuB;AAChD,QAAO,KAAK,CAAC,IAAI,QAAQ,4BAA4B;AAErD,QAAO,sBAAsB,CAAC,IAAI,QAAQ,uBAAuB;AACjE,QAAO,sBAAsB,CAAC,IAAI,QAAQ,8BAA8B;AACxE,QAAO,uBAAuB,CAAC,IAAI,QAAQ,8BAA8B;EACzE"}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
//#region src/utils/currency-constants.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* A decimal string representing a monetary amount, e.g. `"9.99"`, `"0.01"`, or `"1000"`.
|
|
4
|
+
*
|
|
5
|
+
* This is NOT an integer in cents/minor units — it is always a human-readable decimal string.
|
|
6
|
+
* For example, nine dollars and ninety-nine cents is `"9.99"`, not `999`.
|
|
7
|
+
*/
|
|
2
8
|
type MoneyAmount = `${number}` | `${number}.${number}`;
|
|
3
9
|
type Currency = {
|
|
4
10
|
code: Uppercase<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currency-constants.d.ts","names":[],"sources":["../../../src/utils/currency-constants.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"currency-constants.d.ts","names":[],"sources":["../../../src/utils/currency-constants.tsx"],"mappings":";;AAMA;;;;;KAAY,WAAA;AAAA,KAEA,QAAA;EACV,IAAA,EAAM,SAAA;EACN,QAAA;EACA,cAAA;AAAA;AAAA,cAGW,oBAAA;EAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"currency-constants.js","names":[],"sources":["../../../src/utils/currency-constants.tsx"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"currency-constants.js","names":[],"sources":["../../../src/utils/currency-constants.tsx"],"sourcesContent":["/**\n * A decimal string representing a monetary amount, e.g. `\"9.99\"`, `\"0.01\"`, or `\"1000\"`.\n *\n * This is NOT an integer in cents/minor units — it is always a human-readable decimal string.\n * For example, nine dollars and ninety-nine cents is `\"9.99\"`, not `999`.\n */\nexport type MoneyAmount = `${number}` | `${number}.${number}`;\n\nexport type Currency = {\n code: Uppercase<string>,\n decimals: number,\n stripeDecimals: number,\n};\n\nexport const SUPPORTED_CURRENCIES = [\n {\n code: 'USD',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'EUR',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'GBP',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'JPY',\n decimals: 0,\n stripeDecimals: 0,\n },\n {\n code: 'INR',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'AUD',\n decimals: 2,\n stripeDecimals: 2,\n },\n {\n code: 'CAD',\n decimals: 2,\n stripeDecimals: 2,\n },\n] as const satisfies Currency[];\n"],"mappings":";AAcA,MAAa,uBAAuB;CAClC;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACD;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACD;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACD;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACD;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACD;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACD;EACE,MAAM;EACN,UAAU;EACV,gBAAgB;EACjB;CACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/utils/dev-env-state-path.d.ts
|
|
2
|
-
declare function
|
|
3
|
-
declare function
|
|
2
|
+
declare function defaultHexclaveDevEnvStatePath(): string;
|
|
3
|
+
declare function hexclaveDevEnvStatePath(): string;
|
|
4
4
|
//#endregion
|
|
5
|
-
export {
|
|
5
|
+
export { defaultHexclaveDevEnvStatePath, hexclaveDevEnvStatePath };
|
|
6
6
|
//# sourceMappingURL=dev-env-state-path.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-env-state-path.d.ts","names":[],"sources":["../../../src/utils/dev-env-state-path.ts"],"mappings":";iBAGgB,
|
|
1
|
+
{"version":3,"file":"dev-env-state-path.d.ts","names":[],"sources":["../../../src/utils/dev-env-state-path.ts"],"mappings":";iBAGgB,8BAAA,CAAA;AAAA,iBAQA,uBAAA,CAAA"}
|
|
@@ -2,14 +2,14 @@ import { join } from "path";
|
|
|
2
2
|
import { homedir } from "os";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/dev-env-state-path.ts
|
|
5
|
-
function
|
|
5
|
+
function defaultHexclaveDevEnvStatePath() {
|
|
6
6
|
if (process.platform === "win32") return join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "Hexclave", "dev-envs.json");
|
|
7
7
|
return join(homedir(), ".stack", "dev-envs.json");
|
|
8
8
|
}
|
|
9
|
-
function
|
|
10
|
-
return process.env.STACK_DEV_ENVS_PATH ??
|
|
9
|
+
function hexclaveDevEnvStatePath() {
|
|
10
|
+
return process.env.STACK_DEV_ENVS_PATH ?? defaultHexclaveDevEnvStatePath();
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
//#endregion
|
|
14
|
-
export {
|
|
14
|
+
export { defaultHexclaveDevEnvStatePath, hexclaveDevEnvStatePath };
|
|
15
15
|
//# sourceMappingURL=dev-env-state-path.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-env-state-path.js","names":[],"sources":["../../../src/utils/dev-env-state-path.ts"],"sourcesContent":["import { homedir } from \"os\";\nimport { join } from \"path\";\n\nexport function
|
|
1
|
+
{"version":3,"file":"dev-env-state-path.js","names":[],"sources":["../../../src/utils/dev-env-state-path.ts"],"sourcesContent":["import { homedir } from \"os\";\nimport { join } from \"path\";\n\nexport function defaultHexclaveDevEnvStatePath(): string {\n if (process.platform === \"win32\") {\n const localAppData = process.env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\");\n return join(localAppData, \"Hexclave\", \"dev-envs.json\");\n }\n return join(homedir(), \".stack\", \"dev-envs.json\");\n}\n\nexport function hexclaveDevEnvStatePath(): string {\n return process.env.STACK_DEV_ENVS_PATH ?? defaultHexclaveDevEnvStatePath();\n}\n"],"mappings":";;;;AAGA,SAAgB,iCAAyC;AACvD,KAAI,QAAQ,aAAa,QAEvB,QAAO,KADc,QAAQ,IAAI,gBAAgB,KAAK,SAAS,EAAE,WAAW,QAAQ,EAC1D,YAAY,gBAAgB;AAExD,QAAO,KAAK,SAAS,EAAE,UAAU,gBAAgB;;AAGnD,SAAgB,0BAAkC;AAChD,QAAO,QAAQ,IAAI,uBAAuB,gCAAgC"}
|
package/dist/esm/utils/errors.js
CHANGED
|
@@ -71,8 +71,8 @@ registerErrorSink((location, error, level, ...extraArgs) => {
|
|
|
71
71
|
(level === "warning" ? console.warn : console.error)(`${level === "warning" ? "\x1B[43m" : "\x1B[41m"}Captured ${level === "warning" ? "warning" : "error"} in ${location}:`, errorToNiceString(error), ...extraArgs, "\x1B[0m");
|
|
72
72
|
});
|
|
73
73
|
registerErrorSink((location, error, level, ...extraArgs) => {
|
|
74
|
-
globalVar.
|
|
75
|
-
globalVar.
|
|
74
|
+
globalVar.hexclaveCapturedErrors = globalVar.hexclaveCapturedErrors ?? [];
|
|
75
|
+
globalVar.hexclaveCapturedErrors.push({
|
|
76
76
|
location,
|
|
77
77
|
error,
|
|
78
78
|
level,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new HexclaveAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Note: Very often, the concatStacktracesIfRejected function in promises.tsx is an easier way to use this function.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class HexclaveAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Hexclave. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n\n // Use literal dot-form (guarded with `typeof process`) so Next.js / webpack\n // DefinePlugin can inline the value at build time. See getProcessEnv in ./env.\n if ((typeof process !== \"undefined\" ? process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR : undefined) === \"true\") {\n debugger;\n }\n }\n}\nHexclaveAssertionError.prototype.name = \"HexclaveAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nexport type CaptureLevel = \"error\" | \"warning\";\n\ntype ErrorSink = (location: string, error: unknown, level: CaptureLevel, ...extraArgs: unknown[]) => void;\n\nconst errorSinks = new Set<ErrorSink>();\nexport function registerErrorSink(sink: ErrorSink): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, level, ...extraArgs) => {\n const logger = level === \"warning\" ? console.warn : console.error;\n const colorCode = level === \"warning\" ? \"\\x1b[43m\" : \"\\x1b[41m\";\n const label = level === \"warning\" ? \"warning\" : \"error\";\n logger(\n `${colorCode}Captured ${label} in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // 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\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, level, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, level, extraArgs });\n});\n\nfunction dispatchToSinks(location: string, error: unknown, level: CaptureLevel): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n level,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n/**\n * Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are\n * supposed to be seen by an engineer, so they should be actionable and important.\n *\n * The location string is a machine-readable ID, and should hence not contain spaces or anything like that. Good\n * examples are: \"api-route-handler\", \"renderPart()\", etc.\n *\n * Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.\n */\nexport function captureError(location: string, error: unknown): void {\n dispatchToSinks(location, error, \"error\");\n}\n\n/**\n * Like captureError, but logs at warning level. Use for issues that an engineer should know about but that aren't\n * severe enough to be treated as an error (e.g. recoverable failures in background tasks).\n */\nexport function captureWarning(location: string, error: unknown): void {\n dispatchToSinks(location, error, \"warning\");\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new HexclaveAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";;;;;AASA,SAAgB,SAAS,GAAG,MAAoB;AAC9C,KAAI,OAAO,KAAK,OAAO,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1B;GAAE,YAAY;GAAK,SAAS;GAAmC;;CAI7G,YACE,QACA,SACA;AACA,MAAI,OAAO,WAAW,UAAU;AAC9B,eAAY,OAAO;AACnB,YAAS,OAAO;;AAElB,QAAM,QAAQ;iCAxD2B;cAC7B;AAwDZ,OAAK,aAAa;AAClB,MAAI,CAAC,QACH,OAAM,IAAI,uBAAuB,0EAA0E,EAAE,OAAO,MAAM,CAAC;;CAI/H,OAAc,cAAc,OAAsC;AAEhE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,6BAA6B,SAAS,MAAM,4BAA4B;;CAGhI,AAAO,gBAAgB;AACrB,SAAO,KAAK,cAAc,OAAO,KAAK,aAAa;;CAGrD,AAAO,gBAAgB;AACrB,SAAO,CAAC,KAAK,eAAe;;CAG9B,AAAO,gBAAwB;AAC7B,SAAO,KAAK;;CAGd,AAAO,UAAsB;AAC3B,SAAO,IAAI,aAAa,CAAC,OAAO,KAAK,QAAQ;;CAG/C,AAAO,aAAuC;AAC5C,SAAO,EACL,gBAAgB,CAAC,4BAA4B,EAC9C;;CAGH,AAAO,oBAA0B;AAC/B,SAAO;GACL,aAAa,KAAK,eAAe;GACjC,SAAS,KAAK;GACd,SAAS,KAAK,YAAY;GAC3B;;;;;CAMH,AAAO,aAAmB;AACxB,SAAO;GACL,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,SAAS,KAAK,YAAY;GAC3B;;;AAGL,YAAY,UAAU,OAAO"}
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new HexclaveAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Note: Very often, the concatStacktracesIfRejected function in promises.tsx is an easier way to use this function.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class HexclaveAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Hexclave. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n\n // Use literal dot-form (guarded with `typeof process`) so Next.js / webpack\n // DefinePlugin can inline the value at build time. See getProcessEnv in ./env.\n if ((typeof process !== \"undefined\" ? process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR : undefined) === \"true\") {\n debugger;\n }\n }\n}\nHexclaveAssertionError.prototype.name = \"HexclaveAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nexport type CaptureLevel = \"error\" | \"warning\";\n\ntype ErrorSink = (location: string, error: unknown, level: CaptureLevel, ...extraArgs: unknown[]) => void;\n\nconst errorSinks = new Set<ErrorSink>();\nexport function registerErrorSink(sink: ErrorSink): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, level, ...extraArgs) => {\n const logger = level === \"warning\" ? console.warn : console.error;\n const colorCode = level === \"warning\" ? \"\\x1b[43m\" : \"\\x1b[41m\";\n const label = level === \"warning\" ? \"warning\" : \"error\";\n logger(\n `${colorCode}Captured ${label} in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // 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\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, level, ...extraArgs) => {\n globalVar.hexclaveCapturedErrors = globalVar.hexclaveCapturedErrors ?? [];\n globalVar.hexclaveCapturedErrors.push({ location, error, level, extraArgs });\n});\n\nfunction dispatchToSinks(location: string, error: unknown, level: CaptureLevel): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n level,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n/**\n * Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are\n * supposed to be seen by an engineer, so they should be actionable and important.\n *\n * The location string is a machine-readable ID, and should hence not contain spaces or anything like that. Good\n * examples are: \"api-route-handler\", \"renderPart()\", etc.\n *\n * Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.\n */\nexport function captureError(location: string, error: unknown): void {\n dispatchToSinks(location, error, \"error\");\n}\n\n/**\n * Like captureError, but logs at warning level. Use for issues that an engineer should know about but that aren't\n * severe enough to be treated as an error (e.g. recoverable failures in background tasks).\n */\nexport function captureWarning(location: string, error: unknown): void {\n dispatchToSinks(location, error, \"warning\");\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new HexclaveAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";;;;;AASA,SAAgB,SAAS,GAAG,MAAoB;AAC9C,KAAI,OAAO,KAAK,OAAO,SACrB,OAAM,IAAI,uBAAuB,KAAK,IAAI,KAAK,GAAG;UACzC,KAAK,cAAc,MAC5B,OAAM,KAAK;KAGX,OAAM,IAAI,YAAY,GAAG,KAAK;;AAIlC,SAAS,yBAAyB,OAAuB;CAEvD,MAAM,gCAAe,IAAI,OAAO,EAAC,OAAO,WAAW,UAAU;AAC7D,QAAO,MAAM,MAAM,KAAK,CAAC,MAAM,eAAe,IAAI,EAAE,CAAC,KAAK,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;AA2BjE,SAAgB,kBAAkB,OAAc,GAAG,QAAuB;CAExE,MAAM,qBAAqB,MAAM,OAAO,SAAS,KAAK;CA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AO,KAAK,aAAa;;CAGrD,AAAO,gBAAgB;AACrB,SAAO,CAAC,KAAK,eAAe;;CAG9B,AAAO,gBAAwB;AAC7B,SAAO,KAAK;;CAGd,AAAO,UAAsB;AAC3B,SAAO,IAAI,aAAa,CAAC,OAAO,KAAK,QAAQ;;CAG/C,AAAO,aAAuC;AAC5C,SAAO,EACL,gBAAgB,CAAC,4BAA4B,EAC9C;;CAGH,AAAO,oBAA0B;AAC/B,SAAO;GACL,aAAa,KAAK,eAAe;GACjC,SAAS,KAAK;GACd,SAAS,KAAK,YAAY;GAC3B;;;;;CAMH,AAAO,aAAmB;AACxB,SAAO;GACL,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,SAAS,KAAK,YAAY;GAC3B;;;AAGL,YAAY,UAAU,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"esbuild.d.ts","names":[],"sources":["../../../src/utils/esbuild.tsx"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"esbuild.d.ts","names":[],"sources":["../../../src/utils/esbuild.tsx"],"mappings":";;;iBA0BgB,iBAAA,CAAA,GAAqB,OAAA;AAAA,iBAgDf,gBAAA,CAAiB,WAAA,EAAa,MAAA;EAA2B,WAAA;AAAA,GAAuB,OAAA;EACpG,MAAA;EACA,gBAAA,GAAmB,MAAA;EACnB,aAAA;EACA,SAAA;EACA,gBAAA;AAAA,IACO,OAAA,CAAQ,MAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"esbuild.js","names":[],"sources":["../../../src/utils/esbuild.tsx"],"sourcesContent":["import * as esbuild from 'esbuild-wasm/lib/browser.js';\nimport { join } from 'path';\nimport { getProcessEnv, isBrowserLike } from './env';\nimport { captureError, HexclaveAssertionError, throwErr } from \"./errors\";\nimport { createGlobalAsync } from './globals';\nimport { ignoreUnhandledRejection, runAsynchronously } from './promises';\nimport { Result } from \"./results\";\nimport { traceSpan, withTraceSpan } from './telemetry';\n\n\n// esbuild requires self property to be set, and it is not set by default in nodejs\n(globalThis.self as any) ??= globalThis as any;\n\nlet esbuildInitializePromise: Promise<void> | null = null;\n\nif (typeof process !== \"undefined\" && typeof process.exit === \"function\" && getProcessEnv(\"NODE_ENV\") === 'development') {\n // On development Node.js servers, initialize ESBuild as soon as the module is imported so we have to wait less on the first request\n runAsynchronously(async () => {\n try {\n await initializeEsbuild();\n } catch (e) {\n captureError(\"initialize-esbuild-in-dev\", e);\n (globalThis as any).process?.exit?.(1);\n }\n });\n}\n\nexport function initializeEsbuild(): Promise<void> {\n const esbuildWasmUrl = `https://unpkg.com/esbuild-wasm@${esbuild.version}/esbuild.wasm`;\n if (esbuildInitializePromise == null) {\n esbuildInitializePromise = withTraceSpan('initializeEsbuild', async () => {\n try {\n let initOptions;\n if (isBrowserLike()) {\n initOptions = {\n wasmURL: esbuildWasmUrl,\n };\n } else {\n const esbuildWasmModule = await createGlobalAsync('esbuildWasmModule', async () => {\n const esbuildWasmResponse = await fetch(esbuildWasmUrl);\n if (!esbuildWasmResponse.ok) {\n throw new HexclaveAssertionError(`Failed to fetch esbuild.wasm: ${esbuildWasmResponse.status} ${esbuildWasmResponse.statusText}: ${await esbuildWasmResponse.text()}`);\n }\n const esbuildWasm = await esbuildWasmResponse.arrayBuffer();\n const esbuildWasmArray = new Uint8Array(esbuildWasm);\n if (esbuildWasmArray[0] !== 0x00 || esbuildWasmArray[1] !== 0x61 || esbuildWasmArray[2] !== 0x73 || esbuildWasmArray[3] !== 0x6d) {\n throw new HexclaveAssertionError(`Invalid esbuild.wasm file: ${new TextDecoder().decode(esbuildWasmArray)}`);\n }\n return new WebAssembly.Module(esbuildWasm);\n });\n initOptions = {\n wasmModule: esbuildWasmModule,\n worker: false,\n };\n }\n try {\n await esbuild.initialize(initOptions);\n } catch (e) {\n if (e instanceof Error && e.message === 'Cannot call \"initialize\" more than once') {\n // this happens especially in local development, just ignore\n } else {\n throw e;\n }\n }\n } catch (e) {\n esbuildInitializePromise = null;\n throw new HexclaveAssertionError(\"Failed to initialize ESBuild\", { cause: e });\n }\n })();\n ignoreUnhandledRejection(esbuildInitializePromise);\n }\n\n return esbuildInitializePromise;\n}\n\nexport async function bundleJavaScript(sourceFiles: Record<string, string> & { '/entry.js': string }, options: {\n format?: 'iife' | 'esm' | 'cjs',\n externalPackages?: Record<string, string>,\n keepAsImports?: string[],\n sourcemap?: false | 'inline',\n allowHttpImports?: boolean,\n} = {}): Promise<Result<string, string>> {\n await initializeEsbuild();\n\n const sourceFilesMap = new Map(Object.entries(sourceFiles));\n const externalPackagesMap = new Map(Object.entries(options.externalPackages ?? {}));\n const keepAsImports = options.keepAsImports ?? [];\n\n const httpImportCache = new Map<string, { contents: string, loader: esbuild.Loader, resolveDir: string }>();\n\n const extToLoader: Map<string, esbuild.Loader> = new Map([\n ['tsx', 'tsx'],\n ['ts', 'ts'],\n ['js', 'js'],\n ['jsx', 'jsx'],\n ['json', 'json'],\n ['css', 'css'],\n ]);\n let result;\n try {\n result = await traceSpan('bundleJavaScript', async () => await esbuild.build({\n entryPoints: ['/entry.js'],\n bundle: true,\n write: false,\n format: options.format ?? 'iife',\n platform: 'browser',\n target: 'es2015',\n jsx: 'automatic',\n sourcemap: options.sourcemap ?? 'inline',\n external: keepAsImports,\n plugins: [\n ...options.allowHttpImports ? [{\n name: \"esm-sh-only\",\n setup(build: esbuild.PluginBuild) {\n // Handle absolute URLs and relative imports from esm.sh modules.\n build.onResolve({ filter: /.*/ }, (args) => {\n // Only touch absolute http(s) specifiers or children of our own namespace\n const isHttp = args.path.startsWith(\"http://\") || args.path.startsWith(\"https://\");\n const fromEsmNs = args.namespace === \"esm-sh\";\n\n if (!isHttp && !fromEsmNs) return null; // Let other plugins handle bare/relative/local\n\n // Resolve relative URLs inside esm.sh-fetched modules\n const url = new URL(args.path, fromEsmNs ? args.importer : undefined);\n\n if (url.protocol !== \"https:\" || url.host !== \"esm.sh\") {\n throw new Error(`Blocked non-esm.sh URL import: ${url.href}`);\n }\n\n return { path: url.href, namespace: \"esm-sh\" };\n });\n\n build.onLoad({ filter: /.*/, namespace: \"esm-sh\" }, async (args) => {\n if (httpImportCache.has(args.path)) return httpImportCache.get(args.path)!;\n\n const res = await fetch(args.path, { redirect: \"follow\" });\n if (!res.ok) throw new Error(`Fetch ${res.status} ${res.statusText} for ${args.path}`);\n const finalUrl = new URL(res.url);\n // Defensive: follow shouldn’t leave esm.sh, but re-check.\n if (finalUrl.host !== \"esm.sh\") {\n throw new Error(`Redirect escaped esm.sh: ${finalUrl.href}`);\n }\n\n const ct = (res.headers.get(\"content-type\") || \"\").toLowerCase();\n let loader: esbuild.Loader =\n ct.includes(\"css\") ? \"css\" :\n ct.includes(\"json\") ? \"json\" :\n ct.includes(\"typescript\") ? \"ts\" :\n ct.includes(\"jsx\") ? \"jsx\" :\n ct.includes(\"tsx\") ? \"tsx\" :\n \"js\";\n\n // Fallback by extension (esm.sh sometimes omits CT)\n const p = finalUrl.pathname;\n if (p.endsWith(\".css\")) loader = \"css\";\n else if (p.endsWith(\".json\")) loader = \"json\";\n else if (p.endsWith(\".ts\")) loader = \"ts\";\n else if (p.endsWith(\".tsx\")) loader = \"tsx\";\n else if (p.endsWith(\".jsx\")) loader = \"jsx\";\n\n const contents = await res.text();\n const result = {\n contents,\n loader,\n // Ensures relative imports inside that module resolve against the file’s URL\n resolveDir: new URL(\".\", finalUrl.href).toString(),\n watchFiles: [finalUrl.href],\n };\n httpImportCache.set(args.path, result);\n return result;\n });\n },\n } as esbuild.Plugin] : [],\n {\n name: 'replace-packages-with-globals',\n setup(build) {\n build.onResolve({ filter: /.*/ }, args => {\n // Skip packages that should remain external (not be shimmed)\n if (keepAsImports.includes(args.path)) {\n return undefined;\n }\n if (externalPackagesMap.has(args.path)) {\n return { path: args.path, namespace: 'package-shim' };\n }\n return undefined;\n });\n\n build.onLoad({ filter: /.*/, namespace: 'package-shim' }, (args) => {\n const contents = externalPackagesMap.get(args.path);\n if (contents == null) throw new HexclaveAssertionError(`esbuild requested file ${args.path} that is not in the virtual file system`);\n\n return { contents, loader: 'ts' };\n });\n },\n },\n {\n name: 'virtual-fs',\n setup(build) {\n build.onResolve({ filter: /.*/ }, args => {\n const absolutePath = join(\"/\", args.path);\n if (sourceFilesMap.has(absolutePath)) {\n return { path: absolutePath, namespace: 'virtual' };\n }\n return undefined;\n });\n\n /* 2️⃣ Load the module from the map */\n build.onLoad({ filter: /.*/, namespace: 'virtual' }, args => {\n const contents = sourceFilesMap.get(args.path);\n if (contents == null) throw new HexclaveAssertionError(`esbuild requested file ${args.path} that is not in the virtual file system`);\n\n const ext = args.path.split('.').pop() ?? '';\n const loader = extToLoader.get(ext) ?? throwErr(`esbuild requested file ${args.path} with unknown extension ${ext}`);\n\n return { contents, loader };\n });\n },\n },\n ],\n }));\n } catch (e) {\n if (e instanceof Error && e.message.startsWith(\"Build failed with \")) {\n return Result.error(e.message);\n }\n throw e;\n }\n\n if (result.errors.length > 0) {\n return Result.error(result.errors.map(e => e.text).join('\\n'));\n }\n\n if (result.outputFiles.length > 0) {\n return Result.ok(result.outputFiles[0].text);\n }\n return throwErr(\"No output generated??\");\n}\n"],"mappings":";;;;;;;;;;AAWA,AAAC,WAAW,SAAiB;AAE7B,IAAI,2BAAiD;AAErD,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,SAAS,cAAc,cAAc,WAAW,KAAK,cAExG,mBAAkB,YAAY;AAC5B,KAAI;AACF,QAAM,mBAAmB;UAClB,GAAG;AACV,eAAa,6BAA6B,EAAE;AAC5C,EAAC,WAAmB,SAAS,OAAO,EAAE;;EAExC;AAGJ,SAAgB,oBAAmC;CACjD,MAAM,iBAAiB,kCAAkC,QAAQ,QAAQ;AACzE,KAAI,4BAA4B,MAAM;AACpC,6BAA2B,cAAc,qBAAqB,YAAY;AACxE,OAAI;IACF,IAAI;AACJ,QAAI,eAAe,CACjB,eAAc,EACZ,SAAS,gBACV;QAcD,eAAc;KACZ,YAbwB,MAAM,kBAAkB,qBAAqB,YAAY;MACjF,MAAM,sBAA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;OAAW,GAAE,SAAQ;OAC3D,MAAM,WAAW,eAAe,IAAI,KAAK,KAAK;AAC9C,WAAI,YAAY,KAAM,OAAM,IAAI,uBAAuB,0BAA0B,KAAK,KAAK,yCAAyC;OAEpI,MAAM,MAAM,KAAK,KAAK,MAAM,IAAI,CAAC,KAAK,IAAI;AAG1C,cAAO;QAAE;QAAU,QAFJ,YAAY,IAAI,IAAI,IAAI,SAAS,0BAA0B,KAAK,KAAK,0BAA0B,MAAM;QAEzF;QAC3B;;KAEL;IACF;GACF,CAAC,CAAC;UACI,GAAG;AACV,MAAI,aAAa,SAAS,EAAE,QAAQ,WAAW,qBAAqB,CAClE,QAAO,OAAO,MAAM,EAAE,QAAQ;AAEhC,QAAM;;AAGR,KAAI,OAAO,OAAO,SAAS,EACzB,QAAO,OAAO,MAAM,OAAO,OAAO,KAAI,MAAK,EAAE,KAAK,CAAC,KAAK,KAAK,CAAC;AAGhE,KAAI,OAAO,YAAY,SAAS,EAC9B,QAAO,OAAO,GAAG,OAAO,YAAY,GAAG,KAAK;AAE9C,QAAO,SAAS,wBAAwB"}
|
|
1
|
+
{"version":3,"file":"esbuild.js","names":[],"sources":["../../../src/utils/esbuild.tsx"],"sourcesContent":["import * as esbuild from 'esbuild-wasm/lib/browser.js';\nimport { join } from 'path';\nimport { getProcessEnv, isBrowserLike } from './env';\nimport { captureError, HexclaveAssertionError, throwErr } from \"./errors\";\nimport { createGlobalAsync } from './globals';\nimport { ignoreUnhandledRejection, runAsynchronously } from './promises';\nimport { Result } from \"./results\";\nimport { traceSpan, withTraceSpan } from './telemetry';\n\n\n// esbuild requires self property to be set, and it is not set by default in nodejs\n(globalThis.self as any) ??= globalThis as any;\n\nlet esbuildInitializePromise: Promise<void> | null = null;\n\nif (typeof process !== \"undefined\" && typeof process.exit === \"function\" && getProcessEnv(\"NODE_ENV\") === 'development') {\n // On development Node.js servers, initialize ESBuild as soon as the module is imported so we have to wait less on the first request\n runAsynchronously(async () => {\n try {\n await initializeEsbuild();\n } catch (e) {\n captureError(\"initialize-esbuild-in-dev\", e);\n }\n });\n}\n\nexport function initializeEsbuild(): Promise<void> {\n const esbuildWasmUrl = `https://unpkg.com/esbuild-wasm@${esbuild.version}/esbuild.wasm`;\n if (esbuildInitializePromise == null) {\n esbuildInitializePromise = withTraceSpan('initializeEsbuild', async () => {\n try {\n let initOptions;\n if (isBrowserLike()) {\n initOptions = {\n wasmURL: esbuildWasmUrl,\n };\n } else {\n const esbuildWasmModule = await createGlobalAsync('esbuildWasmModule', async () => {\n const esbuildWasmResponse = await fetch(esbuildWasmUrl);\n if (!esbuildWasmResponse.ok) {\n throw new HexclaveAssertionError(`Failed to fetch esbuild.wasm: ${esbuildWasmResponse.status} ${esbuildWasmResponse.statusText}: ${await esbuildWasmResponse.text()}`);\n }\n const esbuildWasm = await esbuildWasmResponse.arrayBuffer();\n const esbuildWasmArray = new Uint8Array(esbuildWasm);\n if (esbuildWasmArray[0] !== 0x00 || esbuildWasmArray[1] !== 0x61 || esbuildWasmArray[2] !== 0x73 || esbuildWasmArray[3] !== 0x6d) {\n throw new HexclaveAssertionError(`Invalid esbuild.wasm file: ${new TextDecoder().decode(esbuildWasmArray)}`);\n }\n return new WebAssembly.Module(esbuildWasm);\n });\n initOptions = {\n wasmModule: esbuildWasmModule,\n worker: false,\n };\n }\n try {\n await esbuild.initialize(initOptions);\n } catch (e) {\n if (e instanceof Error && e.message === 'Cannot call \"initialize\" more than once') {\n // this happens especially in local development, just ignore\n } else {\n throw e;\n }\n }\n } catch (e) {\n esbuildInitializePromise = null;\n throw new HexclaveAssertionError(\"Failed to initialize ESBuild\", { cause: e });\n }\n })();\n ignoreUnhandledRejection(esbuildInitializePromise);\n }\n\n return esbuildInitializePromise;\n}\n\nexport async function bundleJavaScript(sourceFiles: Record<string, string> & { '/entry.js': string }, options: {\n format?: 'iife' | 'esm' | 'cjs',\n externalPackages?: Record<string, string>,\n keepAsImports?: string[],\n sourcemap?: false | 'inline',\n allowHttpImports?: boolean,\n} = {}): Promise<Result<string, string>> {\n await initializeEsbuild();\n\n const sourceFilesMap = new Map(Object.entries(sourceFiles));\n const externalPackagesMap = new Map(Object.entries(options.externalPackages ?? {}));\n const keepAsImports = options.keepAsImports ?? [];\n\n const httpImportCache = new Map<string, { contents: string, loader: esbuild.Loader, resolveDir: string }>();\n\n const extToLoader: Map<string, esbuild.Loader> = new Map([\n ['tsx', 'tsx'],\n ['ts', 'ts'],\n ['js', 'js'],\n ['jsx', 'jsx'],\n ['json', 'json'],\n ['css', 'css'],\n ]);\n let result;\n try {\n result = await traceSpan('bundleJavaScript', async () => await esbuild.build({\n entryPoints: ['/entry.js'],\n bundle: true,\n write: false,\n format: options.format ?? 'iife',\n platform: 'browser',\n target: 'es2015',\n jsx: 'automatic',\n sourcemap: options.sourcemap ?? 'inline',\n external: keepAsImports,\n plugins: [\n ...options.allowHttpImports ? [{\n name: \"esm-sh-only\",\n setup(build: esbuild.PluginBuild) {\n // Handle absolute URLs and relative imports from esm.sh modules.\n build.onResolve({ filter: /.*/ }, (args) => {\n // Only touch absolute http(s) specifiers or children of our own namespace\n const isHttp = args.path.startsWith(\"http://\") || args.path.startsWith(\"https://\");\n const fromEsmNs = args.namespace === \"esm-sh\";\n\n if (!isHttp && !fromEsmNs) return null; // Let other plugins handle bare/relative/local\n\n // Resolve relative URLs inside esm.sh-fetched modules\n const url = new URL(args.path, fromEsmNs ? args.importer : undefined);\n\n if (url.protocol !== \"https:\" || url.host !== \"esm.sh\") {\n throw new Error(`Blocked non-esm.sh URL import: ${url.href}`);\n }\n\n return { path: url.href, namespace: \"esm-sh\" };\n });\n\n build.onLoad({ filter: /.*/, namespace: \"esm-sh\" }, async (args) => {\n if (httpImportCache.has(args.path)) return httpImportCache.get(args.path)!;\n\n const res = await fetch(args.path, { redirect: \"follow\" });\n if (!res.ok) throw new Error(`Fetch ${res.status} ${res.statusText} for ${args.path}`);\n const finalUrl = new URL(res.url);\n // Defensive: follow shouldn’t leave esm.sh, but re-check.\n if (finalUrl.host !== \"esm.sh\") {\n throw new Error(`Redirect escaped esm.sh: ${finalUrl.href}`);\n }\n\n const ct = (res.headers.get(\"content-type\") || \"\").toLowerCase();\n let loader: esbuild.Loader =\n ct.includes(\"css\") ? \"css\" :\n ct.includes(\"json\") ? \"json\" :\n ct.includes(\"typescript\") ? \"ts\" :\n ct.includes(\"jsx\") ? \"jsx\" :\n ct.includes(\"tsx\") ? \"tsx\" :\n \"js\";\n\n // Fallback by extension (esm.sh sometimes omits CT)\n const p = finalUrl.pathname;\n if (p.endsWith(\".css\")) loader = \"css\";\n else if (p.endsWith(\".json\")) loader = \"json\";\n else if (p.endsWith(\".ts\")) loader = \"ts\";\n else if (p.endsWith(\".tsx\")) loader = \"tsx\";\n else if (p.endsWith(\".jsx\")) loader = \"jsx\";\n\n const contents = await res.text();\n const result = {\n contents,\n loader,\n // Ensures relative imports inside that module resolve against the file’s URL\n resolveDir: new URL(\".\", finalUrl.href).toString(),\n watchFiles: [finalUrl.href],\n };\n httpImportCache.set(args.path, result);\n return result;\n });\n },\n } as esbuild.Plugin] : [],\n {\n name: 'replace-packages-with-globals',\n setup(build) {\n build.onResolve({ filter: /.*/ }, args => {\n // Skip packages that should remain external (not be shimmed)\n if (keepAsImports.includes(args.path)) {\n return undefined;\n }\n if (externalPackagesMap.has(args.path)) {\n return { path: args.path, namespace: 'package-shim' };\n }\n return undefined;\n });\n\n build.onLoad({ filter: /.*/, namespace: 'package-shim' }, (args) => {\n const contents = externalPackagesMap.get(args.path);\n if (contents == null) throw new HexclaveAssertionError(`esbuild requested file ${args.path} that is not in the virtual file system`);\n\n return { contents, loader: 'ts' };\n });\n },\n },\n {\n name: 'virtual-fs',\n setup(build) {\n build.onResolve({ filter: /.*/ }, args => {\n const absolutePath = join(\"/\", args.path);\n if (sourceFilesMap.has(absolutePath)) {\n return { path: absolutePath, namespace: 'virtual' };\n }\n return undefined;\n });\n\n /* 2️⃣ Load the module from the map */\n build.onLoad({ filter: /.*/, namespace: 'virtual' }, args => {\n const contents = sourceFilesMap.get(args.path);\n if (contents == null) throw new HexclaveAssertionError(`esbuild requested file ${args.path} that is not in the virtual file system`);\n\n const ext = args.path.split('.').pop() ?? '';\n const loader = extToLoader.get(ext) ?? throwErr(`esbuild requested file ${args.path} with unknown extension ${ext}`);\n\n return { contents, loader };\n });\n },\n },\n ],\n }));\n } catch (e) {\n if (e instanceof Error && e.message.startsWith(\"Build failed with \")) {\n return Result.error(e.message);\n }\n throw e;\n }\n\n if (result.errors.length > 0) {\n return Result.error(result.errors.map(e => e.text).join('\\n'));\n }\n\n if (result.outputFiles.length > 0) {\n return Result.ok(result.outputFiles[0].text);\n }\n return throwErr(\"No output generated??\");\n}\n"],"mappings":";;;;;;;;;;AAWA,AAAC,WAAW,SAAiB;AAE7B,IAAI,2BAAiD;AAErD,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,SAAS,cAAc,cAAc,WAAW,KAAK,cAExG,mBAAkB,YAAY;AAC5B,KAAI;AACF,QAAM,mBAAmB;UAClB,GAAG;AACV,eAAa,6BAA6B,EAAE;;EAE9C;AAGJ,SAAgB,oBAAmC;CACjD,MAAM,iBAAiB,kCAAkC,QAAQ,QAAQ;AACzE,KAAI,4BAA4B,MAAM;AACpC,6BAA2B,cAAc,qBAAqB,YAAY;AACxE,OAAI;IACF,IAAI;AACJ,QAAI,eAAe,CACjB,eAAc,EACZ,SAAS,gBACV;QAcD,eAAc;KACZ,YAbwB,MAAM,kBAAkB,qBAAqB,YAAY;MACjF,MAAM,sBAAsB,MAAM,MAAM,eAAe;AACvD,UAAI,CAAC,oBAAoB,GACvB,OAAM,IAAI,uBAAuB,iCAAiC,oBAAoB,OAAO,GAAG,oBAAoB,WAAW,IAAI,MAAM,oBAAoB,MAAM,GAAG;MAExK,MAAM,cAAc,MAAM,oBAAoB,aAAa;MAC3D,MAAM,mBAAmB,IAAI,WAAW,YAAY;AACpD,UAAI,iBAAiB,OAAO,KAAQ,iBAAiB,OAAO,MAAQ,iBAAiB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MAAM;QAEzF;QAC3B;;KAEL;IACF;GACF,CAAC,CAAC;UACI,GAAG;AACV,MAAI,aAAa,SAAS,EAAE,QAAQ,WAAW,qBAAqB,CAClE,QAAO,OAAO,MAAM,EAAE,QAAQ;AAEhC,QAAM;;AAGR,KAAI,OAAO,OAAO,SAAS,EACzB,QAAO,OAAO,MAAM,OAAO,OAAO,KAAI,MAAK,EAAE,KAAK,CAAC,KAAK,KAAK,CAAC;AAGhE,KAAI,OAAO,YAAY,SAAS,EAC9B,QAAO,OAAO,GAAG,OAAO,YAAY,GAAG,KAAK;AAE9C,QAAO,SAAS,wBAAwB"}
|
|
@@ -5,7 +5,7 @@ type FeaturebaseUser = {
|
|
|
5
5
|
name?: string;
|
|
6
6
|
profilePicture?: string;
|
|
7
7
|
};
|
|
8
|
-
type
|
|
8
|
+
type HexclaveAuthUser = {
|
|
9
9
|
id: string;
|
|
10
10
|
primaryEmail: string | null;
|
|
11
11
|
displayName?: string | null;
|
|
@@ -19,12 +19,12 @@ type StackAuthUser = {
|
|
|
19
19
|
* 3. We handle email conflicts by using fallback emails
|
|
20
20
|
* 4. We update profile information when needed
|
|
21
21
|
*/
|
|
22
|
-
declare function getOrCreateFeaturebaseUser(
|
|
22
|
+
declare function getOrCreateFeaturebaseUser(hexclaveAuthUser: HexclaveAuthUser, options?: {
|
|
23
23
|
apiKey?: string;
|
|
24
24
|
}): Promise<{
|
|
25
25
|
userId: string;
|
|
26
26
|
email: string;
|
|
27
27
|
}>;
|
|
28
28
|
//#endregion
|
|
29
|
-
export { FeaturebaseUser,
|
|
29
|
+
export { FeaturebaseUser, HexclaveAuthUser, getOrCreateFeaturebaseUser };
|
|
30
30
|
//# sourceMappingURL=featurebase.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"featurebase.d.ts","names":[],"sources":["../../../src/utils/featurebase.tsx"],"mappings":";KAGY,eAAA;EACV,MAAA;EACA,KAAA;EACA,IAAA;EACA,cAAA;AAAA;AAAA,KAGU,
|
|
1
|
+
{"version":3,"file":"featurebase.d.ts","names":[],"sources":["../../../src/utils/featurebase.tsx"],"mappings":";KAGY,eAAA;EACV,MAAA;EACA,KAAA;EACA,IAAA;EACA,cAAA;AAAA;AAAA,KAGU,gBAAA;EACV,EAAA;EACA,YAAA;EACA,WAAA;EACA,eAAA;AAAA;;;;;;;;;iBAgKoB,0BAAA,CACpB,gBAAA,EAAkB,gBAAA,EAClB,OAAA;EAAY,MAAA;AAAA,IACX,OAAA;EAAU,MAAA;EAAgB,KAAA;AAAA"}
|
|
@@ -5,9 +5,9 @@ import { getEnvVariable } from "./env.js";
|
|
|
5
5
|
/**
|
|
6
6
|
* Find a Featurebase user by their Hexclave user ID
|
|
7
7
|
*/
|
|
8
|
-
async function findFeaturebaseUserById(
|
|
8
|
+
async function findFeaturebaseUserById(hexclaveAuthUserId, apiKey) {
|
|
9
9
|
try {
|
|
10
|
-
const response = await fetch(`https://do.featurebase.app/v2/organization/identifyUser?id=${
|
|
10
|
+
const response = await fetch(`https://do.featurebase.app/v2/organization/identifyUser?id=${hexclaveAuthUserId}`, {
|
|
11
11
|
method: "GET",
|
|
12
12
|
headers: { "X-API-Key": apiKey }
|
|
13
13
|
});
|
|
@@ -15,9 +15,9 @@ async function findFeaturebaseUserById(stackAuthUserId, apiKey) {
|
|
|
15
15
|
if (!response.ok) throw new HexclaveAssertionError(`Failed to find Featurebase user by ID: ${response.statusText}`);
|
|
16
16
|
const data = await response.json();
|
|
17
17
|
const user = data.user;
|
|
18
|
-
if (!user) throw new HexclaveAssertionError(`Featurebase API returned success but no user data for ID: ${
|
|
18
|
+
if (!user) throw new HexclaveAssertionError(`Featurebase API returned success but no user data for ID: ${hexclaveAuthUserId}`, { data });
|
|
19
19
|
return {
|
|
20
|
-
userId: user.externalUserId || user.userId ||
|
|
20
|
+
userId: user.externalUserId || user.userId || hexclaveAuthUserId,
|
|
21
21
|
email: user.email,
|
|
22
22
|
name: user.name,
|
|
23
23
|
profilePicture: user.profilePicture
|
|
@@ -117,18 +117,18 @@ async function updateFeaturebaseUser(userId, updates, apiKey) {
|
|
|
117
117
|
* 3. We handle email conflicts by using fallback emails
|
|
118
118
|
* 4. We update profile information when needed
|
|
119
119
|
*/
|
|
120
|
-
async function getOrCreateFeaturebaseUser(
|
|
120
|
+
async function getOrCreateFeaturebaseUser(hexclaveAuthUser, options) {
|
|
121
121
|
const apiKey = options?.apiKey || getEnvVariable("STACK_FEATUREBASE_API_KEY");
|
|
122
|
-
const fallbackEmail = `${
|
|
123
|
-
const existingById = await findFeaturebaseUserById(
|
|
122
|
+
const fallbackEmail = `${hexclaveAuthUser.id}@featurebase-user.stack-auth-app.com`;
|
|
123
|
+
const existingById = await findFeaturebaseUserById(hexclaveAuthUser.id, apiKey);
|
|
124
124
|
if (existingById) {
|
|
125
125
|
let ensuredEmail = existingById.email;
|
|
126
126
|
if (!ensuredEmail) try {
|
|
127
127
|
await createFeaturebaseUser({
|
|
128
128
|
userId: existingById.userId,
|
|
129
129
|
email: fallbackEmail,
|
|
130
|
-
name:
|
|
131
|
-
profilePicture:
|
|
130
|
+
name: hexclaveAuthUser.displayName || void 0,
|
|
131
|
+
profilePicture: hexclaveAuthUser.profileImageUrl || void 0
|
|
132
132
|
}, apiKey);
|
|
133
133
|
ensuredEmail = fallbackEmail;
|
|
134
134
|
} catch (e) {
|
|
@@ -136,8 +136,8 @@ async function getOrCreateFeaturebaseUser(stackAuthUser, options) {
|
|
|
136
136
|
}
|
|
137
137
|
try {
|
|
138
138
|
const updates = {};
|
|
139
|
-
if (
|
|
140
|
-
if (
|
|
139
|
+
if (hexclaveAuthUser.displayName && hexclaveAuthUser.displayName !== existingById.name) updates.name = hexclaveAuthUser.displayName;
|
|
140
|
+
if (hexclaveAuthUser.profileImageUrl && hexclaveAuthUser.profileImageUrl !== existingById.profilePicture) updates.profilePicture = hexclaveAuthUser.profileImageUrl;
|
|
141
141
|
if (Object.keys(updates).length > 0) await updateFeaturebaseUser(existingById.userId, updates, apiKey);
|
|
142
142
|
} catch (error) {
|
|
143
143
|
console.error("Failed to update existing Featurebase user profile:", error);
|
|
@@ -147,13 +147,13 @@ async function getOrCreateFeaturebaseUser(stackAuthUser, options) {
|
|
|
147
147
|
email: ensuredEmail
|
|
148
148
|
};
|
|
149
149
|
}
|
|
150
|
-
const candidateEmail =
|
|
150
|
+
const candidateEmail = hexclaveAuthUser.primaryEmail ?? fallbackEmail;
|
|
151
151
|
const safeEmail = await findFeaturebaseUserByEmail(candidateEmail, apiKey) ? fallbackEmail : candidateEmail;
|
|
152
152
|
const created = await createFeaturebaseUser({
|
|
153
|
-
userId:
|
|
153
|
+
userId: hexclaveAuthUser.id,
|
|
154
154
|
email: safeEmail,
|
|
155
|
-
name:
|
|
156
|
-
profilePicture:
|
|
155
|
+
name: hexclaveAuthUser.displayName || hexclaveAuthUser.primaryEmail?.split("@")[0] || "User",
|
|
156
|
+
profilePicture: hexclaveAuthUser.profileImageUrl || void 0
|
|
157
157
|
}, apiKey);
|
|
158
158
|
return {
|
|
159
159
|
userId: created.userId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"featurebase.js","names":[],"sources":["../../../src/utils/featurebase.tsx"],"sourcesContent":["import { getEnvVariable } from \"./env\";\nimport { HexclaveAssertionError } from \"./errors\";\n\nexport type FeaturebaseUser = {\n userId: string,\n email: string,\n name?: string,\n profilePicture?: string,\n};\n\nexport type StackAuthUser = {\n id: string,\n primaryEmail: string | null,\n displayName?: string | null,\n profileImageUrl?: string | null,\n};\n\n/**\n * Find a Featurebase user by their Hexclave user ID\n */\nasync function findFeaturebaseUserById(stackAuthUserId: string, apiKey: string): Promise<FeaturebaseUser | null> {\n try {\n const response = await fetch(`https://do.featurebase.app/v2/organization/identifyUser?id=${stackAuthUserId}`, {\n method: 'GET',\n headers: {\n 'X-API-Key': apiKey,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n throw new HexclaveAssertionError(`Failed to find Featurebase user by ID: ${response.statusText}`);\n }\n\n const data = await response.json();\n const user = data.user;\n\n if (!user) {\n throw new HexclaveAssertionError(`Featurebase API returned success but no user data for ID: ${stackAuthUserId}`, { data });\n }\n\n return {\n userId: user.externalUserId || user.userId || stackAuthUserId,\n email: user.email,\n name: user.name,\n profilePicture: user.profilePicture,\n };\n } catch (error) {\n if (error instanceof HexclaveAssertionError) {\n throw error;\n }\n throw new HexclaveAssertionError(\"Failed to find Featurebase user by ID\", { cause: error });\n }\n}\n\n/**\n * Find a Featurebase user by their email address\n */\nasync function findFeaturebaseUserByEmail(email: string, apiKey: string): Promise<FeaturebaseUser | null> {\n try {\n const response = await fetch(`https://do.featurebase.app/v2/organization/identifyUser?email=${encodeURIComponent(email)}`, {\n method: 'GET',\n headers: {\n 'X-API-Key': apiKey,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n throw new HexclaveAssertionError(`Failed to find Featurebase user by email: ${response.statusText}`);\n }\n\n const data = await response.json();\n const user = data.user;\n\n if (!user) {\n throw new HexclaveAssertionError(`Featurebase API returned success but no user data for email: ${email}`, { data });\n }\n\n return {\n userId: user.externalUserId || user.userId,\n email: user.email,\n name: user.name,\n profilePicture: user.profilePicture,\n };\n } catch (error) {\n console.error('Error finding Featurebase user by email:', error);\n return null;\n }\n}\n\n/**\n * Create a new Featurebase user using the identifyUser endpoint\n */\nasync function createFeaturebaseUser(user: FeaturebaseUser, apiKey: string): Promise<FeaturebaseUser> {\n try {\n const response = await fetch('https://do.featurebase.app/v2/organization/identifyUser', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify({\n userId: user.userId,\n email: user.email,\n name: user.name,\n profilePicture: user.profilePicture,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new HexclaveAssertionError(`Failed to create Featurebase user: ${errorData.error || response.statusText}`, { errorData });\n }\n\n // The identifyUser endpoint just returns { \"success\": true }, so we return the input data\n return user;\n } catch (error) {\n if (error instanceof HexclaveAssertionError) {\n throw error;\n }\n throw new HexclaveAssertionError(\"Failed to create Featurebase user\", { cause: error });\n\n }\n}\n\n/**\n * Update an existing Featurebase user (excluding email)\n */\nasync function updateFeaturebaseUser(userId: string, updates: Partial<Omit<FeaturebaseUser, 'userId' | 'email'>>, apiKey: string): Promise<FeaturebaseUser> {\n try {\n const response = await fetch(`https://do.featurebase.app/v2/users/${userId}`, {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(updates),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new HexclaveAssertionError(`Failed to update Featurebase user: ${errorData.error || response.statusText}`, { errorData });\n }\n\n const data = await response.json();\n return {\n userId: data.userId || userId,\n email: data.email,\n name: data.name,\n profilePicture: data.profilePicture,\n };\n } catch (error) {\n if (error instanceof HexclaveAssertionError) {\n throw error;\n }\n throw new HexclaveAssertionError(\"Failed to update Featurebase user\", { cause: error });\n }\n}\n\n/**\n * Get or create a Featurebase user based on Hexclave user data.\n * This function ensures that:\n * 1. We never change a user's email address on Featurebase\n * 2. We use Hexclave user ID as the primary identifier\n * 3. We handle email conflicts by using fallback emails\n * 4. We update profile information when needed\n */\nexport async function getOrCreateFeaturebaseUser(\n stackAuthUser: StackAuthUser,\n options?: { apiKey?: string }\n): Promise<{ userId: string, email: string }> {\n const apiKey = options?.apiKey || getEnvVariable(\"STACK_FEATUREBASE_API_KEY\");\n const fallbackEmail = `${stackAuthUser.id}@featurebase-user.stack-auth-app.com`;\n\n // First, try to find existing user by Hexclave user ID\n const existingById = await findFeaturebaseUserById(stackAuthUser.id, apiKey);\n if (existingById) {\n // Ensure the user has an email on Featurebase.\n let ensuredEmail = existingById.email;\n if (!ensuredEmail) {\n try {\n await createFeaturebaseUser({\n userId: existingById.userId,\n email: fallbackEmail,\n name: stackAuthUser.displayName || undefined,\n profilePicture: stackAuthUser.profileImageUrl || undefined,\n }, apiKey);\n ensuredEmail = fallbackEmail;\n } catch (e) {\n // If setting fallback email failed, keep ensuredEmail as-is (undefined) and let callers handle\n throw new HexclaveAssertionError(`Failed to set fallback email for existing Featurebase user ${existingById.userId}`, { cause: e });\n }\n }\n\n // Update profile information if needed (but not email)\n try {\n const updates: Partial<Omit<FeaturebaseUser, 'userId' | 'email'>> = {};\n\n if (stackAuthUser.displayName && stackAuthUser.displayName !== existingById.name) {\n updates.name = stackAuthUser.displayName;\n }\n\n if (stackAuthUser.profileImageUrl && stackAuthUser.profileImageUrl !== existingById.profilePicture) {\n updates.profilePicture = stackAuthUser.profileImageUrl;\n }\n\n if (Object.keys(updates).length > 0) {\n await updateFeaturebaseUser(existingById.userId, updates, apiKey);\n }\n } catch (error) {\n console.error('Failed to update existing Featurebase user profile:', error);\n // Continue with existing user data even if update fails\n }\n\n return {\n userId: existingById.userId,\n email: ensuredEmail,\n };\n }\n\n // No existing user found by ID, need to create one\n const candidateEmail = stackAuthUser.primaryEmail ?? fallbackEmail;\n\n // Check if someone already has this email on Featurebase\n const existingByEmail = await findFeaturebaseUserByEmail(candidateEmail, apiKey);\n const safeEmail = existingByEmail ? fallbackEmail : candidateEmail;\n\n // Create new user\n const created = await createFeaturebaseUser({\n userId: stackAuthUser.id,\n email: safeEmail,\n name: stackAuthUser.displayName || stackAuthUser.primaryEmail?.split('@')[0] || 'User',\n profilePicture: stackAuthUser.profileImageUrl || undefined,\n }, apiKey);\n\n return {\n userId: created.userId,\n email: created.email,\n };\n}\n"],"mappings":";;;;;;;AAoBA,eAAe,wBAAwB,iBAAyB,QAAiD;AAC/G,KAAI;EACF,MAAM,WAAW,MAAM,MAAM,8DAA8D,mBAAmB;GAC5G,QAAQ;GACR,SAAS,EACP,aAAa,QACd;GACF,CAAC;AAEF,MAAI,SAAS,WAAW,IACtB,QAAO;AAGT,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,uBAAuB,0CAA0C,SAAS,aAAa;EAGnG,MAAM,OAAO,M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,SAAM,IAAI,uBAAuB,8DAA8D,aAAa,UAAU,EAAE,OAAO,GAAG,CAAC;;AAKvI,MAAI;GACF,MAAM,UAA8D,EAAE;AAEtE,OAAI,cAAc,eAAe,cAAc,gBAAgB,aAAa,KAC1E,SAAQ,OAAO,cAAc;AAG/B,OAAI,cAAc,mBAAmB,cAAc,oBAAoB,aAAa,eAClF,SAAQ,iBAAiB,cAAc;AAGzC,OAAI,OAAO,KAAK,QAAQ,CAAC,SAAS,EAChC,OAAM,sBAAsB,aAAa,QAAQ,SAAS,OAAO;WAE5D,OAAO;AACd,WAAQ,MAAM,uDAAuD,MAAM;;AAI7E,SAAO;GACL,QAAQ,aAAa;GACrB,OAAO;GACR;;CAIH,MAAM,iBAAiB,cAAc,gBAAgB;CAIrD,MAAM,YADkB,MAAM,2BAA2B,gBAAgB,OAAO,GAC5C,gBAAgB;CAGpD,MAAM,UAAU,MAAM,sBAAsB;EAC1C,QAAQ,cAAc;EACtB,OAAO;EACP,MAAM,cAAc,eAAe,cAAc,cAAc,MAAM,IAAI,CAAC,MAAM;EAChF,gBAAgB,cAAc,mBAAmB;EAClD,EAAE,OAAO;AAEV,QAAO;EACL,QAAQ,QAAQ;EAChB,OAAO,QAAQ;EAChB"}
|
|
1
|
+
{"version":3,"file":"featurebase.js","names":[],"sources":["../../../src/utils/featurebase.tsx"],"sourcesContent":["import { getEnvVariable } from \"./env\";\nimport { HexclaveAssertionError } from \"./errors\";\n\nexport type FeaturebaseUser = {\n userId: string,\n email: string,\n name?: string,\n profilePicture?: string,\n};\n\nexport type HexclaveAuthUser = {\n id: string,\n primaryEmail: string | null,\n displayName?: string | null,\n profileImageUrl?: string | null,\n};\n\n/**\n * Find a Featurebase user by their Hexclave user ID\n */\nasync function findFeaturebaseUserById(hexclaveAuthUserId: string, apiKey: string): Promise<FeaturebaseUser | null> {\n try {\n const response = await fetch(`https://do.featurebase.app/v2/organization/identifyUser?id=${hexclaveAuthUserId}`, {\n method: 'GET',\n headers: {\n 'X-API-Key': apiKey,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n throw new HexclaveAssertionError(`Failed to find Featurebase user by ID: ${response.statusText}`);\n }\n\n const data = await response.json();\n const user = data.user;\n\n if (!user) {\n throw new HexclaveAssertionError(`Featurebase API returned success but no user data for ID: ${hexclaveAuthUserId}`, { data });\n }\n\n return {\n userId: user.externalUserId || user.userId || hexclaveAuthUserId,\n email: user.email,\n name: user.name,\n profilePicture: user.profilePicture,\n };\n } catch (error) {\n if (error instanceof HexclaveAssertionError) {\n throw error;\n }\n throw new HexclaveAssertionError(\"Failed to find Featurebase user by ID\", { cause: error });\n }\n}\n\n/**\n * Find a Featurebase user by their email address\n */\nasync function findFeaturebaseUserByEmail(email: string, apiKey: string): Promise<FeaturebaseUser | null> {\n try {\n const response = await fetch(`https://do.featurebase.app/v2/organization/identifyUser?email=${encodeURIComponent(email)}`, {\n method: 'GET',\n headers: {\n 'X-API-Key': apiKey,\n },\n });\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n throw new HexclaveAssertionError(`Failed to find Featurebase user by email: ${response.statusText}`);\n }\n\n const data = await response.json();\n const user = data.user;\n\n if (!user) {\n throw new HexclaveAssertionError(`Featurebase API returned success but no user data for email: ${email}`, { data });\n }\n\n return {\n userId: user.externalUserId || user.userId,\n email: user.email,\n name: user.name,\n profilePicture: user.profilePicture,\n };\n } catch (error) {\n console.error('Error finding Featurebase user by email:', error);\n return null;\n }\n}\n\n/**\n * Create a new Featurebase user using the identifyUser endpoint\n */\nasync function createFeaturebaseUser(user: FeaturebaseUser, apiKey: string): Promise<FeaturebaseUser> {\n try {\n const response = await fetch('https://do.featurebase.app/v2/organization/identifyUser', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify({\n userId: user.userId,\n email: user.email,\n name: user.name,\n profilePicture: user.profilePicture,\n }),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new HexclaveAssertionError(`Failed to create Featurebase user: ${errorData.error || response.statusText}`, { errorData });\n }\n\n // The identifyUser endpoint just returns { \"success\": true }, so we return the input data\n return user;\n } catch (error) {\n if (error instanceof HexclaveAssertionError) {\n throw error;\n }\n throw new HexclaveAssertionError(\"Failed to create Featurebase user\", { cause: error });\n\n }\n}\n\n/**\n * Update an existing Featurebase user (excluding email)\n */\nasync function updateFeaturebaseUser(userId: string, updates: Partial<Omit<FeaturebaseUser, 'userId' | 'email'>>, apiKey: string): Promise<FeaturebaseUser> {\n try {\n const response = await fetch(`https://do.featurebase.app/v2/users/${userId}`, {\n method: 'PATCH',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(updates),\n });\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}));\n throw new HexclaveAssertionError(`Failed to update Featurebase user: ${errorData.error || response.statusText}`, { errorData });\n }\n\n const data = await response.json();\n return {\n userId: data.userId || userId,\n email: data.email,\n name: data.name,\n profilePicture: data.profilePicture,\n };\n } catch (error) {\n if (error instanceof HexclaveAssertionError) {\n throw error;\n }\n throw new HexclaveAssertionError(\"Failed to update Featurebase user\", { cause: error });\n }\n}\n\n/**\n * Get or create a Featurebase user based on Hexclave user data.\n * This function ensures that:\n * 1. We never change a user's email address on Featurebase\n * 2. We use Hexclave user ID as the primary identifier\n * 3. We handle email conflicts by using fallback emails\n * 4. We update profile information when needed\n */\nexport async function getOrCreateFeaturebaseUser(\n hexclaveAuthUser: HexclaveAuthUser,\n options?: { apiKey?: string }\n): Promise<{ userId: string, email: string }> {\n const apiKey = options?.apiKey || getEnvVariable(\"STACK_FEATUREBASE_API_KEY\");\n const fallbackEmail = `${hexclaveAuthUser.id}@featurebase-user.stack-auth-app.com`;\n\n // First, try to find existing user by Hexclave user ID\n const existingById = await findFeaturebaseUserById(hexclaveAuthUser.id, apiKey);\n if (existingById) {\n // Ensure the user has an email on Featurebase.\n let ensuredEmail = existingById.email;\n if (!ensuredEmail) {\n try {\n await createFeaturebaseUser({\n userId: existingById.userId,\n email: fallbackEmail,\n name: hexclaveAuthUser.displayName || undefined,\n profilePicture: hexclaveAuthUser.profileImageUrl || undefined,\n }, apiKey);\n ensuredEmail = fallbackEmail;\n } catch (e) {\n // If setting fallback email failed, keep ensuredEmail as-is (undefined) and let callers handle\n throw new HexclaveAssertionError(`Failed to set fallback email for existing Featurebase user ${existingById.userId}`, { cause: e });\n }\n }\n\n // Update profile information if needed (but not email)\n try {\n const updates: Partial<Omit<FeaturebaseUser, 'userId' | 'email'>> = {};\n\n if (hexclaveAuthUser.displayName && hexclaveAuthUser.displayName !== existingById.name) {\n updates.name = hexclaveAuthUser.displayName;\n }\n\n if (hexclaveAuthUser.profileImageUrl && hexclaveAuthUser.profileImageUrl !== existingById.profilePicture) {\n updates.profilePicture = hexclaveAuthUser.profileImageUrl;\n }\n\n if (Object.keys(updates).length > 0) {\n await updateFeaturebaseUser(existingById.userId, updates, apiKey);\n }\n } catch (error) {\n console.error('Failed to update existing Featurebase user profile:', error);\n // Continue with existing user data even if update fails\n }\n\n return {\n userId: existingById.userId,\n email: ensuredEmail,\n };\n }\n\n // No existing user found by ID, need to create one\n const candidateEmail = hexclaveAuthUser.primaryEmail ?? fallbackEmail;\n\n // Check if someone already has this email on Featurebase\n const existingByEmail = await findFeaturebaseUserByEmail(candidateEmail, apiKey);\n const safeEmail = existingByEmail ? fallbackEmail : candidateEmail;\n\n // Create new user\n const created = await createFeaturebaseUser({\n userId: hexclaveAuthUser.id,\n email: safeEmail,\n name: hexclaveAuthUser.displayName || hexclaveAuthUser.primaryEmail?.split('@')[0] || 'User',\n profilePicture: hexclaveAuthUser.profileImageUrl || undefined,\n }, apiKey);\n\n return {\n userId: created.userId,\n email: created.email,\n };\n}\n"],"mappings":";;;;;;;AAoBA,eAAe,wBAAwB,oBAA4B,QAAiD;AAClH,KAAI;EACF,MAAM,WAAW,MAAM,MAAM,8DAA8D,sBAAsB;GAC/G,Q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AChC,MAAI,CAAC,aACH,KAAI;AACF,SAAM,sBAAsB;IAC1B,QAAQ,aAAa;IACrB,OAAO;IACP,MAAM,iBAAiB,eAAe;IACtC,gBAAgB,iBAAiB,mBAAmB;IACrD,EAAE,OAAO;AACV,kBAAe;WACR,GAAG;AAEV,SAAM,IAAI,uBAAuB,8DAA8D,aAAa,UAAU,EAAE,OAAO,GAAG,CAAC;;AAKvI,MAAI;GACF,MAAM,UAA8D,EAAE;AAEtE,OAAI,iBAAiB,eAAe,iBAAiB,gBAAgB,aAAa,KAChF,SAAQ,OAAO,iBAAiB;AAGlC,OAAI,iBAAiB,mBAAmB,iBAAiB,oBAAoB,aAAa,eACxF,SAAQ,iBAAiB,iBAAiB;AAG5C,OAAI,OAAO,KAAK,QAAQ,CAAC,SAAS,EAChC,OAAM,sBAAsB,aAAa,QAAQ,SAAS,OAAO;WAE5D,OAAO;AACd,WAAQ,MAAM,uDAAuD,MAAM;;AAI7E,SAAO;GACL,QAAQ,aAAa;GACrB,OAAO;GACR;;CAIH,MAAM,iBAAiB,iBAAiB,gBAAgB;CAIxD,MAAM,YADkB,MAAM,2BAA2B,gBAAgB,OAAO,GAC5C,gBAAgB;CAGpD,MAAM,UAAU,MAAM,sBAAsB;EAC1C,QAAQ,iBAAiB;EACzB,OAAO;EACP,MAAM,iBAAiB,eAAe,iBAAiB,cAAc,MAAM,IAAI,CAAC,MAAM;EACtF,gBAAgB,iBAAiB,mBAAmB;EACrD,EAAE,OAAO;AAEV,QAAO;EACL,QAAQ,QAAQ;EAChB,OAAO,QAAQ;EAChB"}
|
package/dist/esm/utils/fs.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as hexclaveFs from "fs";
|
|
2
2
|
import * as path$1 from "path";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/fs.tsx
|
|
5
5
|
async function list(path) {
|
|
6
|
-
return await
|
|
6
|
+
return await hexclaveFs.promises.readdir(path);
|
|
7
7
|
}
|
|
8
8
|
async function listRecursively(p, options = {}) {
|
|
9
9
|
const files = await list(p);
|
|
10
10
|
return [...(await Promise.all(files.map(async (fileName) => {
|
|
11
11
|
const filePath = path$1.join(p, fileName);
|
|
12
|
-
if ((await
|
|
12
|
+
if ((await hexclaveFs.promises.stat(filePath)).isDirectory()) return [...await listRecursively(filePath, options), ...options.excludeDirectories ? [] : [filePath]];
|
|
13
13
|
else return [filePath];
|
|
14
14
|
}))).flat()];
|
|
15
15
|
}
|
|
16
16
|
function writeFileSyncIfChanged(path, content) {
|
|
17
|
-
if (
|
|
18
|
-
if (
|
|
17
|
+
if (hexclaveFs.existsSync(path)) {
|
|
18
|
+
if (hexclaveFs.readFileSync(path, "utf-8") === content) return;
|
|
19
19
|
}
|
|
20
|
-
|
|
20
|
+
hexclaveFs.writeFileSync(path, content);
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
//#endregion
|
package/dist/esm/utils/fs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fs.js","names":["path"],"sources":["../../../src/utils/fs.tsx"],"sourcesContent":["import * as
|
|
1
|
+
{"version":3,"file":"fs.js","names":["path"],"sources":["../../../src/utils/fs.tsx"],"sourcesContent":["import * as hexclaveFs from \"fs\";\nimport * as path from \"path\";\n\nexport async function list(path: string) {\n return await hexclaveFs.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 hexclaveFs.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 (hexclaveFs.existsSync(path)) {\n const existingContent = hexclaveFs.readFileSync(path, \"utf-8\");\n if (existingContent === content) {\n return;\n }\n }\n hexclaveFs.writeFileSync(path, content);\n}\n"],"mappings":";;;;AAGA,eAAsB,KAAK,MAAc;AACvC,QAAO,MAAM,WAAW,SAAS,QAAQ,KAAK;;AAGhD,eAAsB,gBAAgB,GAAW,UAA4C,EAAE,EAAqB;CAClH,MAAM,QAAQ,MAAM,KAAK,EAAE;AAC3B,QAAO,CACL,IAAI,MAAM,QAAQ,IAAI,MAAM,IAAI,OAAO,aAAa;EAClD,MAAM,WAAWA,OAAK,KAAK,GAAG,SAAS;AACvC,OAAK,MAAM,WAAW,SAAS,KAAK,SAAS,EAAE,aAAa,CAC1D,QAAO,CACL,GAAI,MAAM,gBAAgB,UAAU,QAAQ,EAC5C,GAAI,QAAQ,qBAAqB,EAAE,GAAG,CAAC,SAAS,CACjD;MAED,QAAO,CAAC,SAAS;GAEnB,CAAC,EAAE,MAAM,CACZ;;AAGH,SAAgB,uBAAuB,MAAc,SAAuB;AAC1E,KAAI,WAAW,WAAW,KAAK,EAE7B;MADwB,WAAW,aAAa,MAAM,QAAQ,KACtC,QACtB;;AAGJ,YAAW,cAAc,MAAM,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"globals.d.ts","names":[],"sources":["../../../src/utils/globals.tsx"],"mappings":";cAAM,SAAA;AAAA,iBAkBU,YAAA,GAAA,CAAgB,GAAA,UAAa,IAAA,QAAY,CAAA,
|
|
1
|
+
{"version":3,"file":"globals.d.ts","names":[],"sources":["../../../src/utils/globals.tsx"],"mappings":";cAAM,SAAA;AAAA,iBAkBU,YAAA,GAAA,CAAgB,GAAA,UAAa,IAAA,QAAY,CAAA,GAIP,CAAA;;;;AAJlD;iBAWgB,iBAAA,GAAA,CAAqB,GAAA,UAAa,IAAA,QAAY,OAAA,CAAQ,CAAA,IAAK,OAAA,CAAQ,CAAA;AAAA,iBAYnE,SAAA,CAAU,GAAA;AAAA,iBAIV,SAAA,CAAU,GAAA,UAAa,KAAA"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
//#region src/utils/globals.tsx
|
|
2
2
|
const globalVar = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {};
|
|
3
3
|
if (typeof globalThis === "undefined") globalVar.globalThis = globalVar;
|
|
4
|
-
const
|
|
5
|
-
globalVar[
|
|
4
|
+
const hexclaveGlobalsSymbol = Symbol.for("__hexclave-globals");
|
|
5
|
+
globalVar[hexclaveGlobalsSymbol] ??= {};
|
|
6
6
|
function createGlobal(key, init) {
|
|
7
|
-
if (!globalVar[
|
|
8
|
-
return globalVar[
|
|
7
|
+
if (!globalVar[hexclaveGlobalsSymbol][key]) globalVar[hexclaveGlobalsSymbol][key] = init();
|
|
8
|
+
return globalVar[hexclaveGlobalsSymbol][key];
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
11
|
* Like createGlobal, but if the asynchronous initialization fails, the global will be reset and recomputed on the next
|
|
@@ -13,20 +13,20 @@ function createGlobal(key, init) {
|
|
|
13
13
|
*/
|
|
14
14
|
function createGlobalAsync(key, init) {
|
|
15
15
|
let promise = null;
|
|
16
|
-
if (!globalVar[
|
|
16
|
+
if (!globalVar[hexclaveGlobalsSymbol][key]) {
|
|
17
17
|
promise = init().catch((e) => {
|
|
18
|
-
delete globalVar[
|
|
18
|
+
delete globalVar[hexclaveGlobalsSymbol][key];
|
|
19
19
|
throw e;
|
|
20
20
|
});
|
|
21
|
-
globalVar[
|
|
21
|
+
globalVar[hexclaveGlobalsSymbol][key] = promise;
|
|
22
22
|
}
|
|
23
|
-
return promise ?? globalVar[
|
|
23
|
+
return promise ?? globalVar[hexclaveGlobalsSymbol][key];
|
|
24
24
|
}
|
|
25
25
|
function getGlobal(key) {
|
|
26
|
-
return globalVar[
|
|
26
|
+
return globalVar[hexclaveGlobalsSymbol][key];
|
|
27
27
|
}
|
|
28
28
|
function setGlobal(key, value) {
|
|
29
|
-
globalVar[
|
|
29
|
+
globalVar[hexclaveGlobalsSymbol][key] = value;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"globals.js","names":[],"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\n// Hexclave rebrand: file-private symbol key, renamed outright (no cross-version compat needed).\nconst
|
|
1
|
+
{"version":3,"file":"globals.js","names":[],"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\n// Hexclave rebrand: file-private symbol key, renamed outright (no cross-version compat needed).\nconst hexclaveGlobalsSymbol = Symbol.for('__hexclave-globals');\nglobalVar[hexclaveGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[hexclaveGlobalsSymbol][key]) {\n globalVar[hexclaveGlobalsSymbol][key] = init();\n }\n return globalVar[hexclaveGlobalsSymbol][key] as T;\n}\n\n/**\n * Like createGlobal, but if the asynchronous initialization fails, the global will be reset and recomputed on the next\n * invocation.\n */\nexport function createGlobalAsync<T>(key: string, init: () => Promise<T>): Promise<T> {\n let promise: Promise<T> | null = null;\n if (!globalVar[hexclaveGlobalsSymbol][key]) {\n promise = init().catch((e) => {\n delete globalVar[hexclaveGlobalsSymbol][key];\n throw e;\n });\n globalVar[hexclaveGlobalsSymbol][key] = promise;\n }\n return promise ?? globalVar[hexclaveGlobalsSymbol][key] as Promise<T>;\n}\n\nexport function getGlobal(key: string): any {\n return globalVar[hexclaveGlobalsSymbol][key];\n}\n\nexport function setGlobal(key: string, value: any) {\n globalVar[hexclaveGlobalsSymbol][key] = value;\n}\n"],"mappings":";AAAA,MAAM,YACJ,OAAO,eAAe,cAAc,aAClC,OAAO,WAAW,cAAc,SAC9B,OAAO,WAAW,cAAc,SAC9B,OAAO,SAAS,cAAc,OAC5B,EAAE;AAKZ,IAAI,OAAO,eAAe,YACxB,CAAC,UAAkB,aAAa;AAIlC,MAAM,wBAAwB,OAAO,IAAI,qBAAqB;AAC9D,UAAU,2BAA2B,EAAE;AAEvC,SAAgB,aAAgB,KAAa,MAAe;AAC1D,KAAI,CAAC,UAAU,uBAAuB,KACpC,WAAU,uBAAuB,OAAO,MAAM;AAEhD,QAAO,UAAU,uBAAuB;;;;;;AAO1C,SAAgB,kBAAqB,KAAa,MAAoC;CACpF,IAAI,UAA6B;AACjC,KAAI,CAAC,UAAU,uBAAuB,MAAM;AAC1C,YAAU,MAAM,CAAC,OAAO,MAAM;AAC5B,UAAO,UAAU,uBAAuB;AACxC,SAAM;IACN;AACF,YAAU,uBAAuB,OAAO;;AAE1C,QAAO,WAAW,UAAU,uBAAuB;;AAGrD,SAAgB,UAAU,KAAkB;AAC1C,QAAO,UAAU,uBAAuB;;AAG1C,SAAgB,UAAU,KAAa,OAAY;AACjD,WAAU,uBAAuB,OAAO"}
|