@capxul/observability 1.2.3 → 2.0.1
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/engineering.d.mts +1 -2
- package/dist/engineering.mjs +0 -2
- package/dist/index.d.mts +404 -1159
- package/dist/index.mjs +101 -383
- package/package.json +6 -3
- package/dist/engineering.d.mts.map +0 -1
- package/dist/engineering.mjs.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/engineering.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"engineering.mjs","names":[],"sources":["../src/engineering.ts"],"sourcesContent":["import { Cause, Effect, Exit, Layer, Tracer } from \"effect\";\nimport { FetchHttpClient, Headers, HttpClient } from \"effect/unstable/http\";\n// Effect v4 deliberately marks the OTLP exporters unstable. This module is the\n// one quarantine seam: no producer imports these modules directly.\nimport {\n OtlpExporter,\n OtlpLogger,\n OtlpSerialization,\n OtlpTracer,\n} from \"effect/unstable/observability\";\n\nexport type EngineeringProducer = \"browser\" | \"server\";\nexport type EngineeringCapxulEnv = \"development\" | \"e2e\" | \"staging\" | \"production\";\n\nexport interface EngineeringTelemetryConfig {\n readonly host: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly capxulEnv: EngineeringCapxulEnv;\n readonly producer: EngineeringProducer;\n readonly sdkVersion: string;\n readonly serviceName?: string;\n}\n\nconst SAFE_TRACED_HEADER_NAMES = [\n \"content-length\",\n \"content-type\",\n \"traceparent\",\n \"tracestate\",\n \"x-request-id\",\n] as const;\n\nconst ENGINEERING_REDACTED_HEADER_NAMES: ReadonlyArray<string | RegExp> = Object.freeze([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n /auth|email|key|otp|secret|session|token|wallet/i,\n]);\n\nexport const traceHeaderFilter = (name: string): boolean =>\n SAFE_TRACED_HEADER_NAMES.includes(\n name.toLowerCase() as (typeof SAFE_TRACED_HEADER_NAMES)[number],\n );\n\nexport const postHogOtlpEndpoints = (host: string) => {\n const base = host.replace(/\\/+$/, \"\");\n return {\n logs: `${base}/i/v1/logs`,\n traces: `${base}/i/v1/traces`,\n } as const;\n};\n\nconst ENGINEERING_CAPXUL_ENVS = new Set<EngineeringCapxulEnv>([\n \"development\",\n \"e2e\",\n \"staging\",\n \"production\",\n]);\nconst ENGINEERING_PRODUCERS = new Set<EngineeringProducer>([\"browser\", \"server\"]);\nconst PUBLIC_POSTHOG_AUTHORIZATION = /^Bearer phc_[A-Za-z0-9_-]{1,191}$/u;\nconst SAFE_RESOURCE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._+@/-]{0,127}$/u;\n\nconst validateEngineeringTelemetryConfig = (\n config: EngineeringTelemetryConfig,\n): EngineeringTelemetryConfig => {\n let url: URL;\n try {\n url = new URL(config.host);\n } catch {\n throw new TypeError(\"engineering telemetry host must be an absolute HTTPS URL\");\n }\n if (\n url.protocol !== \"https:\" ||\n url.username.length > 0 ||\n url.password.length > 0 ||\n url.pathname !== \"/\" ||\n url.search.length > 0 ||\n url.hash.length > 0 ||\n !(url.hostname === \"posthog.com\" || url.hostname.endsWith(\".posthog.com\"))\n ) {\n throw new TypeError(\"engineering telemetry host must be a credential-free HTTPS origin\");\n }\n if (!ENGINEERING_CAPXUL_ENVS.has(config.capxulEnv)) {\n throw new TypeError(\"engineering telemetry capxulEnv is not canonical\");\n }\n if (!ENGINEERING_PRODUCERS.has(config.producer)) {\n throw new TypeError(\"engineering telemetry producer is not canonical\");\n }\n if (!SAFE_RESOURCE_VALUE.test(config.sdkVersion)) {\n throw new TypeError(\"engineering telemetry sdkVersion must be a bounded safe value\");\n }\n if (config.serviceName !== undefined && !SAFE_RESOURCE_VALUE.test(config.serviceName)) {\n throw new TypeError(\"engineering telemetry serviceName must be a bounded safe value\");\n }\n const headerEntries = Object.entries(config.headers);\n if (\n headerEntries.length !== 1 ||\n headerEntries[0]?.[0].toLowerCase() !== \"authorization\" ||\n !PUBLIC_POSTHOG_AUTHORIZATION.test(headerEntries[0]?.[1] ?? \"\")\n ) {\n throw new TypeError(\n \"engineering telemetry headers must contain exactly one public PostHog authorization token\",\n );\n }\n return {\n ...config,\n host: url.origin,\n headers: Object.freeze({ authorization: headerEntries[0][1] }),\n };\n};\n\nclass RedactedEngineeringSpanFailure extends Error {\n constructor() {\n super(\"Engineering operation failed\");\n this.name = \"RedactedEngineeringSpanFailure\";\n delete this.stack;\n }\n}\n\nconst REDACTED_SPAN_FAILURE = Exit.fail(new RedactedEngineeringSpanFailure());\n\n/** Preserve domain exits while preventing the OTLP serializer from seeing raw causes. */\nexport const makeLeakSafeEngineeringTracer = (delegate: Tracer.Tracer): Tracer.Tracer =>\n Tracer.make({\n span(options) {\n const span = delegate.span(options);\n const wrapped = Object.create(span) as Tracer.Span;\n Object.defineProperty(wrapped, \"end\", {\n configurable: false,\n enumerable: false,\n value: (endTime: bigint, exit: Exit.Exit<unknown, unknown>) =>\n span.end(\n endTime,\n Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)\n ? REDACTED_SPAN_FAILURE\n : exit,\n ),\n writable: false,\n });\n return wrapped;\n },\n ...(delegate.context === undefined ? {} : { context: delegate.context.bind(delegate) }),\n });\n\n/** Shared browser/server OTLP layer. OtlpLogger merges with incumbent loggers once. */\nexport const makeEngineeringTelemetryLayer = (config: EngineeringTelemetryConfig) => {\n const validated = validateEngineeringTelemetryConfig(config);\n const endpoints = postHogOtlpEndpoints(validated.host);\n const resource = {\n serviceName: validated.serviceName ?? \"capxul-sdk\",\n serviceVersion: validated.sdkVersion,\n attributes: {\n capxul_env: validated.capxulEnv,\n producer: validated.producer,\n sdk_version: validated.sdkVersion,\n },\n } as const;\n const tracing = Layer.effect(\n Tracer.Tracer,\n OtlpTracer.make({\n url: endpoints.traces,\n headers: validated.headers,\n resource,\n }).pipe(Effect.map(makeLeakSafeEngineeringTracer)),\n ).pipe(Layer.provideMerge(OtlpExporter.layerFlusher));\n const logging = OtlpLogger.layer({\n url: endpoints.logs,\n headers: validated.headers,\n resource,\n mergeWithExisting: true,\n });\n const headerPolicy = Layer.merge(\n Layer.succeed(HttpClient.TracerHeaderFilter, traceHeaderFilter),\n Layer.succeed(Headers.CurrentRedactedNames, ENGINEERING_REDACTED_HEADER_NAMES),\n );\n return Layer.mergeAll(tracing, logging, headerPolicy).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n};\n"],"mappings":";;;;AAuBA,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,oCAAoE,OAAO,OAAO;CACtF;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,qBAAqB,SAChC,yBAAyB,SACvB,KAAK,YAAY,CACnB;AAEF,MAAa,wBAAwB,SAAiB;CACpD,MAAM,OAAO,KAAK,QAAQ,QAAQ,EAAE;CACpC,OAAO;EACL,MAAM,GAAG,KAAK;EACd,QAAQ,GAAG,KAAK;CAClB;AACF;AAEA,MAAM,0BAA0B,IAAI,IAA0B;CAC5D;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,wBAAwB,IAAI,IAAyB,CAAC,WAAW,QAAQ,CAAC;AAChF,MAAM,+BAA+B;AACrC,MAAM,sBAAsB;AAE5B,MAAM,sCACJ,WAC+B;CAC/B,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,OAAO,IAAI;CAC3B,QAAQ;EACN,MAAM,IAAI,UAAU,0DAA0D;CAChF;CACA,IACE,IAAI,aAAa,YACjB,IAAI,SAAS,SAAS,KACtB,IAAI,SAAS,SAAS,KACtB,IAAI,aAAa,OACjB,IAAI,OAAO,SAAS,KACpB,IAAI,KAAK,SAAS,KAClB,EAAE,IAAI,aAAa,iBAAiB,IAAI,SAAS,SAAS,cAAc,IAExE,MAAM,IAAI,UAAU,mEAAmE;CAEzF,IAAI,CAAC,wBAAwB,IAAI,OAAO,SAAS,GAC/C,MAAM,IAAI,UAAU,kDAAkD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3D,MAAM,YAAY,qBAAqB,UAAU,IAAI;CACrD,MAAM,WAAW;EACf,aAAa,UAAU,eAAe;EACtC,gBAAgB,UAAU;EAC1B,YAAY;GACV,YAAY,UAAU;GACtB,UAAU,UAAU;GACpB,aAAa,UAAU;EACzB;CACF;CACA,MAAM,UAAU,MAAM,OACpB,OAAO,QACP,WAAW,KAAK;EACd,KAAK,UAAU;EACf,SAAS,UAAU;EACnB;CACF,CAAC,EAAE,KAAK,OAAO,IAAI,6BAA6B,CAAC,CACnD,EAAE,KAAK,MAAM,aAAa,aAAa,YAAY,CAAC;CACpD,MAAM,UAAU,WAAW,MAAM;EAC/B,KAAK,UAAU;EACf,SAAS,UAAU;EACnB;EACA,mBAAmB;CACrB,CAAC;CACD,MAAM,eAAe,MAAM,MACzB,MAAM,QAAQ,WAAW,oBAAoB,iBAAiB,GAC9D,MAAM,QAAQ,QAAQ,sBAAsB,iCAAiC,CAC/E;CACA,OAAO,MAAM,SAAS,SAAS,SAAS,YAAY,EAAE,KACpD,MAAM,QAAQ,kBAAkB,SAAS,GACzC,MAAM,QAAQ,gBAAgB,KAAK,CACrC;AACF"}
|
package/dist/index.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../errors/src/errors.ts","../../types/src/brand.ts","../../types/src/index.ts","../src/telemetry-port.ts","../src/index.ts"],"mappings":";;;cAKa,kBAAA;AAAA,KA6BD,eAAA,WAA0B,kBAAkB;;AAAA;AAiDxD;;;;AAAuB;AAkBvB;;;;AAAuC;AAgBvC;;;;;KAlCY,WAAA;AAAA,KAkBA,kBAAA,GAAqB,MAAM;AAAA,KAgB3B,kBAAA;EAAA,SACD,KAAA;EAAA,SACA,OAAA,GAAU,kBAAkB;EAAA,SAC5B,aAAA;EAAA,SACA,KAAA;AAAA;AAAA,cAGE,WAAA,SAAoB,KAAA;EAAA,SACtB,IAAA,EAAM,eAAA;EAAA,SACN,OAAA,GAAU,kBAAA;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,CAAA,GAAS,MAAA,CAAO,MAAA;EAIhB,kBAAA,CACE,MAAA,EAAQ,WAAA,EACR,QAAA,GAAW,yBAAA,GACV,MAAA,CAAO,MAAA;AAAA;AAAA,cAKC,2BAAA,YAAuC,aAAA;EAAA;cAItC,OAAA,GAAS,yBAAA;EAIrB,SAAA,CAAU,OAAA,GAAU,KAAA,EAAO,cAAA;EAO3B,IAAA,CAAK,KAAA,EAAO,cAAA,GAAiB,MAAA,CAAO,MAAA;EAapC,QAAA,CAAS,MAAA,EAAQ,sBAAA,GAAyB,MAAA,CAAO,MAAA;EAIjD,KAAA,CAAM,MAAA,EAAQ,mBAAA,GAAsB,MAAA,CAAO,MAAA;EAI3C,KAAA,CAAA,GAAS,MAAA,CAAO,MAAA;EAIhB,kBAAA,CACE,MAAA,EAAQ,WAAA,EACR,QAAA,GAAW,yBAAA,GACV,MAAA,CAAO,MAAA;AAAA"}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#events","#rawMode","#capture","#subscribers"],"sources":["../../errors/src/errors.ts","../../errors/src/convex-error-decoding.ts","../../types/src/index.ts","../src/index.ts"],"sourcesContent":["// The canonical error-code catalog as a runtime constant. `CapxulErrorCode`\n// is derived from it so the type and any runtime check that needs to\n// enumerate codes (e.g. the convex-error codec's `KNOWN_CODES`) share a\n// single source of truth — a TypeScript union alone can't be introspected\n// at runtime, which previously forced a hand-maintained duplicate.\nexport const CAPXUL_ERROR_CODES = [\n \"NOT_AUTHENTICATED\",\n \"EMAIL_DELIVERY_FAILED\",\n \"PROFILE_NOT_FOUND\",\n \"SMART_ACCOUNT_MISSING\",\n \"PLAYER_NOT_FOUND\",\n \"ACCOUNT_NOT_FOUND\",\n \"PROVIDER_ERROR\",\n \"INVALID_INPUT\",\n \"ENV_MISSING\",\n \"NOT_IMPLEMENTED\",\n \"VERIFICATION_REQUIRED\",\n \"INSUFFICIENT_BALANCE\",\n \"INVALID_RECIPIENT\",\n \"ROLE_PERMISSION_DENIED\",\n \"TRANSACTION_FAILED\",\n \"RATE_LIMITED\",\n \"NETWORK_ERROR\",\n \"UNKNOWN\",\n \"OTP_EXPIRED\",\n \"SIGNER_REJECTED\",\n \"CANCELLED\",\n \"WRONG_STATE\",\n \"STALE_EPOCH\",\n \"SUPERSEDED\",\n \"WORK_DIED\",\n \"ACTOR_STOPPED\",\n] as const;\n\nexport type CapxulErrorCode = (typeof CAPXUL_ERROR_CODES)[number];\n\n/**\n * The error codes that represent an expected product outcome rather than a\n * defect. The SDK and backend observation boundaries both classify failures\n * against this set to route expected outcomes to their own PostHog event\n * stream; keeping the single copy here (adjacent to `CAPXUL_ERROR_CODES`, so a\n * code rename forces this set to move with it) stops the two sides of the wire\n * from drifting and silently splitting one outcome across two streams.\n */\nexport const EXPECTED_OPERATION_OUTCOMES: ReadonlySet<CapxulErrorCode> = new Set([\n \"INVALID_INPUT\",\n \"NOT_AUTHENTICATED\",\n // A user with no Safe yet — the normal post-OTP / pre-provision state. Reading\n // the account, current user, or balance in that window is an expected outcome,\n // not a defect, so both observation boundaries route it to their\n // `*_expected_outcome` stream instead of an unexpected `$exception` (#1031).\n \"SMART_ACCOUNT_MISSING\",\n \"CANCELLED\",\n \"SIGNER_REJECTED\",\n \"VERIFICATION_REQUIRED\",\n \"INSUFFICIENT_BALANCE\",\n \"INVALID_RECIPIENT\",\n \"ROLE_PERMISSION_DENIED\",\n \"RATE_LIMITED\",\n \"OTP_EXPIRED\",\n \"WRONG_STATE\",\n \"STALE_EPOCH\",\n \"SUPERSEDED\",\n \"ACTOR_STOPPED\",\n]);\n\n/**\n * Why an auth/provider call failed — a flat CAUSE enum. The *where* (which\n * OpenFort operation) stays in the separate `operation` detail field; this\n * names the root cause so a single `$exception` can be triaged without\n * parsing the message. Five members, no free strings:\n *\n * - `auth-origin-mismatch`: OTP cookies live on `localhost:PORT` but OpenFort\n * hits the Convex host → no session reaches the provider.\n * - `stale-openfort-cache`: an old `userId` in scoped storage makes the SDK\n * skip re-auth → 401 on `v2/accounts`.\n * - `app-env-allowlist`: the selected app/deployment origin is not allowlisted\n * → 401.\n * - `no-secure-context`: sandboxed/headless browser with no Web Crypto, so\n * `getAddress`/`configure` can never produce an address. Previously vanished\n * into `unknown`; the signer's secure-context probe now names it.\n * - `unknown`: catch-all when no cause could be determined.\n */\nexport type FailureMode =\n | \"auth-origin-mismatch\"\n | \"stale-openfort-cache\"\n | \"app-env-allowlist\"\n | \"no-secure-context\"\n | \"unknown\";\n\n/**\n * The one failure representation carried by domain state, actor work, and\n * public error projection. Keeping it beside the canonical error catalog\n * prevents a machine or shell from inventing a second code vocabulary.\n */\nexport interface Failure {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly mode?: FailureMode;\n}\n\nexport type CapxulErrorDetails = Record<string, unknown>;\n\nexport type SignerSource = \"openfort-embedded\" | \"injected-eip1193\" | \"local-private-key\";\n\nexport type VerificationRequiredDetails =\n | { readonly requiredTier: number }\n | { readonly rail: string; readonly currentKind: string };\n\nexport type SerializedCapxulError = {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n};\n\nexport type CapxulErrorOptions = {\n readonly cause?: unknown;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n};\n\nexport class CapxulError extends Error {\n readonly code: CapxulErrorCode;\n readonly details?: CapxulErrorDetails;\n readonly correlationId?: string;\n readonly layer?: string;\n\n constructor(code: CapxulErrorCode, message: string, options: CapxulErrorOptions = {}) {\n super(message, \"cause\" in options ? { cause: options.cause } : undefined);\n this.name = \"CapxulError\";\n this.code = code;\n if (options.details !== undefined) {\n this.details = options.details;\n }\n if (options.correlationId !== undefined) {\n this.correlationId = options.correlationId;\n }\n if (options.layer !== undefined) {\n this.layer = options.layer;\n }\n }\n}\n\nexport function isCapxulError(value: unknown): value is CapxulError {\n return value instanceof CapxulError;\n}\n\nexport function serializeCapxulError(error: CapxulError): SerializedCapxulError {\n return compactSerialized({\n code: error.code,\n message: error.message,\n details: error.details,\n correlationId: error.correlationId,\n layer: error.layer,\n });\n}\n\nexport function deserializeCapxulError(serialized: SerializedCapxulError): CapxulError {\n return new CapxulError(\n serialized.code,\n serialized.message,\n compactErrorOptions({\n details: serialized.details,\n correlationId: serialized.correlationId,\n layer: serialized.layer,\n }),\n );\n}\n\nfunction compactSerialized(serialized: {\n readonly code: CapxulErrorCode;\n readonly message: string;\n readonly details: CapxulErrorDetails | undefined;\n readonly correlationId: string | undefined;\n readonly layer: string | undefined;\n}): SerializedCapxulError {\n const result: {\n code: CapxulErrorCode;\n message: string;\n details?: CapxulErrorDetails;\n correlationId?: string;\n layer?: string;\n } = {\n code: serialized.code,\n message: serialized.message,\n };\n\n if (serialized.details !== undefined) {\n result.details = serialized.details;\n }\n if (serialized.correlationId !== undefined) {\n result.correlationId = serialized.correlationId;\n }\n if (serialized.layer !== undefined) {\n result.layer = serialized.layer;\n }\n\n return result;\n}\n\nfunction compactErrorOptions(options: {\n readonly cause?: unknown;\n readonly details: CapxulErrorDetails | undefined;\n readonly correlationId: string | undefined;\n readonly layer: string | undefined;\n}): CapxulErrorOptions {\n const result: {\n cause?: unknown;\n details?: CapxulErrorDetails;\n correlationId?: string;\n layer?: string;\n } = {};\n\n if (\"cause\" in options) {\n result.cause = options.cause;\n }\n if (options.details !== undefined) {\n result.details = options.details;\n }\n if (options.correlationId !== undefined) {\n result.correlationId = options.correlationId;\n }\n if (options.layer !== undefined) {\n result.layer = options.layer;\n }\n\n return result;\n}\n\nexport const Errors = {\n notAuthenticated: (message?: string, opts?: { readonly failure_mode?: FailureMode }) =>\n new CapxulError(\n \"NOT_AUTHENTICATED\",\n message ?? \"Not authenticated\",\n opts?.failure_mode ? { details: { failure_mode: opts.failure_mode } } : undefined,\n ),\n emailDeliveryFailed: (detail: string) =>\n new CapxulError(\"EMAIL_DELIVERY_FAILED\", \"Failed to send email\", {\n details: { detail },\n }),\n\n profileNotFound: (authUserId: string) =>\n new CapxulError(\"PROFILE_NOT_FOUND\", `Profile not found for user ${authUserId}`, {\n details: { authUserId },\n }),\n\n smartAccountMissing: (authUserId: string) =>\n new CapxulError(\"SMART_ACCOUNT_MISSING\", \"Smart account not provisioned\", {\n details: { authUserId },\n }),\n\n playerNotFound: (playerId?: string) =>\n new CapxulError(\n \"PLAYER_NOT_FOUND\",\n playerId ? `Openfort player ${playerId} not found` : \"Openfort player not found\",\n playerId === undefined ? undefined : { details: { playerId } },\n ),\n\n accountNotFound: (accountId?: string) =>\n new CapxulError(\n \"ACCOUNT_NOT_FOUND\",\n accountId ? `Openfort account ${accountId} not found` : \"Openfort account not found\",\n accountId === undefined ? undefined : { details: { accountId } },\n ),\n\n providerError: (\n provider: string,\n operation: string,\n cause: unknown,\n opts?: { readonly failure_mode?: FailureMode },\n ) => {\n const details: Record<string, unknown> = { provider, operation };\n if (opts?.failure_mode) {\n details.failure_mode = opts.failure_mode;\n }\n return new CapxulError(\"PROVIDER_ERROR\", `Provider error: ${provider} ${operation}`, {\n cause,\n details,\n });\n },\n\n invalidInput: (field: string, reason: string) =>\n new CapxulError(\"INVALID_INPUT\", `Invalid ${field}: ${reason}`, {\n details: { field, reason },\n }),\n\n envMissing: (name: string) =>\n new CapxulError(\"ENV_MISSING\", `Environment variable ${name} not configured`, {\n details: { name },\n }),\n\n notImplemented: (domain: string, method: string) =>\n new CapxulError(\n \"NOT_IMPLEMENTED\",\n `${domain}.${method} is not yet implemented. This feature is planned for a future release.`,\n { details: { domain, method } },\n ),\n\n /**\n * Sibling factory to {@link Errors.providerError} for the per-state timeout\n * path in flows. Same `PROVIDER_ERROR` code as\n * `providerError`, plus a `details.reason: \"timeout\"` discriminator so\n * downstream observers can distinguish failure modes without parsing the\n * message string. The redacted message names the timeout budget; the\n * native `cause` carries the same information for `reportError` fidelity.\n */\n providerTimeout: (provider: string, operation: string, timeoutMs: number) =>\n new CapxulError(\n \"PROVIDER_ERROR\",\n `Provider error: ${provider} ${operation} (timeout exceeded ${timeoutMs}ms)`,\n {\n details: { provider, operation, reason: \"timeout\" },\n cause: new Error(`timeout: ${operation} exceeded ${timeoutMs}ms`),\n },\n ),\n\n verificationRequired: (details: VerificationRequiredDetails) => {\n const message =\n \"rail\" in details\n ? `Verification is required before ${details.rail} can use ${details.currentKind}.`\n : `Verification tier ${details.requiredTier} is required.`;\n\n return new CapxulError(\"VERIFICATION_REQUIRED\", message, {\n details,\n });\n },\n\n insufficientBalance: (asset: string, available: string, required: string) =>\n new CapxulError(\"INSUFFICIENT_BALANCE\", `Insufficient ${asset} balance`, {\n details: { asset, available, required },\n }),\n\n invalidRecipient: (reason: string) =>\n new CapxulError(\"INVALID_RECIPIENT\", `Invalid recipient: ${reason}`, {\n details: { reason },\n }),\n\n /**\n * The org Zodiac Roles modifier REFUSED the spend on-chain (G4 · #547): the\n * member's role condition (per-tx cap, per-day allowance, allowed recipient,\n * or membership) was violated, so `execTransactionWithRole` reverted. This is\n * a PERMISSION denial — explicitly NOT an `INSUFFICIENT_BALANCE` (the treasury\n * held the funds; the role's authority is what bound). `reason` discriminates\n * the violated condition (`over_cap` / `daily_cap` / `not_member` /\n * `disallowed_recipient` / `condition_violation`); leak-safe — no on-chain\n * identifiers ever enter the details.\n */\n rolePermissionDenied: (details: {\n readonly reason:\n | \"over_cap\"\n | \"daily_cap\"\n | \"not_member\"\n | \"disallowed_recipient\"\n | \"condition_violation\";\n readonly operation?: string;\n }) =>\n new CapxulError(\n \"ROLE_PERMISSION_DENIED\",\n `Org role denied this spend on-chain (${details.reason}).`,\n {\n details:\n details.operation === undefined\n ? { reason: details.reason }\n : { reason: details.reason, operation: details.operation },\n },\n ),\n\n /**\n * A transaction (or sponsored UserOp) failed. `details.reason` discriminates\n * the failure mode for callers that must distinguish a CONFIRMED on-chain\n * revert (`\"onchain_revert\"` — the op executed and reverted, e.g. a Zodiac\n * Roles condition violation) from an inconclusive infra failure. A confirmed\n * revert is the ONLY mode the org spend port may map to a roles denial.\n */\n transactionFailed: (operation: string, cause?: unknown, extra?: { readonly reason?: string }) =>\n new CapxulError(\"TRANSACTION_FAILED\", `Transaction failed: ${operation}`, {\n cause,\n details: extra?.reason === undefined ? { operation } : { operation, reason: extra.reason },\n }),\n\n rateLimited: (details?: { readonly retryAfterMs?: number; readonly resource?: string }) =>\n new CapxulError(\n \"RATE_LIMITED\",\n \"Rate limit exceeded\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n networkError: (operation: string, cause?: unknown) =>\n new CapxulError(\"NETWORK_ERROR\", `Network error during ${operation}`, {\n cause,\n details: { operation },\n }),\n\n unknown: (cause?: unknown) => new CapxulError(\"UNKNOWN\", \"Unknown error\", { cause }),\n\n otpExpired: (details?: { readonly email?: string; readonly expiredAt?: number }) =>\n new CapxulError(\n \"OTP_EXPIRED\",\n \"Verification code has expired. Request a new one.\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n signerRejected: (details: {\n readonly source: SignerSource;\n readonly reason?: string;\n readonly cause?: unknown;\n }) =>\n new CapxulError(\"SIGNER_REJECTED\", \"Signer rejected the request.\", {\n cause: details.cause,\n details:\n details.reason === undefined\n ? { source: details.source }\n : { source: details.source, reason: details.reason },\n }),\n\n cancelled: (details?: { readonly operation?: string; readonly reason?: string }) =>\n new CapxulError(\n \"CANCELLED\",\n \"Operation was cancelled.\",\n details === undefined ? undefined : { details: { ...details } },\n ),\n\n /**\n * Method called from a flow state where its precondition fails (TA16). The\n * SDK's method API short-circuits with this error before driving the\n * internal state machine. `currentState` is the Effect-machine snapshot\n * tag (stringified from the SDK's actor-shell snapshot; see\n * `packages/errors/CONTEXT.md`); `validStates`\n * enumerates the states the method accepts.\n */\n wrongState: (details: {\n readonly method: string;\n readonly currentState: string;\n readonly validStates: readonly string[];\n }) =>\n new CapxulError(\n \"WRONG_STATE\",\n `${details.method} called from state '${details.currentState}'; valid states: ${details.validStates.join(\", \")}`,\n { details: { ...details, validStates: [...details.validStates] } },\n ),\n} as const;\n","// Shared `decodeConvexError` helper (TA5) — used by both the SDK's\n// `ConvexCallAdapter.mapToCapxulError` AND the backend `credentials/http.ts`\n// `bootstrapClient` handler. Single source of truth for cross-Convex-boundary\n// error decoding rules.\n//\n// Recognizes the `ConvexError(SerializedCapxulError)` object-shape produced by\n// `withErrorBoundary` (Probe B finding, 2026-05-19):\n//\n// { name: \"ConvexError\", data: { code, message, details?, correlationId?, layer? } }\n//\n// AND the defensive string-shape branch for older Convex versions where\n// `data` is a JSON-serialized string. Pass-through for raw `CapxulError`\n// instances (which arrive directly when the throw happened in the same\n// V8 isolate as the catch). Returns null when the value is not a\n// recognizable shape — the caller falls back to NETWORK_ERROR + reportError.\n\nimport {\n CAPXUL_ERROR_CODES,\n CapxulError,\n type CapxulErrorCode,\n type SerializedCapxulError,\n deserializeCapxulError,\n} from \"./errors.ts\";\n\n// Derived from the canonical catalog in errors.ts — single source of truth,\n// so a new code added to `CAPXUL_ERROR_CODES` is recognized here automatically.\nconst KNOWN_CODES: ReadonlySet<CapxulErrorCode> = new Set(CAPXUL_ERROR_CODES);\n\nfunction isCapxulCode(value: unknown): value is CapxulErrorCode {\n return typeof value === \"string\" && KNOWN_CODES.has(value as CapxulErrorCode);\n}\n\nfunction reconstruct(serialized: Record<string, unknown>): CapxulError | null {\n if (!isCapxulCode(serialized.code)) return null;\n const payload: SerializedCapxulError = {\n code: serialized.code,\n message: typeof serialized.message === \"string\" ? serialized.message : String(serialized.code),\n ...(typeof serialized.details === \"object\" &&\n serialized.details !== null &&\n !Array.isArray(serialized.details)\n ? { details: serialized.details as Record<string, unknown> }\n : {}),\n ...(typeof serialized.correlationId === \"string\"\n ? { correlationId: serialized.correlationId }\n : {}),\n ...(typeof serialized.layer === \"string\" ? { layer: serialized.layer } : {}),\n };\n return deserializeCapxulError(payload);\n}\n\nexport function decodeConvexError(err: unknown): CapxulError | null {\n if (err === null || err === undefined) return null;\n\n // Pass-through: same isolate, real CapxulError instance.\n if (err instanceof CapxulError) return err;\n\n if (typeof err !== \"object\") return null;\n\n // The canonical shape produced by `withErrorBoundary` then crossed by\n // Convex's `ctx.runQuery` / `ConvexHttpClient`: a `ConvexError` whose\n // `data` is the `SerializedCapxulError` object literal.\n const record = err as Record<string, unknown>;\n if (!(\"data\" in record)) return null;\n const data = record.data;\n\n if (typeof data === \"object\" && data !== null) {\n return reconstruct(data as Record<string, unknown>);\n }\n\n // Defensive depth — some Convex versions JSON-stringify the data at\n // the runtime boundary. Probe B confirmed @convex-dev/better-auth 0.10.13\n // + convex 1.39.x do NOT do this, but the cheap parse keeps forward\n // compatibility.\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data) as unknown;\n if (typeof parsed === \"object\" && parsed !== null) {\n return reconstruct(parsed as Record<string, unknown>);\n }\n } catch {\n // Fall through.\n }\n }\n\n return null;\n}\n","import { Errors } from \"@capxul/errors\";\nimport type { Brand } from \"./brand\";\n\nexport type { Brand } from \"./brand\";\n\nexport type Address = Brand<string, \"Address\">;\nexport type Email = Brand<string, \"Email\">;\nexport type Identity = Brand<string, \"Identity\">;\n// `Profile` is the SDK's user-shaped record returned by `IdentityPort`. Pure\n// record of brand-typed fields — not itself a brand. The field-level brands\n// satisfy `IdentityPort` clause I8 at compile time. Hosted here per the\n// package contract (`packages/types/CONTEXT.md`).\nexport type Profile = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string | null;\n readonly country: CountryCode | null;\n readonly onboarded: boolean;\n readonly withdrawalAddress: Address | null;\n // #1062: globally-unique normalized handle; #1061 / ADR-0014: profile-image\n // serving URL resolved at read time. Plain strings (not branded in this\n // slice); null when unset — the Convex read boundary always maps both.\n readonly username: string | null;\n readonly imageUrl: string | null;\n readonly kycTier: KycTier;\n readonly createdAt: EpochMs;\n readonly updatedAt: EpochMs;\n};\n// `SmartAccount` is the SDK's ERC-4337 record returned by `SmartAccountPort`.\n// Pure record of brand-typed fields — not itself a brand. `deployedAt` is\n// nullable: `null` means the address is counterfactual (derived, not yet\n// on-chain). PRD #462 (derivation v2): `signerAddress` is the CLAIMED owner —\n// `null` until the claim userOp installs the user's signer (`claimedAt`\n// records that event); the address derives from the email alone. Hosted here\n// per the package contract (`packages/types/CONTEXT.md`).\nexport type SmartAccount = {\n readonly authUserId: AuthUserId;\n readonly signerAddress: Address | null;\n readonly smartAccountAddress: Address;\n readonly chainId: ChainId;\n readonly deployedAt: EpochMs | null;\n readonly claimedAt: EpochMs | null;\n readonly createdAt: EpochMs;\n};\n// `Money` is the SDK's consumer-facing value type (canon\n// `account-balance-model.md` §10). Every public monetary value is a `Money`\n// — never wei, never raw token units. `value` is a major-unit decimal string\n// (e.g. \"1.5\" USD); `decimals` is the on-chain token precision used for the\n// internal `fromWei`/`toWei` round-trip at the SDK boundary (USDX is 6).\n// Pure record of a brand-typed field + primitives — not itself a brand.\nexport type Money = {\n readonly currency: CurrencyCode;\n readonly value: string;\n readonly decimals: number;\n};\n\n// `Account` is the SDK's logical money account (canon §6, §9). `id` is the\n// `account_`-shaped `AccountId` — NOT the Safe address and NOT an Openfort id.\n// `balance` is the Safe's top-line holdings; `available` is money not assigned\n// to any sub-account (canon §5/§12). With no sub-accounts (Slice 1a),\n// `available === balance`. Pure record of brand-typed fields — not a brand.\nexport type Account = {\n readonly id: AccountId;\n readonly balance: Money;\n readonly available: Money;\n};\n\n/** Named bucket partitioning a logical Account (canon §9). */\nexport type SubAccount = {\n readonly id: SubAccountId;\n readonly accountId: AccountId;\n readonly name: string;\n readonly balance: Money;\n readonly createdAt: EpochMs;\n};\n\nexport type AuthUserId = Brand<string, \"AuthUserId\">;\nexport type AnonymousDistinctId = Brand<string, \"AnonymousDistinctId\">;\nexport type PlayerId = Brand<string, \"PlayerId\">;\nexport type AccountId = Brand<string, \"AccountId\">;\nexport type SubAccountId = Brand<string, \"SubAccountId\">;\nexport type OrgId = Brand<string, \"OrgId\">;\nexport type AppId = Brand<string, \"AppId\">;\nexport type AllowedOrigin = Brand<string, \"AllowedOrigin\">;\nexport type PublishableKey = Brand<string, \"PublishableKey\">;\nexport type PublishableKeyId = Brand<string, \"PublishableKeyId\">;\nexport type DurationMs = Brand<number, \"DurationMs\">;\n// `DeveloperApplication` and `PublishableKeyRecord` are the SDK's record\n// shapes returned by `CredentialsPort`. Pure records of brand-typed fields\n// — not themselves brands. The field-level brands satisfy CR13 + the record\n// branding clauses of `credentials.test-d.ts` at compile time. Hosted here\n// per the package contract (`packages/types/CONTEXT.md`).\nexport type DeveloperApplication = {\n readonly id: AppId;\n readonly authUserId: AuthUserId;\n readonly name: string;\n readonly allowedOrigins: readonly AllowedOrigin[];\n readonly createdAt: EpochMs;\n readonly archivedAt: EpochMs | null;\n};\nexport type PublishableKeyRecord = {\n readonly id: PublishableKeyId;\n readonly applicationId: AppId;\n readonly activeFromMs: EpochMs;\n readonly gracePeriodEndsMs: EpochMs | null;\n readonly revokedAt: EpochMs | null;\n};\nexport type TxHash = Brand<string, \"TxHash\">;\nexport type DocumentHash = Brand<string, \"DocumentHash\">;\nexport type EpochMs = Brand<number, \"EpochMs\">;\nexport type EpochSeconds = Brand<number, \"EpochSeconds\">;\nexport type ChainId = Brand<number, \"ChainId\">;\nexport type CountryCode = Brand<string, \"CountryCode\">;\nexport type CurrencyCode = Brand<SupportedCurrencyCode, \"CurrencyCode\">;\nexport type KycTier = Brand<0 | 1 | 2 | 3, \"KycTier\">;\nexport type BlockNumber = Brand<number, \"BlockNumber\">;\nexport type LogIndex = Brand<number, \"LogIndex\">;\nexport type WeiAmount = Brand<string, \"WeiAmount\">;\nexport type SafeAddress = Brand<string, \"SafeAddress\">;\nexport type ModuleAddress = Brand<string, \"ModuleAddress\">;\nexport type RunId = Brand<string, \"RunId\">;\nexport type RoleKey = Brand<string, \"RoleKey\">;\nexport type AllowanceKey = Brand<string, \"AllowanceKey\">;\nexport type SessionToken = Brand<string, \"SessionToken\">;\nexport type JwtToken = Brand<string, \"JwtToken\">;\n\n// `AuthSession` is the record type shared by `AuthClientPort` and\n// `SessionStoragePort`. Hosted here per the canon\n// (`packages/types/CONTEXT.md`) so both ports depend on it\n// symmetrically. Every field is branded — field-level brands satisfy the\n// AuthSession branding contract asserted in `auth-client.test-d.ts`.\nexport type AuthSession = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly token: SessionToken;\n readonly expiresAt: EpochMs;\n};\n\nexport const EVM_ADDRESS_RE = /^0x[0-9a-f]{40}$/i;\nexport const BYTES32_RE = /^0x[0-9a-f]{64}$/i;\nexport const PUBLISHABLE_KEY_PATTERN = /^cap_pk_(test|live)_[0-9A-HJKMNP-TV-Z]{32}$/;\nexport const SUPPORTED_CURRENCIES = [\n { code: \"USD\", symbol: \"$\", name: \"US Dollar\" },\n { code: \"NGN\", symbol: \"NGN\", name: \"Nigerian Naira\" },\n { code: \"GHS\", symbol: \"GHS\", name: \"Ghanaian Cedi\" },\n { code: \"KES\", symbol: \"KSh\", name: \"Kenyan Shilling\" },\n { code: \"UGX\", symbol: \"USh\", name: \"Ugandan Shilling\" },\n] as const;\nexport const SUPPORTED_CURRENCY_CODES = SUPPORTED_CURRENCIES.map((currency) => currency.code);\ntype SupportedCurrencyCode = (typeof SUPPORTED_CURRENCIES)[number][\"code\"];\nexport const CURRENCY_SYMBOLS = Object.fromEntries(\n SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]),\n) as Record<SupportedCurrencyCode, string>;\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst COUNTRY_CODE_RE = /^[A-Z]{2}$/;\nconst ANONYMOUS_DISTINCT_ID_RE = /^anon_[a-zA-Z0-9-]+$/;\n// Canon §6: the logical Account brand is `account_`-shaped. The tail mirrors\n// the `app_` ULID-shape generator (`account_<26 Crockford base32 chars>`) but\n// the brand only enforces the `account_` prefix + a non-empty alphanumeric\n// tail so existing opaque test ids (`account_123`) and generated ULIDs both\n// satisfy it.\nconst ACCOUNT_ID_RE = /^account_[0-9A-Za-z]+$/;\nconst SUBACCOUNT_ID_RE = /^subaccount_[0-9A-Za-z]+$/;\n// Exported so `@capxul/wire`'s `AppIdSchema` can reuse the same regex via\n// `Schema.filter(...)` and stay in lockstep with `toAppId` (Decision 2,\n// 2b parity).\nexport const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;\nconst TX_HASH_RE = /^0x[0-9a-f]{64}$/i;\nconst DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;\nconst WEI_RE = /^[0-9]+$/;\nconst RUN_ID_RE = /^run_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst MAX_SAFE_EPOCH_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1000);\n\nexport function toAddress(raw: unknown): Address {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\"address\", invalidValueReason(\"invalid EVM address format\", raw));\n }\n\n return raw.toLowerCase() as Address;\n}\n\nexport function isEvmAddress(raw: unknown): raw is string {\n return typeof raw === \"string\" && EVM_ADDRESS_RE.test(raw);\n}\n\nexport function toEmail(raw: unknown): Email {\n if (typeof raw !== \"string\" || !EMAIL_RE.test(raw)) {\n throw Errors.invalidInput(\"email\", invalidValueReason(\"must look like an email address\", raw));\n }\n\n return raw.toLowerCase() as Email;\n}\n\nexport function toIdentity(raw: unknown): Identity {\n return toNonEmptyStringBrand(raw, \"identity\") as Identity;\n}\n\nexport function toAuthUserId(raw: unknown): AuthUserId {\n return toNonEmptyStringBrand(raw, \"authUserId\") as AuthUserId;\n}\n\nexport function toAnonymousDistinctId(raw: unknown): AnonymousDistinctId {\n if (typeof raw !== \"string\" || !ANONYMOUS_DISTINCT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"anonDistinctId\",\n invalidValueReason(\"must be anon_ plus letters, digits, or hyphens\", raw),\n );\n }\n\n return raw as AnonymousDistinctId;\n}\n\nexport function toPlayerId(raw: unknown): PlayerId {\n return toNonEmptyStringBrand(raw, \"playerId\") as PlayerId;\n}\n\nexport function toAccountId(raw: unknown): AccountId {\n if (typeof raw !== \"string\" || !ACCOUNT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"accountId\",\n invalidValueReason(\"must be account_ plus an alphanumeric id\", raw),\n );\n }\n\n return raw as AccountId;\n}\n\nexport function toSubAccountId(raw: unknown): SubAccountId {\n if (typeof raw !== \"string\" || !SUBACCOUNT_ID_RE.test(raw)) {\n throw Errors.invalidInput(\n \"subAccountId\",\n invalidValueReason(\"must be subaccount_ plus an alphanumeric id\", raw),\n );\n }\n\n return raw as SubAccountId;\n}\n\nexport function toOrgId(raw: unknown): OrgId {\n return toNonEmptyStringBrand(raw, \"orgId\") as OrgId;\n}\n\nexport function toAppId(raw: unknown): AppId {\n if (typeof raw !== \"string\" || !APP_ID_RE.test(raw)) {\n throw Errors.invalidInput(\"appId\", invalidValueReason(\"must be app_ plus a ULID\", raw));\n }\n\n return raw as AppId;\n}\n\nexport function toAllowedOrigin(raw: unknown): AllowedOrigin {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"allowedOrigin\", \"must be an http or https origin string\");\n }\n\n const normalized = normalizeAllowedOrigin(raw);\n if (normalized === null) {\n throw Errors.invalidInput(\n \"allowedOrigin\",\n invalidValueReason(\"must be an http or https origin\", raw),\n );\n }\n\n return normalized as AllowedOrigin;\n}\n\nexport function toPublishableKeyId(raw: unknown): PublishableKeyId {\n return toNonEmptyStringBrand(raw, \"keyId\") as PublishableKeyId;\n}\n\nexport function toDurationMs(raw: unknown): DurationMs {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n throw Errors.invalidInput(\n \"duration\",\n invalidValueReason(\"must be a non-negative safe integer\", raw),\n );\n }\n\n return raw as DurationMs;\n}\n\nexport function toPublishableKey(raw: unknown): PublishableKey {\n if (typeof raw !== \"string\" || !PUBLISHABLE_KEY_PATTERN.test(raw)) {\n throw Errors.invalidInput(\n \"publishableKey\",\n invalidValueReason(\"must match cap_pk_(test|live) plus 32 Crockford base32 chars\", raw),\n );\n }\n\n return raw as PublishableKey;\n}\n\nexport function toTxHash(raw: unknown): TxHash {\n if (typeof raw !== \"string\" || !TX_HASH_RE.test(raw)) {\n throw Errors.invalidInput(\"txHash\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as TxHash;\n}\n\nexport function toDocumentHash(raw: unknown): DocumentHash {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"documentHash\", \"must be a string\");\n }\n\n const stripped = raw.startsWith(\"0x\") || raw.startsWith(\"0X\") ? raw.slice(2) : raw;\n if (!DOCUMENT_HASH_HEX_RE.test(stripped)) {\n throw Errors.invalidInput(\"documentHash\", \"must be 32 bytes of hex\");\n }\n\n return `0x${stripped.toLowerCase()}` as DocumentHash;\n}\n\nexport function toEpochMs(raw: unknown): EpochMs {\n assertSafeNonNegativeInteger(raw, \"epochMs\");\n return raw as EpochMs;\n}\n\nexport function toEpochSeconds(raw: unknown): EpochSeconds {\n assertSafeNonNegativeInteger(raw, \"epochSeconds\");\n return raw as EpochSeconds;\n}\n\nexport function secondsToMs(seconds: EpochSeconds): EpochMs {\n if (seconds > MAX_SAFE_EPOCH_SECONDS) {\n throw Errors.invalidInput(\"epochSeconds\", `${seconds} would overflow when multiplied by 1000`);\n }\n\n return toEpochMs(seconds * 1000);\n}\n\nexport function epochMsToSeconds(ms: EpochMs): EpochSeconds {\n return toEpochSeconds(Math.floor(ms / 1000));\n}\n\nexport function toChainId(raw: unknown): ChainId {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw <= 0) {\n throw Errors.invalidInput(\n \"chainId\",\n invalidValueReason(\"must be a positive safe integer\", raw),\n );\n }\n\n return raw as ChainId;\n}\n\nexport function toBlockNumber(raw: unknown): BlockNumber {\n assertSafeNonNegativeInteger(raw, \"blockNumber\");\n return raw as BlockNumber;\n}\n\nexport function toLogIndex(raw: unknown): LogIndex {\n assertSafeNonNegativeInteger(raw, \"logIndex\");\n return raw as LogIndex;\n}\n\nexport function toWeiAmount(raw: unknown): WeiAmount {\n if (typeof raw !== \"string\" || !WEI_RE.test(raw)) {\n throw Errors.invalidInput(\n \"weiAmount\",\n invalidValueReason(\"must be a non-negative integer string\", raw),\n );\n }\n\n return raw as WeiAmount;\n}\n\nexport function toCountryCode(raw: unknown): CountryCode {\n if (typeof raw !== \"string\") {\n throw Errors.invalidInput(\"countryCode\", \"must be a string\");\n }\n\n const upper = raw.toUpperCase();\n if (!COUNTRY_CODE_RE.test(upper)) {\n throw Errors.invalidInput(\n \"countryCode\",\n invalidValueReason(\"must be a 2-letter ISO 3166-1 alpha-2 code\", raw),\n );\n }\n\n return upper as CountryCode;\n}\n\nexport function toCurrencyCode(raw: unknown): CurrencyCode {\n if (typeof raw !== \"string\" || !SUPPORTED_CURRENCY_CODES.includes(raw as SupportedCurrencyCode)) {\n throw Errors.invalidInput(\"currencyCode\", invalidValueReason(\"unsupported currency\", raw));\n }\n\n return raw as CurrencyCode;\n}\n\nexport function currencySymbolFor(code: CurrencyCode): string {\n const symbol = CURRENCY_SYMBOLS[code as SupportedCurrencyCode];\n if (symbol === undefined) {\n throw Errors.invalidInput(\"currencyCode\", `no symbol registered for \"${String(code)}\"`);\n }\n\n return symbol;\n}\n\nexport function toKycTier(raw: unknown): KycTier {\n if (typeof raw !== \"number\" || !Number.isInteger(raw) || raw < 0 || raw > 3) {\n throw Errors.invalidInput(\"kycTier\", invalidValueReason(\"must be an integer in [0, 3]\", raw));\n }\n\n return raw as KycTier;\n}\n\nexport function toSafeAddress(raw: unknown): SafeAddress {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\"safeAddress\", invalidValueReason(\"invalid EVM address format\", raw));\n }\n\n return raw.toLowerCase() as SafeAddress;\n}\n\nexport function toModuleAddress(raw: unknown): ModuleAddress {\n if (typeof raw !== \"string\" || !EVM_ADDRESS_RE.test(raw)) {\n throw Errors.invalidInput(\n \"moduleAddress\",\n invalidValueReason(\"invalid EVM address format\", raw),\n );\n }\n\n return raw.toLowerCase() as ModuleAddress;\n}\n\nexport function toRunId(raw: unknown): RunId {\n if (typeof raw !== \"string\" || !RUN_ID_RE.test(raw)) {\n throw Errors.invalidInput(\"runId\", \"must match the format run_<uuid>\");\n }\n\n return raw as RunId;\n}\n\nexport function toRoleKey(raw: unknown): RoleKey {\n if (typeof raw !== \"string\" || !BYTES32_RE.test(raw)) {\n throw Errors.invalidInput(\"roleKey\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as RoleKey;\n}\n\nexport function toAllowanceKey(raw: unknown): AllowanceKey {\n if (typeof raw !== \"string\" || !BYTES32_RE.test(raw)) {\n throw Errors.invalidInput(\"allowanceKey\", invalidValueReason(\"must be 0x + 64 hex chars\", raw));\n }\n\n return raw.toLowerCase() as AllowanceKey;\n}\n\nexport function toSessionToken(raw: unknown): SessionToken {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(\"token\", \"must be a non-empty string\");\n }\n\n return raw as SessionToken;\n}\n\nexport function toJwtToken(raw: unknown): JwtToken {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(\"jwtToken\", \"must be a non-empty string\");\n }\n\n return raw as JwtToken;\n}\n\nfunction toNonEmptyStringBrand(raw: unknown, field: string): string {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw Errors.invalidInput(field, \"must be a non-empty string\");\n }\n\n return raw;\n}\n\nfunction assertSafeNonNegativeInteger(raw: unknown, field: string): asserts raw is number {\n if (typeof raw !== \"number\" || !Number.isSafeInteger(raw) || raw < 0) {\n throw Errors.invalidInput(\n field,\n invalidValueReason(\"must be a non-negative safe integer\", raw),\n );\n }\n}\n\nfunction normalizeAllowedOrigin(raw: string): string | null {\n let parsed: URL;\n try {\n parsed = new URL(raw);\n } catch {\n return null;\n }\n\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return null;\n }\n\n if (parsed.hostname.includes(\"*\")) {\n return null;\n }\n\n return parsed.origin;\n}\n\nfunction invalidValueReason(prefix: string, raw: unknown): string {\n if (typeof raw === \"string\") {\n return `${prefix}: ${raw.slice(0, 40)}`;\n }\n\n return `${prefix}: ${String(raw)}`;\n}\n","import { Effect } from \"effect\";\n\nimport { Schema, SchemaGetter } from \"effect\";\nimport type { CapxulError } from \"@capxul/errors\";\nimport {\n APP_ID_RE,\n BYTES32_RE,\n EVM_ADDRESS_RE,\n type AccountId,\n type Address,\n type AnonymousDistinctId,\n type AppId,\n type BlockNumber,\n type ChainId,\n type CurrencyCode,\n type DurationMs,\n type EpochMs,\n type PublishableKeyId,\n type SubAccountId,\n type TxHash,\n type WeiAmount,\n} from \"@capxul/types\";\n\nexport const TELEMETRY_EVENT_NAMES = [\n \"auth_otp_requested\",\n \"auth_otp_delivered\",\n \"auth_otp_expired\",\n \"auth_verified\",\n \"auth_failed\",\n \"auth_signed_out\",\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"onboarding_organization_submitted\",\n \"onboarding_dashboard_reached\",\n \"provisioning_safe_created\",\n \"provisioning_safe_confirmed\",\n \"bootstrap_resolved\",\n \"bootstrap_failed\",\n \"member_activation_started\",\n \"member_activation_ready\",\n \"member_activation_failed\",\n \"organization_creation_started\",\n \"organization_creation_ready\",\n \"organization_creation_failed\",\n // Money domain (M2). Producer split documented in\n // packages/observability/CONTEXT.md \"Money domain\".\n \"account_balance_read\",\n \"account_balance_failed\",\n \"faucet_requested\",\n \"faucet_confirmed\",\n \"faucet_failed\",\n \"subaccount_created\",\n \"subaccount_renamed\",\n \"subaccount_deleted\",\n \"subaccount_op_failed\",\n \"transfer_requested\",\n \"transfer_backend_received\",\n \"transfer_confirmed\",\n \"transfer_failed\",\n // Organization domain — creation funnel (canon org-domain-model.md §C5, J1).\n // Producer split documented in packages/observability/CONTEXT.md\n // \"Organization domain\". Grouped by the PostHog `organization` group type.\n \"org_create_started\",\n \"org_safe_created\",\n \"org_safe_confirmed\",\n \"org_roles_seeded\",\n \"org_created\",\n \"org_create_failed\",\n \"org_invite_sent\",\n \"org_invite_accepted\",\n \"org_role_granted\",\n \"org_member_active\",\n \"org_member_removed\",\n \"org_invite_expired\",\n \"org_role_grant_failed\",\n // Financial-ops target surface (G0 RED scaffold, #543). These names are\n // cataloged before behavior lands; `FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS`\n // below is the single producer registry until follow-up issues wire emits.\n \"payment_requested\",\n \"payment_resolved\",\n \"payment_document_attached\",\n \"payment_submitted\",\n \"payment_settled\",\n \"payment_claimed\",\n \"payment_cancelled\",\n \"payment_redirected\",\n \"payment_failed\",\n \"stream_created\",\n \"stream_claimed\",\n \"stream_cancelled\",\n \"stream_completed\",\n \"stream_failed\",\n // Withdrawal / cash-out lane (B3). Value leaves the custody Safe to an\n // EXTERNAL 0x wallet. Props are leak-safe: payment_id + document_hash + amount\n // + currency + status + reason — NEVER the external destAddress (it lives on\n // the kind:4 Withdrawal document only). `withdrawal_settled` is WIRED (emitted\n // from the withdraw settlement action via emitServerAwaited); the other three\n // are planned RED targets in FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS.\n \"withdrawal_requested\",\n \"withdrawal_submitted\",\n \"withdrawal_settled\",\n \"withdrawal_failed\",\n] as const;\n\nexport type TelemetryEventName = (typeof TELEMETRY_EVENT_NAMES)[number];\n\nexport type NonEmptyTelemetryEventNames = readonly [TelemetryEventName, ...TelemetryEventName[]];\nexport type FunnelStepPropertyFilter = {\n readonly key: string;\n readonly value: readonly string[];\n readonly operator: \"exact\";\n readonly type: \"event\";\n};\nexport type FunnelJourney = {\n readonly type: \"funnel\";\n readonly steps: NonEmptyTelemetryEventNames;\n readonly drops_on?: NonEmptyTelemetryEventNames;\n readonly step_filters?: Readonly<\n Partial<Record<TelemetryEventName, readonly FunnelStepPropertyFilter[]>>\n >;\n};\nexport type PointEventJourney = {\n readonly type: \"point_event\";\n readonly point_event: TelemetryEventName;\n};\nexport type Journey = FunnelJourney | PointEventJourney;\n\nexport const TELEMETRY_JOURNEYS = {\n returning_user_login: {\n type: \"funnel\",\n steps: [\"auth_otp_requested\", \"auth_otp_delivered\", \"auth_verified\"],\n drops_on: [\"auth_otp_expired\", \"auth_failed\"],\n },\n new_user_first_signin: {\n type: \"funnel\",\n steps: [\n \"auth_otp_requested\",\n \"auth_otp_delivered\",\n \"auth_verified\",\n \"provisioning_safe_created\",\n \"provisioning_safe_confirmed\",\n ],\n drops_on: [\"auth_otp_expired\", \"auth_failed\"],\n },\n sign_out_session_close: {\n type: \"point_event\",\n point_event: \"auth_signed_out\",\n },\n member_activation: {\n type: \"funnel\",\n steps: [\"member_activation_started\", \"member_activation_ready\"],\n drops_on: [\"member_activation_failed\"],\n },\n organization_creation_lifecycle: {\n type: \"funnel\",\n steps: [\"organization_creation_started\", \"organization_creation_ready\"],\n drops_on: [\"organization_creation_failed\"],\n },\n new_member_personal_dashboard: {\n type: \"funnel\",\n steps: [\n \"auth_verified\",\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"member_activation_ready\",\n \"onboarding_dashboard_reached\",\n ],\n step_filters: {\n onboarding_intent_selected: [\n { key: \"intent\", value: [\"personal\"], operator: \"exact\", type: \"event\" },\n { key: \"entry_point\", value: [\"signup\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_profile_submitted: [\n { key: \"intent\", value: [\"personal\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_dashboard_reached: [\n { key: \"intent\", value: [\"personal\"], operator: \"exact\", type: \"event\" },\n ],\n },\n },\n new_member_organization_dashboard: {\n type: \"funnel\",\n steps: [\n \"auth_verified\",\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"onboarding_organization_submitted\",\n \"member_activation_started\",\n \"member_activation_ready\",\n \"organization_creation_started\",\n \"organization_creation_ready\",\n \"onboarding_dashboard_reached\",\n ],\n step_filters: {\n onboarding_intent_selected: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n { key: \"entry_point\", value: [\"signup\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_profile_submitted: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_dashboard_reached: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n ],\n },\n },\n existing_member_organization_dashboard: {\n type: \"funnel\",\n steps: [\n \"onboarding_intent_selected\",\n \"onboarding_organization_submitted\",\n \"organization_creation_started\",\n \"organization_creation_ready\",\n \"onboarding_dashboard_reached\",\n ],\n step_filters: {\n onboarding_intent_selected: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n { key: \"entry_point\", value: [\"dashboard\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_dashboard_reached: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n ],\n },\n },\n // Money domain (M2).\n money_on_screen: {\n type: \"point_event\",\n point_event: \"account_balance_read\",\n },\n fund_account: {\n type: \"funnel\",\n steps: [\"faucet_requested\", \"faucet_confirmed\"],\n drops_on: [\"faucet_failed\"],\n },\n first_value_movement: {\n type: \"funnel\",\n steps: [\"account_balance_read\", \"transfer_requested\", \"transfer_confirmed\"],\n drops_on: [\"transfer_failed\"],\n },\n subaccount_lifecycle: {\n type: \"point_event\",\n point_event: \"subaccount_created\",\n },\n // Organization domain (canon org-domain-model.md §C5). J1 create-org funnel.\n org_creation: {\n type: \"funnel\",\n steps: [\n \"org_create_started\",\n \"org_safe_created\",\n \"org_safe_confirmed\",\n \"org_roles_seeded\",\n \"org_created\",\n ],\n drops_on: [\"org_create_failed\"],\n },\n org_member_onboarding: {\n type: \"funnel\",\n steps: [\"org_invite_sent\", \"org_invite_accepted\", \"org_role_granted\", \"org_member_active\"],\n drops_on: [\"org_invite_expired\", \"org_role_grant_failed\"],\n },\n // Financial-ops domain (ADR-1 money journey + funnel catalog,\n // docs/adr/0006-money-journey-funnel-catalog.md). These reconcile the\n // alpha-scope FE journeys, the J1–J4 telemetry funnels, and the G0–G6 capstone\n // goals into one canonical set. Producers are wired per lane in B1; until then\n // every step/drop is a planned RED target in\n // FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS (ADR-2 seam: planned XOR wired).\n // Org-spend, payroll, and receivable-collect lanes ride the same payment_*\n // events with a source/context prop discriminator — no new event names.\n direct_payment: {\n type: \"funnel\",\n steps: [\n \"payment_requested\",\n \"payment_resolved\",\n \"payment_document_attached\",\n \"payment_submitted\",\n \"payment_settled\",\n ],\n drops_on: [\"payment_failed\"],\n },\n commitment_claim: {\n type: \"funnel\",\n steps: [\"payment_submitted\", \"payment_claimed\"],\n drops_on: [\"payment_cancelled\"],\n },\n commitment_redirect: {\n type: \"point_event\",\n point_event: \"payment_redirected\",\n },\n salary_stream: {\n type: \"funnel\",\n steps: [\"stream_created\", \"stream_claimed\", \"stream_completed\"],\n drops_on: [\"stream_cancelled\", \"stream_failed\"],\n },\n // Cash-out / withdraw lane (B3). USDX leaves the custody Safe to an external\n // 0x wallet; `withdrawal_settled` is the server-confirmed evidence-bound step.\n cash_out: {\n type: \"funnel\",\n steps: [\"withdrawal_requested\", \"withdrawal_submitted\", \"withdrawal_settled\"],\n drops_on: [\"withdrawal_failed\"],\n },\n} as const satisfies Record<string, Journey>;\n\nexport type TelemetryProps = Record<string, unknown>;\n\nexport type TelemetryEvent = {\n readonly name: TelemetryEventName;\n readonly props?: TelemetryProps | undefined;\n};\n\nexport const PII = Schema.String.pipe(Schema.brand(\"PII\"));\nexport type PII = Schema.Schema.Type<typeof PII>;\n\nconst OptionalString = Schema.optional(Schema.String);\nconst AddressSchema: Schema.Codec<Address, string> = Schema.String.pipe(\n Schema.decodeTo(Schema.String, {\n decode: SchemaGetter.transform((value) => value.toLowerCase()),\n encode: SchemaGetter.transform((value) => value),\n }),\n Schema.refine((value): value is Address => EVM_ADDRESS_RE.test(value), {\n message: \"must be 0x + 40 hex chars\",\n }),\n);\nconst AppIdSchema: Schema.Codec<AppId, string> = Schema.String.pipe(\n Schema.refine((value): value is AppId => APP_ID_RE.test(value), {\n message: \"must be app_ plus a ULID\",\n }),\n);\nconst BlockNumberSchema: Schema.Codec<BlockNumber, number> = Schema.Number.pipe(\n Schema.refine((value): value is BlockNumber => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\nconst ChainIdSchema: Schema.Codec<ChainId, number> = Schema.Number.pipe(\n Schema.refine((value): value is ChainId => Number.isSafeInteger(value) && value > 0, {\n message: \"must be a positive safe integer\",\n }),\n);\nconst DurationMsSchema: Schema.Codec<DurationMs, number> = Schema.Number.pipe(\n Schema.refine((value): value is DurationMs => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\nconst EpochMsSchema: Schema.Codec<EpochMs, number> = Schema.Number.pipe(\n Schema.refine((value): value is EpochMs => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\nconst PublishableKeyIdSchema: Schema.Codec<PublishableKeyId, string> = Schema.String.pipe(\n Schema.refine((value): value is PublishableKeyId => value.length > 0, {\n message: \"must be a non-empty string\",\n }),\n);\nconst TxHashSchema: Schema.Codec<TxHash, string> = Schema.String.pipe(\n Schema.refine((value): value is TxHash => BYTES32_RE.test(value), {\n message: \"must be 0x + 64 hex chars\",\n }),\n);\n// Money-domain brands. `account_`/`subaccount_` prefixes mirror the `@capxul/types`\n// brand constructors (`toAccountId`/`toSubAccountId`); WeiAmount is a non-negative\n// integer STRING per `.claude/rules/numeric-parsing.md` (never a float, never a number).\nconst ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;\nconst SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;\nconst WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;\nconst AccountIdSchema: Schema.Codec<AccountId, string> = Schema.String.pipe(\n Schema.refine((value): value is AccountId => ACCOUNT_ID_TELEMETRY_RE.test(value), {\n message: \"must be account_ plus an alphanumeric id\",\n }),\n);\nconst SubAccountIdSchema: Schema.Codec<SubAccountId, string> = Schema.String.pipe(\n Schema.refine((value): value is SubAccountId => SUBACCOUNT_ID_TELEMETRY_RE.test(value), {\n message: \"must be subaccount_ plus an alphanumeric id\",\n }),\n);\nconst WeiAmountSchema: Schema.Codec<WeiAmount, string> = Schema.String.pipe(\n Schema.refine((value): value is WeiAmount => WEI_AMOUNT_TELEMETRY_RE.test(value), {\n message: \"must be a non-negative integer string\",\n }),\n);\nconst CurrencyCodeSchema: Schema.Codec<CurrencyCode, string> = Schema.String.pipe(\n Schema.refine((value): value is CurrencyCode => value.length > 0, {\n message: \"must be a non-empty currency code\",\n }),\n);\nconst BalanceBucketSchema = Schema.Literals([\"zero\", \"nonzero\"]);\nconst TransferDirectionSchema = Schema.Literals([\"add\", \"out\", \"between\"]);\nconst SubAccountOpSchema = Schema.Literals([\"create\", \"rename\", \"delete\"]);\nconst OptionalAccountId = Schema.optional(AccountIdSchema);\nconst OptionalSubAccountId = Schema.optional(SubAccountIdSchema);\nconst OptionalWeiAmount = Schema.optional(WeiAmountSchema);\nconst OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);\nconst OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);\nconst OptionalTransferDirection = Schema.optional(TransferDirectionSchema);\nconst OptionalSubAccountOp = Schema.optional(SubAccountOpSchema);\nconst OptionalTrue = Schema.optional(Schema.Literal(true));\nconst OptionalAddress = Schema.optional(AddressSchema);\nconst OptionalAppId = Schema.optional(AppIdSchema);\nconst OptionalBlockNumber = Schema.optional(BlockNumberSchema);\nconst OptionalChainId = Schema.optional(ChainIdSchema);\nconst OptionalDurationMs = Schema.optional(DurationMsSchema);\nconst OptionalEpochMs = Schema.optional(EpochMsSchema);\nconst OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);\nconst OptionalTxHash = Schema.optional(TxHashSchema);\nconst PAYMENT_ID_TELEMETRY_RE = /^payment_[0-9A-Za-z]+$/;\nconst PAYEE_ID_TELEMETRY_RE = /^payee_[0-9A-Za-z]+$/;\nconst PaymentIdTelemetrySchema = Schema.String.pipe(\n Schema.refine((value): value is string => PAYMENT_ID_TELEMETRY_RE.test(value), {\n message: \"must be payment_ plus an alphanumeric id\",\n }),\n);\nconst PayeeIdTelemetrySchema = Schema.String.pipe(\n Schema.refine((value): value is string => PAYEE_ID_TELEMETRY_RE.test(value), {\n message: \"must be payee_ plus an alphanumeric id\",\n }),\n);\nconst DocumentHashSchema = Schema.String.pipe(\n Schema.refine((value): value is string => BYTES32_RE.test(value), {\n message: \"must be 0x + 64 hex chars\",\n }),\n);\n/**\n * Environment discriminator (ADR-0020 A1 amendment, 2026-08-07). PostHog\n * project 368736 is the SINGLE sink for every environment, so `capxul_env` —\n * not project isolation — is what keeps a production surface from reading dev\n * traffic. It is REQUIRED on every catalog event and every synced artifact\n * filters on it.\n *\n * `unknown` is a defect marker, not an environment: it means a producer\n * reached the transport without declaring where it runs. It is in the union so\n * the property is never ABSENT (an absent property is invisible to a filter,\n * a present `unknown` is loud), and sync v2 never synthesizes an artifact for\n * it.\n */\nexport const CAPXUL_ENVS = [\"development\", \"e2e\", \"staging\", \"production\", \"unknown\"] as const;\nexport type CapxulEnv = (typeof CAPXUL_ENVS)[number];\n\n/** Environments a synced product surface may be built for (`unknown` cannot). */\nexport const SYNCABLE_CAPXUL_ENVS = [\"development\", \"e2e\", \"staging\", \"production\"] as const;\n\n/**\n * Which half of the system emitted the event. REQUIRED alongside `capxul_env`\n * so a name that two halves can produce (settlement, auth) stays attributable.\n */\nexport const TELEMETRY_PRODUCERS = [\"server\", \"browser\", \"sdk\", \"mcp\", \"e2e\"] as const;\nexport type TelemetryProducer = (typeof TELEMETRY_PRODUCERS)[number];\n\nconst CapxulEnvSchema = Schema.Literals(CAPXUL_ENVS);\nconst TelemetryProducerSchema = Schema.Literals(TELEMETRY_PRODUCERS);\n\n/**\n * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and\n * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema\n * decode instead of silently shipping an unattributable event. Call sites do\n * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,\n * which is the only place that knows where the process runs.\n */\nconst TelemetryEnvelopeProps = {\n capxul_env: CapxulEnvSchema,\n producer: TelemetryProducerSchema,\n journey_id: OptionalString,\n correlation_id: OptionalString,\n sdk_version: OptionalString,\n};\n\nexport interface TelemetryEnvelopeDefaults {\n readonly capxul_env: CapxulEnv;\n readonly producer: TelemetryProducer;\n}\n\n/**\n * Stamp the required envelope onto an event at its emit boundary. Call-site\n * props win on conflict: a relay that already knows the true producer (the\n * browser-failure relay stamps `browser` while running on the server) must not\n * be overwritten by the transport's own default.\n */\nexport function stampTelemetryEnvelope(\n event: TelemetryEvent,\n defaults: TelemetryEnvelopeDefaults,\n): TelemetryEvent {\n return { name: event.name, props: { ...defaults, ...event.props } };\n}\n\nconst AuthOtpRequestedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n email: Schema.optional(PII),\n email_domain: OptionalString,\n});\nconst AuthOtpDeliveredProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n durationMs: OptionalDurationMs,\n email: Schema.optional(PII),\n email_domain: OptionalString,\n resendMessageId: OptionalString,\n});\nconst AuthOtpExpiredProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n email: Schema.optional(PII),\n email_domain: OptionalString,\n});\nconst AuthVerifiedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n auth_type: OptionalString,\n});\nconst AuthFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n email: Schema.optional(PII),\n auth_type: OptionalString,\n reason: OptionalString,\n});\nconst AuthSignedOutProps = Schema.Struct(TelemetryEnvelopeProps);\nconst ProvisioningSafeCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n safe_address: OptionalAddress,\n});\nconst ProvisioningSafeConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n chainId: OptionalChainId,\n deployedAt: OptionalEpochMs,\n deployedAtBlock: OptionalBlockNumber,\n deployTxHash: OptionalTxHash,\n durationMs: OptionalDurationMs,\n safe_address: OptionalAddress,\n userOpHash: OptionalTxHash,\n});\nconst BootstrapResolvedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n applicationId: OptionalAppId,\n durationMs: OptionalDurationMs,\n env: OptionalString,\n keyId: OptionalPublishableKeyId,\n origin: OptionalString,\n});\nconst BootstrapFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n applicationId: OptionalAppId,\n durationMs: OptionalDurationMs,\n origin: OptionalString,\n reason: OptionalString,\n});\n\n// Money domain (M2). No sub-account NAMES, no raw emails, no raw addresses —\n// only branded ids, WeiAmount strings, buckets, and durations. See\n// packages/observability/CONTEXT.md \"Money domain\".\nconst AccountBalanceReadProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n account_id: OptionalAccountId,\n currency: OptionalCurrencyCode,\n balance_bucket: OptionalBalanceBucket,\n durationMs: OptionalDurationMs,\n});\nconst AccountBalanceFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n reason: OptionalString,\n});\nconst FaucetRequestedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n chainId: OptionalChainId,\n});\nconst FaucetConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n chainId: OptionalChainId,\n txHash: OptionalTxHash,\n durationMs: OptionalDurationMs,\n});\nconst FaucetFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n reason: OptionalString,\n});\nconst SubaccountCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n sub_account_id: OptionalSubAccountId,\n durationMs: OptionalDurationMs,\n});\nconst SubaccountRenamedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n sub_account_id: OptionalSubAccountId,\n});\nconst SubaccountDeletedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n sub_account_id: OptionalSubAccountId,\n});\nconst SubaccountOpFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n op: OptionalSubAccountOp,\n reason: OptionalString,\n});\nconst TransferRequestedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n direction: OptionalTransferDirection,\n});\nconst TransferBackendReceivedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n direction: OptionalTransferDirection,\n});\nconst TransferConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n direction: OptionalTransferDirection,\n available_bucket: OptionalBalanceBucket,\n txless: OptionalTrue,\n durationMs: OptionalDurationMs,\n});\nconst TransferFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n reason: OptionalString,\n});\n\n// Organization domain (canon org-domain-model.md §C5). No raw emails (PII):\n// `email_domain` only; `org_id` is the public `org_`-shaped brand (also the\n// PostHog `organization` group key); `safe_address` is the Org Safe; `role` is\n// the seeded role label; `reason` is the failure cause. See\n// packages/observability/CONTEXT.md \"Organization domain\".\nconst ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;\nconst OrgIdTelemetrySchema: Schema.Codec<string, string> = Schema.String.pipe(\n Schema.refine((value): value is string => ORG_ID_TELEMETRY_RE.test(value), {\n message: \"must be org_ plus an alphanumeric id\",\n }),\n);\nconst OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);\nconst AttemptNumberSchema = Schema.Number.pipe(\n Schema.refine((value): value is number => Number.isSafeInteger(value) && value > 0, {\n message: \"must be a positive safe integer\",\n }),\n);\nconst OnboardingStageSchema = Schema.Literals([\n \"profile\",\n \"accountProvisioning\",\n \"accountClaim\",\n \"preparingFounderAccount\",\n \"awaitingFounderAuthorization\",\n \"submittingBootstrap\",\n \"confirmingBootstrap\",\n]);\n// The #816 lifecycle family: strict (non-optional) props plus the shared\n// envelope. `producer` comes from the envelope now — the literal \"server\"\n// constraint moved to the emit boundary, which is the only place that knows.\nconst MemberActivationStartedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n});\nconst MemberActivationReadyProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n duration_ms: DurationMsSchema,\n});\nconst MemberActivationFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n stage: OnboardingStageSchema,\n error_code: Schema.String,\n retryable: Schema.Boolean,\n});\nconst OrganizationCreationStartedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n organization_id: OrgIdTelemetrySchema,\n attempt_number: AttemptNumberSchema,\n});\nconst OrganizationCreationReadyProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n organization_id: OrgIdTelemetrySchema,\n attempt_number: AttemptNumberSchema,\n duration_ms: DurationMsSchema,\n});\nconst OrganizationCreationFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n organization_id: OrgIdTelemetrySchema,\n attempt_number: AttemptNumberSchema,\n stage: OnboardingStageSchema,\n error_code: Schema.String,\n retryable: Schema.Boolean,\n});\nconst OnboardingIntentSchema = Schema.Literals([\"personal\", \"organization\"]);\nconst OnboardingIntentSelectedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n intent: OnboardingIntentSchema,\n entry_point: Schema.String,\n});\nconst OnboardingProfileSubmittedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n intent: OnboardingIntentSchema,\n});\nconst OnboardingOrganizationSubmittedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n});\nconst OnboardingDashboardReachedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n intent: OnboardingIntentSchema,\n organization_id: Schema.optional(OrgIdTelemetrySchema),\n});\nconst OrgCreateStartedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n email_domain: OptionalString,\n template: OptionalString,\n});\nconst OrgSafeCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n safe_address: OptionalAddress,\n});\nconst OrgSafeConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n safe_address: OptionalAddress,\n durationMs: OptionalDurationMs,\n});\nconst OrgRolesSeededProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n role: OptionalString,\n txHash: OptionalTxHash,\n});\nconst OrgCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n safe_address: OptionalAddress,\n durationMs: OptionalDurationMs,\n});\nconst OrgCreateFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n reason: OptionalString,\n});\nconst OrgInviteSentProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n email_domain: OptionalString,\n role: OptionalString,\n status: OptionalString,\n});\nconst OrgInviteAcceptedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n});\nconst OrgRoleGrantedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n txHash: OptionalTxHash,\n});\nconst OrgMemberActiveProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n durationMs: OptionalDurationMs,\n});\nconst OrgMemberRemovedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n txHash: OptionalTxHash,\n});\nconst OrgInviteExpiredProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n email_domain: OptionalString,\n reason: OptionalString,\n role: OptionalString,\n status: OptionalString,\n});\nconst OrgRoleGrantFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n reason: OptionalString,\n role: OptionalString,\n});\n\n// Financial-ops target telemetry (G0 RED scaffold). Props intentionally carry\n// product ids, document hashes, buckets, and reasons. No raw emails, no raw\n// addresses, no userOp hashes, and no chain custody vocabulary.\nconst OptionalPaymentId = Schema.optional(PaymentIdTelemetrySchema);\nconst OptionalPayeeId = Schema.optional(PayeeIdTelemetrySchema);\nconst OptionalDocumentHash = Schema.optional(DocumentHashSchema);\nconst PaymentTargetTelemetryProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n payment_id: OptionalPaymentId,\n payee_id: OptionalPayeeId,\n document_hash: OptionalDocumentHash,\n amount: OptionalWeiAmount,\n currency: OptionalCurrencyCode,\n status: OptionalString,\n reason: OptionalString,\n durationMs: OptionalDurationMs,\n});\nconst StreamTargetTelemetryProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n payment_id: OptionalPaymentId,\n document_hash: OptionalDocumentHash,\n amount: OptionalWeiAmount,\n currency: OptionalCurrencyCode,\n status: OptionalString,\n available_bucket: OptionalBalanceBucket,\n reason: OptionalString,\n durationMs: OptionalDurationMs,\n});\n// Withdrawal / cash-out lane (B3). Leak-safe: product id + document hash +\n// amount + currency + status + reason + duration. NO destAddress (the external\n// 0x lives on the kind:4 Withdrawal document only), no txHash/userOpHash, no\n// chain custody vocabulary.\nconst WithdrawalTargetTelemetryProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n payment_id: OptionalPaymentId,\n document_hash: OptionalDocumentHash,\n amount: OptionalWeiAmount,\n currency: OptionalCurrencyCode,\n status: OptionalString,\n reason: OptionalString,\n durationMs: OptionalDurationMs,\n});\n\nexport const AuthOtpRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_requested\"),\n props: AuthOtpRequestedProps,\n});\nexport const AuthOtpDeliveredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_delivered\"),\n props: AuthOtpDeliveredProps,\n});\nexport const AuthOtpExpiredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_expired\"),\n props: AuthOtpExpiredProps,\n});\nexport const AuthVerifiedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_verified\"),\n props: AuthVerifiedProps,\n});\nexport const AuthFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_failed\"),\n props: AuthFailedProps,\n});\nexport const AuthSignedOutTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_signed_out\"),\n props: AuthSignedOutProps,\n});\nexport const OnboardingIntentSelectedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_intent_selected\"),\n props: OnboardingIntentSelectedProps,\n});\nexport const OnboardingProfileSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_profile_submitted\"),\n props: OnboardingProfileSubmittedProps,\n});\nexport const OnboardingOrganizationSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_organization_submitted\"),\n props: OnboardingOrganizationSubmittedProps,\n});\nexport const OnboardingDashboardReachedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_dashboard_reached\"),\n props: OnboardingDashboardReachedProps,\n});\nexport const ProvisioningSafeCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"provisioning_safe_created\"),\n props: ProvisioningSafeCreatedProps,\n});\nexport const ProvisioningSafeConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"provisioning_safe_confirmed\"),\n props: ProvisioningSafeConfirmedProps,\n});\nexport const BootstrapResolvedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"bootstrap_resolved\"),\n props: BootstrapResolvedProps,\n});\nexport const BootstrapFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"bootstrap_failed\"),\n props: BootstrapFailedProps,\n});\nexport const MemberActivationStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"member_activation_started\"),\n props: MemberActivationStartedProps,\n});\nexport const MemberActivationReadyTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"member_activation_ready\"),\n props: MemberActivationReadyProps,\n});\nexport const MemberActivationFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"member_activation_failed\"),\n props: MemberActivationFailedProps,\n});\nexport const OrganizationCreationStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"organization_creation_started\"),\n props: OrganizationCreationStartedProps,\n});\nexport const OrganizationCreationReadyTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"organization_creation_ready\"),\n props: OrganizationCreationReadyProps,\n});\nexport const OrganizationCreationFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"organization_creation_failed\"),\n props: OrganizationCreationFailedProps,\n});\nexport const AccountBalanceReadTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"account_balance_read\"),\n props: AccountBalanceReadProps,\n});\nexport const AccountBalanceFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"account_balance_failed\"),\n props: AccountBalanceFailedProps,\n});\nexport const FaucetRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_requested\"),\n props: FaucetRequestedProps,\n});\nexport const FaucetConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_confirmed\"),\n props: FaucetConfirmedProps,\n});\nexport const FaucetFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_failed\"),\n props: FaucetFailedProps,\n});\nexport const SubaccountCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_created\"),\n props: SubaccountCreatedProps,\n});\nexport const SubaccountRenamedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_renamed\"),\n props: SubaccountRenamedProps,\n});\nexport const SubaccountDeletedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_deleted\"),\n props: SubaccountDeletedProps,\n});\nexport const SubaccountOpFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_op_failed\"),\n props: SubaccountOpFailedProps,\n});\nexport const TransferRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_requested\"),\n props: TransferRequestedProps,\n});\nexport const TransferBackendReceivedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_backend_received\"),\n props: TransferBackendReceivedProps,\n});\nexport const TransferConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_confirmed\"),\n props: TransferConfirmedProps,\n});\nexport const TransferFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_failed\"),\n props: TransferFailedProps,\n});\nexport const OrgCreateStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_create_started\"),\n props: OrgCreateStartedProps,\n});\nexport const OrgSafeCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_safe_created\"),\n props: OrgSafeCreatedProps,\n});\nexport const OrgSafeConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_safe_confirmed\"),\n props: OrgSafeConfirmedProps,\n});\nexport const OrgRolesSeededTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_roles_seeded\"),\n props: OrgRolesSeededProps,\n});\nexport const OrgCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_created\"),\n props: OrgCreatedProps,\n});\nexport const OrgCreateFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_create_failed\"),\n props: OrgCreateFailedProps,\n});\nexport const OrgInviteSentTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_sent\"),\n props: OrgInviteSentProps,\n});\nexport const OrgInviteAcceptedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_accepted\"),\n props: OrgInviteAcceptedProps,\n});\nexport const OrgRoleGrantedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_role_granted\"),\n props: OrgRoleGrantedProps,\n});\nexport const OrgMemberActiveTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_member_active\"),\n props: OrgMemberActiveProps,\n});\nexport const OrgMemberRemovedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_member_removed\"),\n props: OrgMemberRemovedProps,\n});\nexport const OrgInviteExpiredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_expired\"),\n props: OrgInviteExpiredProps,\n});\nexport const OrgRoleGrantFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_role_grant_failed\"),\n props: OrgRoleGrantFailedProps,\n});\nexport const PaymentRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_requested\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentResolvedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_resolved\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentDocumentAttachedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_document_attached\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_submitted\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentSettledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_settled\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentClaimedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_claimed\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentCancelledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_cancelled\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentRedirectedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_redirected\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_failed\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const StreamCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_created\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamClaimedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_claimed\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamCancelledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_cancelled\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamCompletedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_completed\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_failed\"),\n props: StreamTargetTelemetryProps,\n});\nexport const WithdrawalRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_requested\"),\n props: WithdrawalTargetTelemetryProps,\n});\nexport const WithdrawalSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_submitted\"),\n props: WithdrawalTargetTelemetryProps,\n});\nexport const WithdrawalSettledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_settled\"),\n props: WithdrawalTargetTelemetryProps,\n});\nexport const WithdrawalFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_failed\"),\n props: WithdrawalTargetTelemetryProps,\n});\n\nexport const TELEMETRY_EVENT_SCHEMAS = {\n auth_otp_requested: AuthOtpRequestedTelemetryEventSchema,\n auth_otp_delivered: AuthOtpDeliveredTelemetryEventSchema,\n auth_otp_expired: AuthOtpExpiredTelemetryEventSchema,\n auth_verified: AuthVerifiedTelemetryEventSchema,\n auth_failed: AuthFailedTelemetryEventSchema,\n auth_signed_out: AuthSignedOutTelemetryEventSchema,\n onboarding_intent_selected: OnboardingIntentSelectedTelemetryEventSchema,\n onboarding_profile_submitted: OnboardingProfileSubmittedTelemetryEventSchema,\n onboarding_organization_submitted: OnboardingOrganizationSubmittedTelemetryEventSchema,\n onboarding_dashboard_reached: OnboardingDashboardReachedTelemetryEventSchema,\n provisioning_safe_created: ProvisioningSafeCreatedTelemetryEventSchema,\n provisioning_safe_confirmed: ProvisioningSafeConfirmedTelemetryEventSchema,\n bootstrap_resolved: BootstrapResolvedTelemetryEventSchema,\n bootstrap_failed: BootstrapFailedTelemetryEventSchema,\n member_activation_started: MemberActivationStartedTelemetryEventSchema,\n member_activation_ready: MemberActivationReadyTelemetryEventSchema,\n member_activation_failed: MemberActivationFailedTelemetryEventSchema,\n organization_creation_started: OrganizationCreationStartedTelemetryEventSchema,\n organization_creation_ready: OrganizationCreationReadyTelemetryEventSchema,\n organization_creation_failed: OrganizationCreationFailedTelemetryEventSchema,\n account_balance_read: AccountBalanceReadTelemetryEventSchema,\n account_balance_failed: AccountBalanceFailedTelemetryEventSchema,\n faucet_requested: FaucetRequestedTelemetryEventSchema,\n faucet_confirmed: FaucetConfirmedTelemetryEventSchema,\n faucet_failed: FaucetFailedTelemetryEventSchema,\n subaccount_created: SubaccountCreatedTelemetryEventSchema,\n subaccount_renamed: SubaccountRenamedTelemetryEventSchema,\n subaccount_deleted: SubaccountDeletedTelemetryEventSchema,\n subaccount_op_failed: SubaccountOpFailedTelemetryEventSchema,\n transfer_requested: TransferRequestedTelemetryEventSchema,\n transfer_backend_received: TransferBackendReceivedTelemetryEventSchema,\n transfer_confirmed: TransferConfirmedTelemetryEventSchema,\n transfer_failed: TransferFailedTelemetryEventSchema,\n org_create_started: OrgCreateStartedTelemetryEventSchema,\n org_safe_created: OrgSafeCreatedTelemetryEventSchema,\n org_safe_confirmed: OrgSafeConfirmedTelemetryEventSchema,\n org_roles_seeded: OrgRolesSeededTelemetryEventSchema,\n org_created: OrgCreatedTelemetryEventSchema,\n org_create_failed: OrgCreateFailedTelemetryEventSchema,\n org_invite_sent: OrgInviteSentTelemetryEventSchema,\n org_invite_accepted: OrgInviteAcceptedTelemetryEventSchema,\n org_role_granted: OrgRoleGrantedTelemetryEventSchema,\n org_member_active: OrgMemberActiveTelemetryEventSchema,\n org_member_removed: OrgMemberRemovedTelemetryEventSchema,\n org_invite_expired: OrgInviteExpiredTelemetryEventSchema,\n org_role_grant_failed: OrgRoleGrantFailedTelemetryEventSchema,\n payment_requested: PaymentRequestedTelemetryEventSchema,\n payment_resolved: PaymentResolvedTelemetryEventSchema,\n payment_document_attached: PaymentDocumentAttachedTelemetryEventSchema,\n payment_submitted: PaymentSubmittedTelemetryEventSchema,\n payment_settled: PaymentSettledTelemetryEventSchema,\n payment_claimed: PaymentClaimedTelemetryEventSchema,\n payment_cancelled: PaymentCancelledTelemetryEventSchema,\n payment_redirected: PaymentRedirectedTelemetryEventSchema,\n payment_failed: PaymentFailedTelemetryEventSchema,\n stream_created: StreamCreatedTelemetryEventSchema,\n stream_claimed: StreamClaimedTelemetryEventSchema,\n stream_cancelled: StreamCancelledTelemetryEventSchema,\n stream_completed: StreamCompletedTelemetryEventSchema,\n stream_failed: StreamFailedTelemetryEventSchema,\n withdrawal_requested: WithdrawalRequestedTelemetryEventSchema,\n withdrawal_submitted: WithdrawalSubmittedTelemetryEventSchema,\n withdrawal_settled: WithdrawalSettledTelemetryEventSchema,\n withdrawal_failed: WithdrawalFailedTelemetryEventSchema,\n} as const;\n\nexport const FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS = [\n { eventName: \"payment_requested\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"payment_resolved\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"payment_document_attached\", ownerIssue: 486, producer: \"sdk-target\" },\n { eventName: \"payment_submitted\", ownerIssue: 410, producer: \"sdk-target\" },\n // payment_settled WIRED in B1 → emitted from financialOps/actions.ts. #575 wired\n // the settle lanes: direct pay (markPaymentSettled) via the awaited\n // emitSettledTelemetry, and org spend/payroll (applyOrgPaymentRecord) via the\n // scheduled emitScheduledSettledTelemetry. (#1144 demolished the workbench\n // execute and receivable collect lanes; the two literal producers stay.) The\n // ADR-0007 rule was relaxed from exactly-one to ≥1 for this reason. Absent\n // here per planned-XOR-wired.\n //\n // #575 WIRED the commitment-resolution backend producers (financialOps/actions.ts:\n // claimCommitment → payment_claimed | stream_claimed | stream_completed;\n // cancelCommitment → payment_cancelled | stream_cancelled; redirectCommitment →\n // payment_redirected). All absent here per planned-XOR-wired.\n { eventName: \"payment_failed\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"stream_created\", ownerIssue: 411, producer: \"sdk-target\" },\n { eventName: \"stream_failed\", ownerIssue: 411, producer: \"sdk-target\" },\n // Withdrawal / cash-out lane (B3). `withdrawal_settled` is WIRED (emitted from\n // financialOps/actions.ts markWithdrawalSettled via emitServerAwaited) — per\n // planned-XOR-wired it is ABSENT here. The other three stay RED targets until\n // their producers land.\n { eventName: \"withdrawal_requested\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"withdrawal_submitted\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"withdrawal_failed\", ownerIssue: 410, producer: \"sdk-target\" },\n] as const;\n\n/**\n * Catalog events whose product mapper remains gated on the #1150 frontend\n * adoption. L1 S1 removes their retired SDK-flow producers without inventing\n * replacements inside the identity actor. The telemetry-spine gate enforces\n * planned-XOR-wired: a name must leave this list in the same change that adds\n * its real product-boundary producer.\n */\nexport const PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS = [\"auth_otp_expired\"] as const;\n\n/** Catalogued browser observations whose only legal producer lands in L1 S6. */\nexport const BROWSER_GATED_TELEMETRY_EVENTS = [\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"onboarding_organization_submitted\",\n \"onboarding_dashboard_reached\",\n] as const;\n\nexport interface TelemetryIdentifyInput {\n readonly distinctId: string;\n readonly anonDistinctId?: AnonymousDistinctId;\n readonly traits?: TelemetryProps;\n readonly properties?: TelemetryProps;\n}\n\nexport interface TelemetryGroupInput {\n readonly groupType: string;\n readonly groupKey: string;\n readonly properties?: TelemetryProps;\n}\n\nimport type { TelemetryPort, HandledErrorReportContext } from \"./telemetry-port\";\nexport type { TelemetryPort, HandledErrorReportContext } from \"./telemetry-port\";\n\nexport type TrackHandler = (name: TelemetryEventName, props?: TelemetryProps) => void;\n\nlet trackHandler: TrackHandler = () => {};\n\nexport function setTrackHandler(handler: TrackHandler): TrackHandler {\n const previous = trackHandler;\n trackHandler = handler;\n return previous;\n}\n\nexport function getTrackHandler(): TrackHandler {\n return trackHandler;\n}\n\nexport function track(name: TelemetryEventName, props?: TelemetryProps): void {\n trackHandler(name, props);\n}\n\nexport interface TelemetryRedactionOptions {\n readonly rawMode?: boolean;\n}\n\nexport function redactTelemetryEvent(\n event: TelemetryEvent,\n options: TelemetryRedactionOptions = {},\n): TelemetryEvent {\n const props = redactTelemetryProps(event.name, event.props, options);\n return props === undefined ? { name: event.name } : { name: event.name, props };\n}\n\nexport function redactTelemetryProps(\n name: TelemetryEventName,\n props: TelemetryProps | undefined,\n options: TelemetryRedactionOptions = {},\n): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n\n const clone = cloneProps(props);\n if (options.rawMode === true) return clone;\n\n for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) {\n redactProperty(clone, key);\n }\n return clone;\n}\n\n/**\n * The vendor-neutral shape needed by a PostHog `before_send` callback.\n * Keeping this structural avoids making the observability contract depend on\n * posthog-js while still giving browser hosts one shared URL-scrubbing policy.\n */\nexport interface PostHogBrowserCapture {\n readonly event: string;\n properties: Record<string, unknown>;\n $set?: Record<string, unknown>;\n $set_once?: Record<string, unknown>;\n}\n\n/**\n * Remove query strings and fragments from every PostHog URL/referrer/path\n * property before transport. Browser applications may carry emails, draft ids,\n * or other capabilities in the URL; those values must never leave the origin.\n *\n * The callback mutates and returns the supplied event, matching PostHog's\n * `before_send` contract while preserving the event's full structural type.\n */\nexport function sanitizePostHogBrowserEvent<T extends PostHogBrowserCapture | null>(event: T): T {\n if (event === null) return event;\n\n const seen = new WeakSet<object>();\n sanitizePostHogBrowserValue(event.properties, seen);\n if (event.$set !== undefined) sanitizePostHogBrowserValue(event.$set, seen);\n if (event.$set_once !== undefined) sanitizePostHogBrowserValue(event.$set_once, seen);\n return event;\n}\n\n/**\n * Sanitize AND stamp. Every browser event leaves with `capxul_env` and\n * `producer: \"browser\"` on it, because the browser half has no transport of\n * its own to stamp at — `before_send` is the one funnel every capture,\n * pageview, exception and replay-meta event passes through. Forgetting to\n * register a super-property is therefore not a failure mode.\n */\nexport function createCapxulBeforeSend(\n capxulEnv: CapxulEnv,\n): <T extends PostHogBrowserCapture | null>(event: T) => T {\n return (event) => {\n const sanitized = sanitizePostHogBrowserEvent(event);\n if (sanitized === null) return sanitized;\n sanitized.properties.capxul_env = capxulEnv;\n sanitized.properties.producer ??= \"browser\" satisfies TelemetryProducer;\n return sanitized;\n };\n}\n\nexport type PostHogBeforeSend = ReturnType<typeof createCapxulBeforeSend>;\n\n/**\n * ADR-0016 posture, unchanged: capability-URL utility apps (approval links,\n * docs). No persistence, no autocapture, no replay, no flags, pathname-only\n * pageviews. Survives the app demolition as a library.\n */\nexport interface PostHogUtilityAppOptions {\n readonly api_host: string;\n readonly defaults: \"2026-01-30\";\n readonly autocapture: false;\n readonly capture_pageview: false;\n readonly capture_pageleave: true;\n readonly disable_session_recording: true;\n readonly disable_persistence: true;\n readonly capture_heatmaps: false;\n readonly capture_exceptions: false;\n readonly capture_performance: false;\n readonly disable_surveys: true;\n readonly disable_web_experiments: true;\n readonly disable_product_tours: true;\n readonly disable_conversations: true;\n readonly disable_external_dependency_loading: true;\n readonly person_profiles: \"identified_only\";\n readonly advanced_disable_flags: true;\n readonly save_campaign_params: false;\n readonly save_referrer: false;\n readonly before_send: PostHogBeforeSend;\n}\n\n/** Back-compat alias for the pre-ADR-0020 name. */\nexport type PostHogBrowserOptions = PostHogUtilityAppOptions;\n\n/**\n * ADR-0020 A6 product posture: same sanitizer / slim-bundle / token-guard core\n * as the utility profile, but the three toggles a PRODUCT needs and a\n * capability-URL utility must not have —\n *\n * - `disable_persistence: false` — J1 spans an OTP reload; without persistence\n * step 1 and step 3 are different anonymous \"users\" and every multi-page\n * funnel lies.\n * - identify-driven person profiles (ADR-0020 A2 wires the calls at L1).\n * - session replay, PRODUCTION only, fully masked (inputs, all text, no\n * canvas, no header/body capture). Below production it stays off, which is\n * also why external dependency loading (the recorder script) stays blocked\n * there.\n *\n * Autocapture stays OFF: funnels run on catalog events, not on DOM guesses.\n */\nexport interface PostHogProductAppOptions {\n readonly api_host: string;\n readonly defaults: \"2026-01-30\";\n readonly autocapture: false;\n readonly capture_pageview: false;\n readonly capture_pageleave: true;\n readonly disable_session_recording: boolean;\n readonly disable_persistence: false;\n readonly capture_heatmaps: false;\n readonly capture_exceptions: true;\n readonly capture_performance: false;\n readonly disable_surveys: true;\n readonly disable_web_experiments: true;\n readonly disable_product_tours: true;\n readonly disable_conversations: true;\n readonly disable_external_dependency_loading: boolean;\n readonly person_profiles: \"identified_only\";\n readonly advanced_disable_flags: true;\n readonly save_campaign_params: false;\n readonly save_referrer: false;\n readonly session_recording: {\n readonly maskAllInputs: true;\n readonly maskTextSelector: \"*\";\n readonly captureCanvas: { readonly recordCanvas: false };\n readonly recordHeaders: false;\n readonly recordBody: false;\n };\n readonly before_send: PostHogBeforeSend;\n}\n\nexport interface CapxulBrowserAnalyticsInput {\n readonly key: string | undefined;\n readonly host: string;\n /** Where this browser build runs. Stamped on every event it sends. */\n readonly capxulEnv: CapxulEnv;\n}\n\n/** Back-compat alias for the pre-ADR-0020 name. */\nexport type InitializePostHogBrowserAnalyticsInput = CapxulBrowserAnalyticsInput;\n\nexport function utilityAppAnalytics(input: CapxulBrowserAnalyticsInput): PostHogUtilityAppOptions {\n return {\n api_host: input.host,\n defaults: \"2026-01-30\",\n autocapture: false,\n capture_pageview: false,\n capture_pageleave: true,\n disable_session_recording: true,\n disable_persistence: true,\n capture_heatmaps: false,\n capture_exceptions: false,\n capture_performance: false,\n disable_surveys: true,\n disable_web_experiments: true,\n disable_product_tours: true,\n disable_conversations: true,\n disable_external_dependency_loading: true,\n person_profiles: \"identified_only\",\n advanced_disable_flags: true,\n save_campaign_params: false,\n save_referrer: false,\n before_send: createCapxulBeforeSend(input.capxulEnv),\n };\n}\n\nexport function productAppAnalytics(input: CapxulBrowserAnalyticsInput): PostHogProductAppOptions {\n const replay = input.capxulEnv === \"production\";\n return {\n api_host: input.host,\n defaults: \"2026-01-30\",\n autocapture: false,\n capture_pageview: false,\n capture_pageleave: true,\n disable_session_recording: !replay,\n disable_persistence: false,\n capture_heatmaps: false,\n capture_exceptions: true,\n capture_performance: false,\n disable_surveys: true,\n disable_web_experiments: true,\n disable_product_tours: true,\n disable_conversations: true,\n disable_external_dependency_loading: !replay,\n person_profiles: \"identified_only\",\n advanced_disable_flags: true,\n save_campaign_params: false,\n save_referrer: false,\n session_recording: {\n maskAllInputs: true,\n maskTextSelector: \"*\",\n captureCanvas: { recordCanvas: false },\n recordHeaders: false,\n recordBody: false,\n },\n before_send: createCapxulBeforeSend(input.capxulEnv),\n };\n}\n\nexport type PostHogBrowserInitialize<Options, T> = (key: string, options: Options) => T;\n\nexport interface PostHogBrowserPageviewClient {\n capture(event: \"$pageview\", properties: Readonly<Record<string, unknown>>): unknown;\n}\n\n/**\n * Apply a named privacy profile before an application-owned PostHog client\n * initializes. Hosts still own the vendor client and lifecycle; this helper\n * centralizes the security-relevant options and the missing-key opt-out (no\n * key ⇒ no client ⇒ no network call).\n */\nexport function initializeCapxulBrowserAnalytics<Options, T>(\n profile: (input: CapxulBrowserAnalyticsInput) => Options,\n input: CapxulBrowserAnalyticsInput,\n initialize: PostHogBrowserInitialize<Options, T>,\n): T | undefined {\n const key = input.key?.trim();\n if (key === undefined || key.length === 0) return undefined;\n\n try {\n return initialize(key, profile(input));\n } catch {\n return undefined;\n }\n}\n\n/** The utility profile, pre-bound — the shape ADR-0016's consumers already use. */\nexport function initializePostHogBrowserAnalytics<T>(\n input: CapxulBrowserAnalyticsInput,\n initialize: PostHogBrowserInitialize<PostHogUtilityAppOptions, T>,\n): T | undefined {\n return initializeCapxulBrowserAnalytics(utilityAppAnalytics, input, initialize);\n}\n\n/**\n * Build an explicit SPA pageview sink for toolbar-free PostHog clients. The\n * pathname-only input avoids query capabilities, repeated pathnames are\n * deduplicated, and vendor failures remain best-effort.\n */\nexport function createPostHogBrowserPageviewTracker(\n client: PostHogBrowserPageviewClient | null | undefined,\n): (pathname: string) => void {\n let previousPathname: string | undefined;\n return (pathname) => {\n if (client === null || client === undefined) return;\n const safePathname = stripUrlQueryAndFragment(pathname);\n if (safePathname === previousPathname) return;\n try {\n void Promise.resolve(client.capture(\"$pageview\", { $pathname: safePathname })).catch(\n () => {},\n );\n previousPathname = safePathname;\n } catch {\n // Analytics is best effort and cannot interrupt application navigation.\n }\n };\n}\n\nfunction sanitizePostHogBrowserValue(value: unknown, seen: WeakSet<object>): void {\n if (typeof value !== \"object\" || value === null || seen.has(value)) return;\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) sanitizePostHogBrowserValue(item, seen);\n return;\n }\n\n const properties = value as Record<string, unknown>;\n for (const [key, nestedValue] of Object.entries(properties)) {\n if (isPostHogQueryDerivedProperty(key)) {\n delete properties[key];\n continue;\n }\n if (typeof nestedValue === \"string\" && isPostHogUrlProperty(key)) {\n properties[key] = stripUrlQueryAndFragment(nestedValue);\n continue;\n }\n sanitizePostHogBrowserValue(nestedValue, seen);\n }\n}\n\nconst POSTHOG_QUERY_DERIVED_PROPERTY_NAMES = [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_content\",\n \"utm_term\",\n \"gad_source\",\n \"mc_cid\",\n \"gclid\",\n \"gclsrc\",\n \"dclid\",\n \"gbraid\",\n \"wbraid\",\n \"fbclid\",\n \"msclkid\",\n \"twclid\",\n \"li_fat_id\",\n \"igshid\",\n \"ttclid\",\n \"rdt_cid\",\n \"epik\",\n \"qclid\",\n \"sccid\",\n \"irclid\",\n \"_kx\",\n \"ph_keyword\",\n] as const;\n\nfunction isPostHogQueryDerivedProperty(key: string): boolean {\n const normalized = key.toLowerCase();\n return POSTHOG_QUERY_DERIVED_PROPERTY_NAMES.some(\n (propertyName) =>\n normalized === propertyName ||\n normalized.endsWith(`_${propertyName}`) ||\n normalized.endsWith(`$${propertyName}`),\n );\n}\n\nfunction isPostHogUrlProperty(key: string): boolean {\n const normalized = key.toLowerCase();\n return (\n normalized.includes(\"url\") ||\n normalized.includes(\"referrer\") ||\n normalized.includes(\"path\") ||\n normalized.includes(\"filename\")\n );\n}\n\nfunction stripUrlQueryAndFragment(value: string): string {\n const queryIndex = value.indexOf(\"?\");\n const fragmentIndex = value.indexOf(\"#\");\n if (queryIndex === -1 && fragmentIndex === -1) return value;\n if (queryIndex === -1) return value.slice(0, fragmentIndex);\n if (fragmentIndex === -1) return value.slice(0, queryIndex);\n return value.slice(0, Math.min(queryIndex, fragmentIndex));\n}\n\nexport class RecordingTelemetryAdapter implements TelemetryPort {\n readonly #events: TelemetryEvent[] = [];\n readonly #rawMode: boolean;\n\n constructor(options: TelemetryRedactionOptions = {}) {\n this.#rawMode = options.rawMode === true;\n }\n\n get events(): readonly TelemetryEvent[] {\n return this.#events.map((event) => cloneEvent(event));\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never> {\n return Effect.sync(() => {\n this.#events.push(redactTelemetryEvent(event, { rawMode: this.#rawMode }));\n });\n }\n\n identify(_input: TelemetryIdentifyInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n group(_input: TelemetryGroupInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reset(): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reportHandledError(\n _error: CapxulError,\n _context?: HandledErrorReportContext,\n ): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n clear(): void {\n this.#events.length = 0;\n }\n}\n\nexport class PostHogTelemetryAdapter implements TelemetryPort {\n readonly #capture: (name: string, props?: TelemetryProps) => void | Promise<void>;\n\n constructor(deps: {\n readonly capture: (name: string, props?: TelemetryProps) => void | Promise<void>;\n }) {\n this.#capture = deps.capture;\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never> {\n return Effect.sync(() => {\n try {\n void Promise.resolve(\n this.#capture(event.name, redactTelemetryProps(event.name, event.props)),\n ).catch(() => {});\n } catch {}\n });\n }\n\n identify(_input: TelemetryIdentifyInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n group(_input: TelemetryGroupInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reset(): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reportHandledError(\n _error: CapxulError,\n _context?: HandledErrorReportContext,\n ): Effect.Effect<void, never> {\n return Effect.void;\n }\n}\n\nexport class InMemoryTelemetryBusAdapter implements TelemetryPort {\n readonly #subscribers = new Set<(event: TelemetryEvent) => void>();\n readonly #rawMode: boolean;\n\n constructor(options: TelemetryRedactionOptions = {}) {\n this.#rawMode = options.rawMode === true;\n }\n\n subscribe(handler: (event: TelemetryEvent) => void): () => void {\n this.#subscribers.add(handler);\n return () => {\n this.#subscribers.delete(handler);\n };\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never> {\n return Effect.sync(() => {\n const delivered = redactTelemetryEvent(event, { rawMode: this.#rawMode });\n for (const handler of this.#subscribers) {\n try {\n handler(cloneEvent(delivered));\n } catch {\n /* fire-and-forget */\n }\n }\n });\n }\n\n identify(_input: TelemetryIdentifyInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n group(_input: TelemetryGroupInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reset(): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reportHandledError(\n _error: CapxulError,\n _context?: HandledErrorReportContext,\n ): Effect.Effect<void, never> {\n return Effect.void;\n }\n}\n\nconst PII_PROP_KEYS_BY_EVENT: Partial<Record<TelemetryEventName, readonly string[]>> = {\n auth_otp_requested: [\"email\"],\n auth_otp_delivered: [\"email\"],\n auth_otp_expired: [\"email\"],\n auth_failed: [\"email\"],\n};\n\nfunction redactProperty(props: TelemetryProps, key: string): void {\n const value = props[key];\n if (typeof value === \"string\") {\n props[key] = sha256Hex(value).slice(0, 12);\n }\n}\n\nfunction cloneEvent(event: TelemetryEvent): TelemetryEvent {\n if (event.props === undefined) {\n return { name: event.name };\n }\n\n return {\n name: event.name,\n props: cloneProps(event.props),\n };\n}\n\nfunction cloneProps(props: TelemetryProps): TelemetryProps {\n const cloned: TelemetryProps = {};\n for (const [key, value] of Object.entries(props)) {\n cloned[key] = cloneTelemetryValue(value);\n }\n return cloned;\n}\n\nfunction cloneTelemetryValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(cloneTelemetryValue);\n if (value === null || typeof value !== \"object\") return value;\n if (Object.getPrototypeOf(value) !== Object.prototype) return value;\n const cloned: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n cloned[key] = cloneTelemetryValue(nested);\n }\n return cloned;\n}\n\nconst SHA256_INITIAL_HASH: readonly number[] = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n] as const;\n\nconst SHA256_K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n] as const;\n\nfunction sha256Hex(input: string): string {\n const bytes = new TextEncoder().encode(input);\n const padded = padSha256Message(bytes);\n const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n const words = new Uint32Array(64);\n let h0 = SHA256_INITIAL_HASH[0]!;\n let h1 = SHA256_INITIAL_HASH[1]!;\n let h2 = SHA256_INITIAL_HASH[2]!;\n let h3 = SHA256_INITIAL_HASH[3]!;\n let h4 = SHA256_INITIAL_HASH[4]!;\n let h5 = SHA256_INITIAL_HASH[5]!;\n let h6 = SHA256_INITIAL_HASH[6]!;\n let h7 = SHA256_INITIAL_HASH[7]!;\n\n for (let offset = 0; offset < padded.byteLength; offset += 64) {\n for (let i = 0; i < 16; i++) {\n words[i] = view.getUint32(offset + i * 4);\n }\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(words[i - 15]!, 7) ^ rotr(words[i - 15]!, 18) ^ (words[i - 15]! >>> 3);\n const s1 = rotr(words[i - 2]!, 17) ^ rotr(words[i - 2]!, 19) ^ (words[i - 2]! >>> 10);\n words[i] = (words[i - 16]! + s0 + words[i - 7]! + s1) >>> 0;\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n let f = h5;\n let g = h6;\n let h = h7;\n\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const ch = (e & f) ^ (~e & g);\n const temp1 = (h + s1 + ch + SHA256_K[i]! + words[i]!) >>> 0;\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const maj = (a & b) ^ (a & c) ^ (b & c);\n const temp2 = (s0 + maj) >>> 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + temp1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temp1 + temp2) >>> 0;\n }\n\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n h5 = (h5 + f) >>> 0;\n h6 = (h6 + g) >>> 0;\n h7 = (h7 + h) >>> 0;\n }\n\n return [h0, h1, h2, h3, h4, h5, h6, h7]\n .map((word) => word.toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n\nfunction padSha256Message(bytes: Uint8Array): Uint8Array {\n const bitLength = bytes.byteLength * 8;\n const zeroPadLength = (64 - ((bytes.byteLength + 1 + 8) % 64)) % 64;\n const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);\n output.set(bytes);\n output[bytes.byteLength] = 0x80;\n\n const view = new DataView(output.buffer);\n view.setUint32(output.byteLength - 8, Math.floor(bitLength / 0x100000000));\n view.setUint32(output.byteLength - 4, bitLength >>> 0);\n return output;\n}\n\nfunction rotr(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits));\n}\n"],"mappings":";AC0BkD,IAAI,IAAI;CDpBxD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;ACLwD,CAAkB;;;ACgH5E,MAAa,iBAAiB;AAC9B,MAAa,aAAa;AAE1B,MAAa,uBAAuB;CAClC;EAAE,MAAM;EAAO,QAAQ;EAAK,MAAM;CAAY;CAC9C;EAAE,MAAM;EAAO,QAAQ;EAAO,MAAM;CAAiB;CACrD;EAAE,MAAM;EAAO,Q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